first commit

This commit is contained in:
Roman Pyrih
2023-07-24 08:30:51 +02:00
commit c2e100a763
7128 changed files with 1622619 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
BUILD_ENVIRONMENT=fixes
FREE_BRANCH=fixes-2.2.8
PRO_BRANCH=fixes-2.2.5
EDITOR_BRANCH=fixes-170

View File

@@ -0,0 +1,59 @@
name: Brizy Free
on:
push:
branches:
- master
- beta-*
- fixes-*
- develop
jobs:
base:
environment: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: '1'
- name: Load Build Evnrorment Data
uses: falti/dotenv-action@master
id: env
with:
path: .github/.build-env
- name: Declare some variables
id: vars
shell: bash
run: |
echo "::set-output name=sha_short::$(git rev-parse --short HEAD)"
- name: Intialize the containers
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.KEY }}
port: ${{ secrets.PORT }}
command_timeout: 200m
passphrase: ${{ secrets.KEY_PASSPHRASE }}
script: |
./BB/build/run-editor-instance.sh \
-c ${{ steps.vars.outputs.sha_short }} \
-v ${{ steps.env.outputs.build_environment }} \
-f ${{ steps.env.outputs.free_branch }} \
-p ${{ steps.env.outputs.pro_branch }} \
-e ${{ steps.env.outputs.editor_branch }} \
-n traefik \
-t ${{ secrets.COMPOSER_TOKEN }}
- name: Clean context folder
uses: appleboy/ssh-action@master
if: ${{ always() }}
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.KEY }}
port: ${{ secrets.PORT }}
command_timeout: 200m
passphrase: ${{ secrets.KEY_PASSPHRASE }}
script:
./BB/build/clean-context-folder.sh -c ${{ steps.vars.outputs.sha_short }}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
<?php
/**
* Class Brizy_Admin_AbstractApi
*/
abstract class Brizy_Admin_AbstractApi {
abstract protected function initializeApiActions();
abstract protected function getRequestNonce();
/**
* Brizy_Admin_AbstractApi constructor.
*/
public function __construct() {
$this->initializeApiActions();
}
/**
* @param $action
*/
protected function verifyNonce( $action ) {
$version = $this->param( 'version' );
if ( $version !== BRIZY_EDITOR_VERSION ) {
Brizy_Logger::instance()->critical( 'Request with invalid version',
[
'editorVersion' => BRIZY_EDITOR_VERSION,
'providedVersion' => $version
] );
$this->error( 400, "Invalid editor version. Please refresh the page and try again" );
}
if ( ! wp_verify_nonce( $this->getRequestNonce(), $action ) ) {
Brizy_Logger::instance()->error( 'Invalid request nonce', $_REQUEST );
$this->error( 400, "Bad request" );
}
}
/**
* @param $name
*
* @return null
*/
protected function param( $name ) {
if ( isset( $_REQUEST[ $name ] ) ) {
return $_REQUEST[ $name ];
}
return null;
}
/**
* @param $code
* @param $message
*/
protected function error( $code, $message ) {
wp_send_json_error( $message, $code );
}
/**
* @param $data
*/
protected function success( $data ) {
wp_send_json_success( $data );
}
}

View File

@@ -0,0 +1,32 @@
<?php
abstract class Brizy_Admin_AbstractWidget {
abstract public function getId();
abstract public function getName();
abstract public function render();
/**
* Brizy_Admin_AbstractWidget constructor.
* @throws Exception
*/
public function __construct() {
wp_add_dashboard_widget( $this->internalGetId(), $this->getName(), array( $this, 'render' ) );
}
/**
* @return string
* @throws Exception
*/
protected function internalGetId() {
$id = $this->getId();
if ( empty( $id ) ) {
throw new Exception( 'You should return an Id for the widget' );
}
return Brizy_Editor::get_slug() . '_' . $id;
}
}

View File

@@ -0,0 +1,753 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 7/18/18
* Time: 10:48 AM
*/
class Brizy_Admin_Blocks_Api extends Brizy_Admin_AbstractApi {
const nonce = 'brizy-api';
const GET_SAVED_BLOCK_ACTION = '-get-saved-block';
const GET_GLOBAL_BLOCKS_ACTION = '-get-global-blocks';
const GET_SAVED_BLOCKS_ACTION = '-get-saved-blocks';
const CREATE_GLOBAL_BLOCK_ACTION = '-create-global-block';
const CREATE_SAVED_BLOCK_ACTION = '-create-saved-block';
const UPDATE_GLOBAL_BLOCK_ACTION = '-update-global-block';
const UPDATE_GLOBAL_BLOCKS_ACTION = '-update-global-blocks';
const UPDATE_SAVED_BLOCK_ACTION = '-saved-global-block';
const DELETE_GLOBAL_BLOCK_ACTION = '-delete-global-block';
const DELETE_SAVED_BLOCK_ACTION = '-delete-saved-block';
const UPDATE_POSITIONS_ACTION = '-update-block-positions';
const DOWNLOAD_BLOCKS = '-download-blocks';
const UPLOAD_BLOCKS = '-upload-blocks';
/**
* @var Brizy_Admin_Rules_Manager
*/
private $ruleManager;
/**
* @return Brizy_Admin_Blocks_Api
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self( new Brizy_Admin_Rules_Manager() );
}
return $instance;
}
/**
* Brizy_Admin_Blocks_Api constructor.
*
* @param Brizy_Admin_Rules_Manager $ruleManager
*/
public function __construct( $ruleManager ) {
$this->ruleManager = $ruleManager;
parent::__construct();
}
protected function getRequestNonce() {
return $this->param( 'hash' );
}
protected function initializeApiActions() {
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
add_action( $pref . self::DOWNLOAD_BLOCKS, array( $this, 'actionDownloadBlocks' ) );
add_action( $pref . self::UPLOAD_BLOCKS, array( $this, 'actionUploadBlocks' ) );
add_action( $pref . self::GET_GLOBAL_BLOCKS_ACTION, array( $this, 'actionGetGlobalBlocks' ) );
add_action( $pref . self::CREATE_GLOBAL_BLOCK_ACTION, array( $this, 'actionCreateGlobalBlock' ) );
add_action( $pref . self::UPDATE_GLOBAL_BLOCK_ACTION, array( $this, 'actionUpdateGlobalBlock' ) );
add_action( $pref . self::UPDATE_GLOBAL_BLOCKS_ACTION, array( $this, 'actionUpdateGlobalBlocks' ) );
add_action( $pref . self::DELETE_GLOBAL_BLOCK_ACTION, array( $this, 'actionDeleteGlobalBlock' ) );
add_action( $pref . self::GET_SAVED_BLOCKS_ACTION, array( $this, 'actionGetSavedBlocks' ) );
add_action( $pref . self::GET_SAVED_BLOCK_ACTION, array( $this, 'actionGetSavedBlockByUid' ) );
add_action( $pref . self::UPDATE_SAVED_BLOCK_ACTION, array( $this, 'actionUpdateSavedBlock' ) );
add_action( $pref . self::CREATE_SAVED_BLOCK_ACTION, array( $this, 'actionCreateSavedBlock' ) );
add_action( $pref . self::DELETE_SAVED_BLOCK_ACTION, array( $this, 'actionDeleteSavedBlock' ) );
add_action( $pref . self::UPDATE_POSITIONS_ACTION, array( $this, 'actionUpdateBlockPositions' ) );
}
public function actionDownloadBlocks() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( 400, 'Invalid block uid param' );
}
try {
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$uids = [];
// this is not a very eficien solution if you have a big array of uids
$explode = explode( ',', $this->param( 'uid' ) );
$items = array_map( function ( $auid ) use ( $uids, $bockManager ) {
list( $uid, $isPro ) = explode( ':', $auid );
$uids[] = $uid;
$item = new Brizy_Editor_Zip_ArchiveItem( $uid, $isPro );
if ( $post = $bockManager->getEntity( $uid ) ) {
$item->setPost( $post );
return $item;
}
return null;
}, $explode );
$items = array_filter( $items );
if ( count( $items ) == 0 ) {
$this->error( 404, __( 'There are no block to be archived' ) );
}
$fontManager = new Brizy_Admin_Fonts_Manager();
$zip = new Brizy_Editor_Zip_Archiver( Brizy_Editor_Project::get(), $fontManager, BRIZY_EDITOR_VERSION );
switch ( $this->param( 'type' ) ) {
case 'popup':
$zipPath = "Popup-" . date( DATE_ATOM ) . ".zip";
break;
default:
$zipPath = "Block-" . date( DATE_ATOM ) . ".zip";
break;
}
$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-Transfer-Encoding: binary" );
echo file_get_contents( $zipPath );
exit;
} catch ( Exception $exception ) {
$this->error( 400, __( $exception->getMessage(), 'brizy' ) );
}
}
public function actionUploadBlocks() {
try {
$this->verifyNonce( self::nonce );
if ( ! isset( $_FILES['files'] ) ) {
$this->error( 400, __( 'Invalid block file' ) );
}
$fields = $this->param( 'fields' ) ? $this->param( 'fields' ) : [];
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$file = [
'name' => $_FILES['files']['name'][0],
'type' => $_FILES['files']['type'][0],
'tmp_name' => $_FILES['files']['tmp_name'][0],
'error' => $_FILES['files']['error'][0],
'size' => $_FILES['files']['size'][0],
];
$uploadedFile = wp_handle_upload( $file, [ 'test_form' => false ] );
if ( isset( $uploadedFile['file'] ) ) {
$zip = new Brizy_Editor_Zip_Archiver( Brizy_Editor_Project::get(),
new Brizy_Admin_Fonts_Manager(),
BRIZY_EDITOR_VERSION );
list( $instances, $errors ) = $zip->createFromZip( $uploadedFile['file'] );
unset( $uploadedFile['file'] );
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$this->success( [
'success' => $bockManager->createResponseForEntities( $instances, $fields ),
'errors' => $errors
] );
} else {
if ( isset( $uploadedFile['error'] ) ) {
$this->error( 400, $uploadedFile['error'] );
} else {
$this->error( 400, __( "Invalid zip file provided" ) );
}
}
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionGetGlobalBlocks() {
$this->verifyNonce( self::nonce );
try {
$fields = $this->param( 'fields' ) ? $this->param( 'fields' ) : [];
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_GLOBAL );
$blocks = $bockManager->getEntities( ['post_status'=>'any'] );
$this->success( $bockManager->createResponseForEntities( $blocks, $fields ) );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionCreateGlobalBlock() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( 400, 'Invalid uid' );
}
if ( ! $this->param( 'data' ) ) {
$this->error( 400, 'Invalid data' );
}
if ( ! $this->param( 'meta' ) ) {
$this->error( 400, 'Invalid meta data' );
}
try {
$editorData = stripslashes( $this->param( 'data' ) );
$position = stripslashes( $this->param( 'position' ) );
$status = stripslashes( $this->param( 'status' ) );
$rulesData = stripslashes( $this->param( 'rules' ) );
if ( ! in_array( $status, [ 'publish', 'draft' ] ) ) {
$this->error( 400, "Invalid status" );
}
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_GLOBAL );
$block = $bockManager->createEntity( $this->param( 'uid' ), $status );
$block->setMeta( stripslashes( $this->param( 'meta' ) ) );
$block->set_editor_data( $editorData );
$block->set_needs_compile( true );
if ( $position ) {
$block->setPosition( Brizy_Editor_BlockPosition::createFromSerializedData( get_object_vars( json_decode( $position ) ) ) );
}
// rules
if ( $rulesData ) {
$rules = $this->ruleManager->createRulesFromJson( $rulesData, Brizy_Admin_Blocks_Main::CP_GLOBAL );
$this->ruleManager->addRules( $block->getWpPostId(), $rules );
}
$block->save();
do_action( 'brizy_global_block_created', $block );
do_action( 'brizy_global_data_updated' );
$this->success( $block->createResponse() );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionUpdateGlobalBlock() {
$this->verifyNonce( self::nonce );
try {
if ( ! $this->param( 'uid' ) ) {
$this->error( '400', 'Invalid uid' );
}
if ( ! $this->param( 'data' ) ) {
$this->error( '400', 'Invalid data' );
}
if ( ! $this->param( 'meta' ) ) {
$this->error( 400, 'Invalid meta data' );
}
$status = stripslashes( $this->param( 'status' ) );
if ( ! in_array( $status, [ 'publish', 'draft' ] ) ) {
$this->error( 400, "Invalid post type" );
}
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_GLOBAL );
$block = $bockManager->getEntity( $this->param( 'uid' ) );
if ( ! $block ) {
$this->error( 400, "Global block not found" );
}
/**
* @var Brizy_Editor_Block $block ;
*/
$block->setMeta( stripslashes( $this->param( 'meta' ) ) );
$block->set_editor_data( stripslashes( $this->param( 'data' ) ) );
if ( (int) $this->param( 'is_autosave' ) ) {
$block->save( 1 );
} else {
// issue: #14271
//$block->setDataVersion( $this->param( 'dataVersion' ) );
$block->getWpPost()->post_status = $status;
// position
$position = stripslashes( $this->param( 'position' ) );
if ( $position ) {
$block->setPosition( Brizy_Editor_BlockPosition::createFromSerializedData( get_object_vars( json_decode( $position ) ) ) );
}
// rules
$rulesData = stripslashes( $this->param( 'rules' ) );
if ( $rulesData ) {
$rules = $this->ruleManager->createRulesFromJson( $rulesData, Brizy_Admin_Blocks_Main::CP_GLOBAL );
$this->ruleManager->setRules( $block->getWpPostId(), $rules );
}
$block->save( 0 );
do_action( 'brizy_global_block_updated', $block );
do_action( 'brizy_global_data_updated' );
}
Brizy_Editor_Block::cleanClassCache();
$this->success( Brizy_Editor_Block::get( $block->getWpPostId() )->createResponse() );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionUpdateGlobalBlocks() {
//$this->verifyNonce( self::nonce );
try {
if ( ! $this->param( 'uid' ) ) {
$this->success( [] );
}
foreach ( (array) $this->param( 'uid' ) as $i => $uid ) {
if ( ! $this->param( 'uid' )[ $i ] ) {
$this->error( '400', 'Invalid uid' );
}
// if ( ! $this->param( 'data' )[ $i ] ) {
// $this->error( '400', 'Invalid data' );
// }
if ( ! $this->param( 'meta' )[ $i ] ) {
$this->error( 400, 'Invalid meta data' );
}
$status = stripslashes( $this->param( 'status' )[ $i ] );
if ( ! in_array( $status, [ 'publish', 'draft' ] ) ) {
$this->error( 400, "Invalid post type" );
}
}
$blocks = [];
foreach ( (array) $this->param( 'uid' ) as $i => $uid ) {
$status = stripslashes( $this->param( 'status' )[ $i ] );
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_GLOBAL );
$block = $bockManager->getEntity( $this->param( 'uid' )[ $i ] );
if ( ! $block ) {
$this->error( 400, "Global block not found" );
}
/**
* @var Brizy_Editor_Block $block ;
*/
$block->setMeta( stripslashes( $this->param( 'meta' )[ $i ] ) );
if ( isset( $this->param( 'data' )[ $i ] ) && ! empty( $this->param( 'data' )[ $i ] ) ) {
$block->set_editor_data( stripslashes( $this->param( 'data' )[ $i ] ) );
}
if ( isset( $this->param( 'is_autosave' )[ $i ] ) && (int) $this->param( 'is_autosave' )[ $i ] === 1 ) {
$block->save( 1 );
} else {
// issue: #14271
//$block->setDataVersion( $this->param( 'dataVersion' )[ $i ] );
$block->getWpPost()->post_status = $status;
// position
$position = stripslashes( $this->param( 'position' )[ $i ] );
if ( $position && ( $positionObject = json_decode( $position ) ) ) {
$block->setPosition( Brizy_Editor_BlockPosition::createFromSerializedData( get_object_vars( $positionObject ) ) );
}
// rules
$rulesData = stripslashes( $this->param( 'rules' )[ $i ] );
if ( $rulesData ) {
$rules = $this->ruleManager->createRulesFromJson( $rulesData,
Brizy_Admin_Blocks_Main::CP_GLOBAL );
$this->ruleManager->setRules( $block->getWpPostId(), $rules );
}
$block->save( 0 );
do_action( 'brizy_global_block_updated', $block );
$blocks[] = $block;
}
}
do_action( 'brizy_global_data_updated' );
Brizy_Editor_Block::cleanClassCache();
$response = [];
foreach ( $blocks as $block ) {
$response[] = Brizy_Editor_Block::get( $block->getWpPostId() )->createResponse();
}
$this->success( $response );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionDeleteGlobalBlock() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( '400', 'Invalid uid' );
}
$block = $this->getBlock( $this->param( 'uid' ), Brizy_Admin_Blocks_Main::CP_GLOBAL );
if ( $block ) {
do_action( 'brizy_global_block_deleted', $block );
do_action( 'brizy_global_data_deleted' );
$this->deleteBlock( $block, Brizy_Admin_Blocks_Main::CP_GLOBAL );
$this->success( null );
}
$this->error( '404', 'Block not found' );
}
public function actionGetSavedBlocks() {
$this->verifyNonce( self::nonce );
try {
$fields = $this->param( 'fields' ) ? $this->param( 'fields' ) : [];
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$blocks = $bockManager->getEntities( [] );
$blocks = apply_filters( 'brizy_get_saved_blocks',
$bockManager->createResponseForEntities( $blocks, $fields ),
$fields,
$bockManager );
$this->success( $blocks );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionGetSavedBlockByUid() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( 400, 'Invalid uid' );
}
$fields = $this->param( 'fields' ) ? $this->param( 'fields' ) : [];
try {
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$block = $bockManager->getEntity( $this->param( 'uid' ) );
$block = apply_filters( 'brizy_get_saved_block', $block, $this->param( 'uid' ), $bockManager );
if ( ! $block ) {
$this->error( 404, 'Block not found' );
}
$this->success( $block->createResponse( $fields ) );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionCreateSavedBlock() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( 400, 'Invalid uid' );
}
if ( ! $this->param( 'data' ) ) {
$this->error( 400, 'Invalid data' );
}
if ( ! $this->param( 'meta' ) ) {
$this->error( 400, 'Invalid meta data' );
}
if ( ! $this->param( 'media' ) ) {
$this->error( 400, 'Invalid media data provided' );
}
try {
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$block = $bockManager->createEntity( $this->param( 'uid' ) );
$block->setMedia( stripslashes( $this->param( 'media' ) ) );
$block->setMeta( stripslashes( $this->param( 'meta' ) ) );
$block->set_editor_data( stripslashes( $this->param( 'data' ) ) );
$block->set_needs_compile( true );
//$block->setCloudUpdateRequired( true );
$block->save();
do_action( 'brizy_saved_block_created', $block );
do_action( 'brizy_global_data_updated' );
$this->success( $block->createResponse() );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionUpdateSavedBlock() {
$this->verifyNonce( self::nonce );
try {
if ( ! $this->param( 'uid' ) ) {
$this->error( '400', 'Invalid uid' );
}
if ( ! $this->param( 'data' ) ) {
$this->error( '400', 'Invalid data' );
}
if ( $this->param( 'dataVersion' ) === null ) {
$this->error( '400', 'Invalid data version' );
}
if ( ! $this->param( 'meta' ) ) {
$this->error( 400, 'Invalid meta data' );
}
if ( ! $this->param( 'media' ) ) {
$this->error( 400, 'Invalid media data provided' );
}
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$block = $bockManager->getEntity( $this->param( 'uid' ) );
if ( ! $block instanceof Brizy_Editor_Block ) {
$this->error( '404', 'Block not found' );
}
$block->set_editor_data( stripslashes( $this->param( 'data' ) ) );
$block->setDataVersion( $this->param( 'dataVersion' ) );
$block->setMedia( stripslashes( $this->param( 'media' ) ) );
$block->setMeta( stripslashes( $this->param( 'meta' ) ) );
if ( (int) $this->param( 'is_autosave' ) ) {
$block->save( 1 );
} else {
$block->save();
do_action( 'brizy_saved_block_updated', $block );
do_action( 'brizy_global_data_updated' );
}
Brizy_Editor_Block::cleanClassCache();
$this->success( Brizy_Editor_Block::get( $block->getWpPostId() )->createResponse() );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionDeleteSavedBlock() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( '400', 'Invalid uid' );
}
try {
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_SAVED );
$block = $bockManager->getEntity( $this->param( 'uid' ) );
do_action( 'brizy_saved_block_delete', $this->param( 'uid' ) );
if ( $block ) {
do_action( 'brizy_global_data_deleted' );
$bockManager->deleteEntity( $block );
} else {
$this->error( '404', 'Block not found' );
}
} catch ( Exception $e ) {
$this->error( '500', 'Unable to delete block' );
}
$this->success( null );
}
public function actionUpdateBlockPositions() {
global $wpdb;
$this->verifyNonce( self::nonce );
$data = file_get_contents( "php://input" );
$dataObject = json_decode( $data );
if ( ! $dataObject ) {
$this->error( 400, 'Invalid position data provided' );
}
$wpdb->query( 'START TRANSACTION' );
try {
foreach ( get_object_vars( $dataObject ) as $uid => $position ) {
if ( ! ( isset( $position->top ) && isset( $position->bottom ) && isset( $position->align ) ) ) {
throw new Exception();
}
$positionObj = new Brizy_Editor_BlockPosition( $position->top, $position->bottom, $position->align );
$bockManager = new Brizy_Admin_Blocks_Manager( Brizy_Admin_Blocks_Main::CP_GLOBAL );
$block = $bockManager->getEntity( $uid );
if ( ! $block ) {
throw new Exception();
}
$block->setPosition( $positionObj );
if ( $this->param( 'is_autosave' ) == 1 ) {
$block->save( 1 );
} else {
$block->saveStorage();
}
do_action( 'brizy_global_block_updated', $block );
}
do_action( 'brizy_global_data_updated' );
$wpdb->query( 'COMMIT' );
} catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' );
$this->error( '400', 'Unable to save block positions' );
}
$this->success( json_encode( $dataObject ) );
}
/**
* @param $uid
* @param $postType
*
* @return string|null
*/
private function getBlockIdByUidAndBlockType( $uid, $postType ) {
global $wpdb;
$prepare = $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm ON
pm.post_id=p.ID and
meta_key='brizy_post_uid' and
meta_value='%s'
WHERE p.post_type IN ('%s')
ORDER BY p.ID DESC
LIMIT 1",
array( $uid, $postType ) );
return $wpdb->get_var( $prepare );
}
/**
* @param $uid
* @param $postType
*
* @return string|null
*/
private function getBlockIdByUid( $uid ) {
global $wpdb;
$prepare = $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} pm ON pm.post_id=p.ID and meta_key='brizy_post_uid' and meta_value='%s'
WHERE p.post_type <> 'attachment'
ORDER BY p.ID DESC
LIMIT 1",
array( $uid, ) );
return $wpdb->get_var( $prepare );
}
/**
* @param $id
* @param $postType
*
* @return Brizy_Editor_Block|null
* @throws Brizy_Editor_Exceptions_NotFound
*/
private function getBlock( $id, $postType ) {
$postId = $this->getBlockIdByUidAndBlockType( $id, $postType );
if ( $postId ) {
return Brizy_Editor_Block::get( $postId );
}
return null;
}
/**
* @param $uid
* @param $status
* @param $type
*
* @return Brizy_Editor_Block
* @throws Brizy_Editor_Exceptions_NotFound
*/
private function createBlock( $uid, $status, $type ) {
$name = md5( time() );
$post = wp_insert_post( array(
'post_title' => $name,
'post_name' => $name,
'post_status' => $status,
'post_type' => $type,
) );
if ( $post ) {
$brizyPost = Brizy_Editor_Block::get( $post, $uid );
$brizyPost->set_uses_editor( true );
$brizyPost->set_needs_compile( true );
$brizyPost->setDataVersion( 1 );
return $brizyPost;
}
throw new Exception( 'Unable to create block' );
}
/**
* @param $postUid
* @param $postType
*
* @return false|WP_Post|null
*/
private function deleteBlock( $block, $postType ) {
if ( $postType === Brizy_Admin_Blocks_Main::CP_SAVED ) {
}
return wp_delete_post( $block->getWpPostId() );
}
}

View File

@@ -0,0 +1,150 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/11/19
* Time: 10:59 AM
*/
class Brizy_Admin_Blocks_Main {
const CP_GLOBAL = 'brizy-global-block';
const CP_SAVED = 'brizy-saved-block';
/**
* @return Brizy_Admin_Blocks_Main
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* BrizyPro_Admin_Popups constructor.
*/
public function __construct() {
if ( Brizy_Editor_User::is_user_allowed() ) {
add_action( 'wp_loaded', array( $this, 'initializeActions' ) );
}
add_filter( 'brizy_global_data', array( $this, 'populateGlobalData' ) );
}
/**
* Populated the global data for compiler
*
* @param $globalData
*
* @return mixed
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function populateGlobalData( $globalData ) {
if ( ! is_object( $globalData ) ) {
$globalData = (object) array( 'globalBlocks' => array(), 'savedBlocks' => array() );
}
$blocks = get_posts( array(
'post_type' => Brizy_Admin_Blocks_Main::CP_GLOBAL,
'posts_per_page' => - 1,
'post_status' => 'publish',
'orderby' => 'ID',
'order' => 'ASC',
) );
foreach ( $blocks as $block ) {
$brizy_editor_block = Brizy_Editor_Block::get( $block );
$uid = $brizy_editor_block->getUid();
$block_data = $brizy_editor_block->convertToOptionValue();
$globalData->globalBlocks[ $uid ] = array(
'data' => json_decode( $brizy_editor_block->get_editor_data() ),
'position' => $block_data['position'],
'rules' => $block_data['rules']
);
}
$blocks = get_posts( array(
'post_type' => Brizy_Admin_Blocks_Main::CP_SAVED,
'posts_per_page' => - 1,
'post_status' => 'publish',
'orderby' => 'ID',
'order' => 'ASC',
) );
foreach ( $blocks as $block ) {
$brizy_editor_block = Brizy_Editor_Block::get( $block );
$block_data = $brizy_editor_block->convertToOptionValue();
$globalData->savedBlocks[] = array(
'data' => json_decode( $brizy_editor_block->get_editor_data() ),
'rules' => $block_data['rules']
);
}
return $globalData;
}
public function initializeActions() {
Brizy_Admin_Blocks_Api::_init();
}
static public function registerCustomPosts() {
$labels = array(
'name' => _x( 'Global blocks', 'post type general name' ),
);
register_post_type( self::CP_GLOBAL,
array(
'labels' => $labels,
'public' => false,
'has_archive' => false,
'description' => __bt( 'brizy', 'Brizy' ) . ' ' . __( 'global block.', 'brizy' ),
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => false,
'capability_type' => 'page',
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'supports' => array( 'title', 'revisions', 'page-attributes' )
)
);
$labels = array(
'name' => _x( 'Saved blocks', 'brizy' ),
);
register_post_type( self::CP_SAVED,
array(
'labels' => $labels,
'public' => false,
'has_archive' => false,
'description' => __bt( 'brizy', 'Brizy' ) . ' ' . __( 'global block.' ),
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => false,
'capability_type' => 'page',
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'supports' => array( 'title', 'revisions', 'page-attributes' )
)
);
add_filter( 'brizy_supported_post_types', function ( $posts ) {
$posts[] = self::CP_SAVED;
$posts[] = self::CP_GLOBAL;
return $posts;
} );
}
}

View File

@@ -0,0 +1,202 @@
<?php
class Brizy_Admin_Blocks_Manager extends Brizy_Admin_Entity_AbstractManager {
/**
* @var
*/
private $blockType;
/**
* Brizy_Admin_Blocks_Manager constructor.
*
* @param $type
*
* @throws Exception
*/
public function __construct( $type ) {
if ( ! in_array( $type, [ Brizy_Admin_Blocks_Main::CP_GLOBAL, Brizy_Admin_Blocks_Main::CP_SAVED ] ) ) {
throw new Exception();
}
$this->blockType = $type;
}
/**
* @param $args
*
* @return Brizy_Editor_Block[]
* @throws Exception
*/
public function getEntities( $args ) {
return $this->getEntitiesByType( $this->blockType, $args );
}
/**
* @param $uid
*
* @return Brizy_Editor_Block
* @throws Exception
*/
public function getEntity( $uid ) {
return $this->getEntityUidAndType( $uid, $this->blockType );
}
/**
* @param $uid
* @param string $status
*
* @return mixed|null+
*/
public function createEntity( $uid, $status = 'publish' ) {
return $this->createEntityByType( $uid, $this->blockType, $status );
}
/**
* @param $post
* @param null $uid
*
* @return Brizy_Editor_Block|Brizy_Editor_Post|mixed$uid
* @throws Exception
*/
protected function convertWpPostToEntity( $post, $uid = null ) {
return Brizy_Editor_Block::get( $post, $uid );
}
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
/**
* @param $type
* @param $arags
* @param array $fields
*
* @return array
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function getAllBlocks( $type, $arags, $fields = array() ) {
$blocks = $this->getLocalBlocks( $type, $arags, $fields );
try {
$versions = $this->cloud->getCloudEditorVersions();
if ( $this->cloud && $type == Brizy_Admin_Blocks_Main::CP_SAVED && $versions['sync'] == BRIZY_SYNC_VERSION ) {
$cloudBlocks = $this->cloud->getBlocks( array( 'fields' => $fields ) );
foreach ( (array) $cloudBlocks as $cblock ) {
$existingBlock = false;
foreach ( $blocks as $block ) {
if ( $cblock->uid == $block['uid'] ) {
$existingBlock = true;
}
}
if ( ! $existingBlock ) {
$localBlock = $this->getLocalBlock( Brizy_Admin_Blocks_Main::CP_SAVED, $cblock->uid );
if ( in_array( 'synchronized', $fields ) ) {
if ( $localBlock ) {
$cblock->synchronized = $localBlock->isSynchronized( $this->cloud->getBrizyProject()->getCloudAccountId() );
} else {
$cblock->synchronized = false;
}
}
if ( in_array( 'isCloudEntity', $fields ) ) {
$cblock->isCloudEntity = true;
}
if ( in_array( 'synchronizable', $fields ) ) {
$cblock->synchronizable = true;
}
$blocks[] = (array) $cblock;
}
}
}
} catch ( Exception $e ) {
// do nothing...
}
return $blocks;
}
public function getBlockByUid( $type, $uid ) {
$block = $this->getLocalBlock( $type, $uid );
$versions = $this->cloud->getCloudEditorVersions();
if ( ! $block && $this->cloud && $type == Brizy_Admin_Blocks_Main::CP_SAVED && $versions['sync'] == BRIZY_SYNC_VERSION ) {
$bridge = new Brizy_Admin_Cloud_BlockBridge( $this->cloud );
$bridge->import( $uid );
$block = $this->getLocalBlock( $type, $uid );
}
return $block;
}
/**
* @param $type
* @param array $arags
* @param array $fields
*
* @return array
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function getLocalBlocks( $type, $arags = array(), $fields = array() ) {
$filterArgs = array(
'post_type' => $type,
'posts_per_page' => - 1,
'post_status' => 'any',
'orderby' => 'ID',
'order' => 'ASC',
);
$filterArgs = array_merge( $filterArgs, $arags );
$wpBlocks = get_posts( $filterArgs );
$blocks = array();
foreach ( $wpBlocks as $wpPost ) {
$blocks[] = Brizy_Editor_Block::get( $wpPost )->createResponse( $fields );
}
return $blocks;
}
/**
* @param $type
* @param $uid
*
* @return array|null
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function getLocalBlock( $type, $uid ) {
$blocks = get_posts( array(
'post_type' => $type,
'post_status' => 'publish',
'meta_key' => 'brizy_post_uid',
'meta_value' => $uid,
'numberposts' => - 1,
'orderby' => 'ID',
'order' => 'DESC',
) );
if ( isset( $blocks[0] ) ) {
$block = \Brizy_Editor_Block::get( $blocks[0] )->createResponse();
} else {
$block = null;
}
return $block;
}
}

View File

@@ -0,0 +1,60 @@
<?php
class Brizy_Admin_Capabilities {
/**
* @var Brizy_Editor_Storage_Common
*/
private $storage;
const CAP_EDIT_WHOLE_PAGE = 'brizy_edit_whole_page';
const CAP_EDIT_CONTENT_ONLY = 'brizy_edit_content_only';
/**
* Brizy_Admin_Capabilities constructor.
*
* @param $common_storage
*
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function __construct( $common_storage ) {
$this->storage = $common_storage;
$are_capabilities_created = $common_storage->get( 'capabilities_created', false );
if ( ! $are_capabilities_created ) {
$this->create_capabilities();
$common_storage->set( 'capabilities_created', 1 );
$this->storage->delete( 'exclude-roles' );
}
}
/**
* @throws Brizy_Editor_Exceptions_NotFound
*/
private function create_capabilities() {
global $wp_roles;
// add capability to adiministrator
$wp_roles->add_cap( 'administrator', self::CAP_EDIT_WHOLE_PAGE );
$roles = Brizy_Admin_Settings::get_role_list();
$old_explude = $this->storage->get( 'exclude-roles', false );
$old_explude = is_array( $old_explude ) ? $old_explude : array();
foreach ( $roles as $role ) {
if ( $role['id'] == 'subscriber' ) {
continue;
}
if ( in_array( $role['id'], $old_explude ) ) {
$wp_roles->remove_cap( $role['id'], self::CAP_EDIT_WHOLE_PAGE );
continue;
}
$wp_roles->add_cap( $role['id'], self::CAP_EDIT_WHOLE_PAGE );
}
}
}

View File

@@ -0,0 +1,237 @@
<?php
class Brizy_Admin_Cloud {
// const PAGE_KEY = 'brizy-cloud';
// const GET_CLOUD_PROJECTS_ACTION = 'brizy-cloud-projects';
//
// static private $subpageId = null;
//
// /**
// * @var Brizy_TwigEngine
// */
// private $twig;
/**
* @var Brizy_Editor_Project
*/
private $project;
/**
* @var Brizy_Admin_Cloud_Client
*/
private $cloudClient;
/**
* @return Brizy_Admin_Cloud
* @throws Exception
*/
public static function _init() {
static $instance;
return $instance ? $instance : $instance = new self( Brizy_Editor_Project::get() );
}
/**
* Brizy_Admin_Cloud constructor.
*
* @param Brizy_Editor_Project $project
*
* @throws Exception
*/
private function __construct( Brizy_Editor_Project $project ) {
$this->project = $project;
$this->cloudClient = Brizy_Admin_Cloud_Client::instance( $project, new WP_Http() );
add_action( 'wp_loaded', array( $this, 'initializeActions' ) );
// add_action( 'wp_ajax_' . self::GET_CLOUD_PROJECTS_ACTION, array( $this, 'actionGetProjects' ) );
// add_action( 'admin_enqueue_scripts', array( $this, 'registersCloudAssets' ) );
// add_action( 'admin_menu', array( $this, 'actionRegisterCloutLoginPage' ), 11 );
//
// if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
// add_action( 'admin_init', array( $this, 'handleSubmit' ), 10 );
// }
//
// if ( isset( $_REQUEST['brizy-cloud-logout'] ) ) {
// add_action( 'admin_init', array( $this, 'handleLogout' ), 10 );
// }
//
// $this->twig = Brizy_TwigEngine::instance( BRIZY_PLUGIN_PATH . "/admin/views/cloud/" );
}
public function initializeActions() {
Brizy_Admin_Cloud_Api::_init( $this->project );
}
// public function registersCloudAssets() {
// $current_screen = get_current_screen();
// if ( $current_screen->id == self::$subpageId ) {
// wp_enqueue_script(
// Brizy_Editor::get()->get_slug() . '-cloud-js',
// Brizy_Editor::get()->get_url( 'admin/static/js/cloud.js' ),
// array( 'jquery' ),
// true
// );
// }
// }
//
// public function actionGetProjects() {
// $projects = $this->cloudClient->getProjects( array( 'container' => isset( $_REQUEST['container'] ) ? (int) $_REQUEST['container'] : null ) );
// wp_send_json_success( $projects );
// exit;
// }
//
// public function actionRegisterCloutLoginPage() {
// self::$subpageId = add_submenu_page( Brizy_Admin_Settings::menu_slug(),
// __( 'Cloud' ),
// __( 'Cloud' ),
// 'manage_options',
// self::menu_slug(),
// array( $this, 'render' )
// );
// }
// public function render() {
//
// $token = $this->project->getMetaValue( 'brizy-cloud-token' );
//
// if ( ! $token ) {
// $this->handleLoginPage();
// } else {
// $this->handleProjectPage();
// }
// }
// private function handleLoginPage() {
// $context = array(
// 'nonce' => wp_nonce_field( 'validate-cloud', '_wpnonce', true, false ),
// 'username' => '',
// 'password' => ''
// );
//
// echo $this->twig->render( 'cloud-login.html.twig', $context );
// }
// private function handleProjectPage() {
// $pageUrl = menu_page_url( self::menu_slug(), false );
// $containers = $this->cloudClient->getContainers();
// $project = $this->cloudClient->getProject( $this->project->getMetaValue( 'brizy-cloud-project' ) );
// $usedContainer = isset( $_REQUEST['container'] ) ? (int) $_REQUEST['container'] : ( isset( $containers[0] ) ? $containers[0]->id : null );
// $projects = $this->cloudClient->getProjects( array( 'container' => $usedContainer ) );
// $context = array(
// 'nonce' => wp_nonce_field( 'validate-cloud', '_wpnonce', true, false ),
// 'logoutUrl' => add_query_arg( array( 'brizy-cloud-logout' => 1 ), menu_page_url( self::menu_slug(), false ) ),
// 'containers' => $containers,
// 'selectedContainer' => is_object( $project ) ? $project->container : ( isset( $containers[0] ) ? array( 'container' => $containers[0]->id ) : null ),
// 'projects' => $projects,
// 'pageUrl' => $pageUrl,
// 'projectObject' => $project
// );
//
// echo $this->twig->render( 'cloud-projects.html.twig', $context );
// }
// public function handleSubmit() {
// if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'validate-cloud' ) ) {
// return;
// }
// $pageUrl = menu_page_url( self::menu_slug(), false );
//
// if ( isset( $_REQUEST['brizy-cloud-login'] ) ) {
// $this->handleLogin();
// }
//
// if ( isset( $_REQUEST['brizy-cloud-logout'] ) ) {
// $this->handleLogout();
// }
//
// if ( isset( $_REQUEST['brizy-cloud-use-container'] ) ) {
// $this->handleUseContainer();
// }
//
// wp_redirect( $pageUrl );
// exit;
// }
//
// public function handleLogin() {
// if ( ! isset( $_REQUEST['cloud-username'] ) || ! isset( $_REQUEST['cloud-password'] ) ) {
// Brizy_Admin_Flash::instance()->add_error( __( 'Please provide the username and password.' ) );
//
// return;
// }
//
// try {
// $token = $this->cloudClient->signIn( $_REQUEST['cloud-username'], $_REQUEST['cloud-password'] );
//
// if ( ! $token ) {
// Brizy_Admin_Flash::instance()->add_error( __( 'Unable to obtain authorization data. Please check your credentials.' ) );
// } else {
// $this->project->setCloudToken( $token );
//
// $containers = $this->cloudClient->getContainers();
//
// if ( isset( $containers[0] ) ) {
// $this->project->setCloudContainer( $containers[0]->id );
// }
//
// $this->project->save();
//
//
// }
//
// } catch ( Exception $e ) {
// Brizy_Logger::instance()->error( 'Unable to obtain cloud token', $e );
// Brizy_Admin_Flash::instance()->add_error( __( 'Unable to obtain authorization data. Please check your credentials.' ) );
// }
//
// $pageUrl = menu_page_url( self::menu_slug(), false );
// wp_redirect( $pageUrl );
// exit;
// }
//
// public function handleLogout() {
// $this->project->setCloudToken( null );
// $this->project->setCloudContainer( null );
// $this->project->save();
// }
//
// public function handleUseContainer() {
// if ( ! isset( $_REQUEST['brizy-cloud-use-container'] ) || $_REQUEST['brizy-cloud-use-container'] == '' ) {
// Brizy_Admin_Flash::instance()->add_error( __( 'Please provide the container id' ) );
//
// return;
// }
//
// $projectId = $_REQUEST['brizy-cloud-use-container'];
//
// if ( $projectId ) {
// $this->project->setCloudContainer( $projectId );
// Brizy_Admin_Flash::instance()->add_success( __( 'Success' ) );
// } else {
// $this->project->removeMetaValue( 'cloudContainer' );
// }
//
// $this->project->save();
//
// $pageUrl = menu_page_url( self::menu_slug(), false );
// wp_redirect( $pageUrl );
// exit;
// }
//
// /**
// * @return string
// */
// public function menu_slug() {
// return self::PAGE_KEY;
// }
//
// /**
// * @return bool
// */
// public function isLoggedIn() {
// return ! ! $this->project->getCloudToken();
// }
}

View File

@@ -0,0 +1,379 @@
<?php
class Brizy_Admin_Cloud {
/**
* @var self
*/
static $instance;
/**
* @var Brizy_Editor_Project
*/
private $project;
/**
* @var Brizy_Admin_Cloud_Client
*/
private $cloudClient;
/**
* @var Brizy_Admin_Cloud_BlockBridge
*/
private $blockBridge;
/**
* @var Brizy_Admin_Cloud_LayoutBridge
*/
private $layoutBridge;
/**
* @param Brizy_Editor_Project|null $project
* @param Brizy_Admin_Cloud_Client|null $cloudClient
*
* @return Brizy_Admin_Cloud
* @throws Exception
*/
public static function _init( Brizy_Editor_Project $project = null, Brizy_Admin_Cloud_Client $cloudClient = null ) {
if ( ! $project ) {
$project = Brizy_Editor_Project::get();
}
if ( ! $cloudClient ) {
$cloudClient = Brizy_Admin_Cloud_Client::instance( $project, new WP_Http() );
}
if ( ! wp_doing_ajax() && Brizy_Editor_Project::get()->getCloudToken() ) {
// do not run cron actions on ajax request
Brizy_Admin_Cloud_Cron::_init();
}
return self::$instance ? self::$instance : ( self::$instance = new self( $project, $cloudClient ) );
}
/**
* Brizy_Admin_Cloud constructor.
*
* @param Brizy_Editor_Project $project
* @param Brizy_Admin_Cloud_Client $client
*/
private function __construct( Brizy_Editor_Project $project, Brizy_Admin_Cloud_Client $client ) {
$this->setProject( $project );
$this->setCloudClient( $client );
$this->blockBridge = new Brizy_Admin_Cloud_BlockBridge( $client );
$this->layoutBridge = new Brizy_Admin_Cloud_LayoutBridge( $client );
add_action( 'wp_loaded', array( $this, 'initializeActions' ) );
}
/**
* @param Brizy_Editor_Project $project
*
* @return Brizy_Admin_Cloud
*/
public function setProject( Brizy_Editor_Project $project ) {
$this->project = $project;
return $this;
}
/**
* @param Brizy_Admin_Cloud_Client $cloudClient
*
* @return Brizy_Admin_Cloud
*/
public function setCloudClient( Brizy_Admin_Cloud_Client $cloudClient ) {
$this->cloudClient = $cloudClient;
return $this;
}
/**
* @param Brizy_Admin_Cloud_BlockBridge $blockBridge
*
* @return Brizy_Admin_Cloud
*/
public function setBlockBridge( Brizy_Admin_Cloud_BlockBridge $blockBridge ){
$this->blockBridge = $blockBridge;
return $this;
}
/**
* @param Brizy_Admin_Cloud_LayoutBridge $layoutBridge
*
* @return Brizy_Admin_Cloud
*/
public function setLayoutBridge( Brizy_Admin_Cloud_LayoutBridge $layoutBridge ) {
$this->layoutBridge = $layoutBridge;
return $this;
}
public function initializeActions() {
try {
if ( wp_doing_ajax() && $this->project->getCloudToken() && $this->project->getCloudContainer() ) {
$versions = $this->cloudClient->getCloudEditorVersions();
if ( $versions['sync'] == BRIZY_SYNC_VERSION ) {
self::registerCloudFilters();
}
}
Brizy_Admin_Cloud_Api::_init( $this->project );
} catch(\Exception $e) {
Brizy_Logger::instance()->exception( $e );
}
}
static public function registerCloudFilters() {
add_filter( 'brizy_get_saved_block', [ self::$instance, 'onGetSavedBlock' ], 10, 3 );
add_filter( 'brizy_get_saved_blocks', [ self::$instance, 'onGetSavedBlocks' ], 10, 3 );
add_action( 'brizy_saved_block_delete', [ self::$instance, 'onDeleteSavedBlock' ] );
add_filter( 'brizy_get_layout', [ self::$instance, 'onGetLayout' ], 10, 3 );
add_filter( 'brizy_get_layouts', [ self::$instance, 'onGetLayouts' ], 10, 3 );
add_action( 'brizy_layout_delete', [ self::$instance, 'onDeleteLayout' ] );
}
static public function unRegisterCloudFilters() {
remove_filter( 'brizy_get_saved_block', [ self::$instance, 'onGetSavedBlock' ] );
remove_filter( 'brizy_get_saved_blocks', [ self::$instance, 'onGetSavedBlocks' ] );
remove_action( 'brizy_saved_block_delete', [ self::$instance, 'onDeleteSavedBlock' ] );
remove_filter( 'brizy_get_layout', [ self::$instance, 'onGetLayout' ] );
remove_filter( 'brizy_get_layouts', [ self::$instance, 'onGetLayouts' ] );
remove_action( 'brizy_layout_delete', [ self::$instance, 'onDeleteLayout' ] );
}
/**
* @param Brizy_Editor_Entity[] $blocks
* @param string[] $fields
* @param Brizy_Admin_Blocks_Manager $manager
*/
public function onGetSavedBlocks( $blocks, $fields, $manager ) {
if ( ! is_array( $blocks ) ) {
$blocks = [];
}
try {
$cloudBlocks = $this->cloudClient->getBlocks( array( 'fields' => $fields ) );
// remove all local block that came from cloud and are deleted from cloud
foreach ( $blocks as $i => $block ) {
$existingBlock = false;
foreach ( (array) $cloudBlocks as $cblock ) {
if ( $cblock->uid == $block['uid'] ) {
$existingBlock = true;
break;
}
}
if ( ! $existingBlock &&
( $localBlock = $manager->getEntity( $block['uid'] ) ) &&
$localBlock->isSynchronized( $this->cloudClient->getBrizyProject()->getCloudAccountId() ) ) {
// delete this block as this block does not exist anymore in cloud
$manager->trashEntity( $localBlock );
unset( $blocks[ $i ] );
}
}
$blocks = array_values( $blocks );
// remove cloud blocks that are already saved localy
foreach ( (array) $cloudBlocks as $cblock ) {
$existingBlock = false;
foreach ( $blocks as $block ) {
if ( $cblock->uid == $block['uid'] ) {
$existingBlock = true;
break;
}
}
if ( ! $existingBlock ) {
if ( in_array( 'synchronized', $fields ) ) {
$localBlock = $manager->getEntity( $cblock->uid );
if ( $localBlock ) {
$cblock->synchronized = $localBlock->isSynchronized( $this->cloudClient->getBrizyProject()->getCloudAccountId() );
} else {
$cblock->synchronized = false;
}
}
if ( in_array( 'isCloudEntity', $fields ) ) {
$cblock->isCloudEntity = true;
}
if ( in_array( 'synchronizable', $fields ) ) {
$cblock->synchronizable = true;
}
$blocks[] = (array) $cblock;
}
}
} catch ( Exception $e ) {
// do nothing...
}
return $blocks;
}
/**
* @param Brizy_Editor_Entity $block
* @param string $uid
* @param Brizy_Admin_Blocks_Manager $manager
*
* @throws Exception
*/
public function onGetSavedBlock( $block, $uid, $manager ) {
try {
if ( ! $block ) {
$this->blockBridge->import( $uid );
$block = $manager->getEntity( $uid );
}
} catch ( Exception $e ) {
}
return $block;
}
/**
* @param $blockUid
*/
public function onDeleteSavedBlock( $blockUid ) {
try {
$blocks = $this->cloudClient->getBlocks( [ 'uid' => $blockUid ] );
if ( isset( $blocks[0] ) ) {
$block = (array) $blocks[0];
$this->cloudClient->deleteBlock( $block['id'] );
}
} catch ( Exception $e ) {
}
}
/**
* @param Brizy_Editor_Entity[] $layouts
* @param string[] $fields
* @param Brizy_Admin_Layouts_Manager $manager
*/
public function onGetLayouts( $layouts, $fields, $manager ) {
if ( ! is_array( $layouts ) ) {
$layouts = [];
}
try {
$cloudLayouts = $this->cloudClient->getLayouts( array( 'fields' => $fields ) );
// remove all local block that came from cloud and are deleted from cloud
foreach ( $layouts as $i => $block ) {
$existingBlock = false;
foreach ( (array) $cloudLayouts as $cblock ) {
if ( $cblock->uid == $block['uid'] ) {
$existingBlock = true;
break;
}
}
if ( ! $existingBlock &&
( $localLayout = $manager->getEntity( $block['uid'] ) ) &&
$localLayout->isSynchronized( $this->cloudClient->getBrizyProject()->getCloudAccountId() ) ) {
// delete this block as this block does not exist anymore in cloud
$manager->deleteEntity( $localLayout );
unset( $layouts[ $i ] );
}
}
$layouts = array_values( $layouts );
foreach ( (array) $cloudLayouts as $aLayout ) {
$existingLayout = false;
foreach ( $layouts as $block ) {
if ( $aLayout->uid == $block['uid'] ) {
$existingLayout = true;
break;
}
}
if ( ! $existingLayout ) {
$localLayout = $manager->getEntity( $aLayout->uid );
if ( in_array( 'synchronized', $fields ) ) {
if ( $localLayout ) {
$aLayout->synchronized = $localLayout->isSynchronized( $this->cloudClient->getBrizyProject()->getCloudAccountId() );
} else {
$aLayout->synchronized = false;
}
}
if ( in_array( 'isCloudEntity', $fields ) ) {
$aLayout->isCloudEntity = true;
}
if ( in_array( 'synchronizable', $fields ) ) {
$aLayout->synchronizable = true;
}
$layouts[] = (array) $aLayout;
}
}
} catch ( Exception $e ) {
// do nothing...
}
return $layouts;
}
/**
* @param Brizy_Editor_Entity $block
* @param string $uid
* @param Brizy_Admin_Layouts_Manager $manager
*
* @throws Exception
*/
public function onGetLayout( $block, $uid, $manager ) {
try {
if ( ! $block ) {
$this->layoutBridge->import( $uid );
$block = $manager->getEntity( $uid );
}
} catch ( Exception $e ) {
}
return $block;
}
/**
* @param $blockUid
*/
public function onDeleteLayout( $blockUid ) {
try {
$blocks = $this->cloudClient->getLayouts( [ 'uid' => $blockUid ] );
if ( isset( $blocks[0] ) ) {
$block = (array) $blocks[0];
$this->cloudClient->deleteLayout( $block['id'] );
}
} catch ( Exception $e ) {
}
}
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* Class Brizy_Admin_Cloud_AbstractUploader
*/
abstract class Brizy_Admin_Cloud_AbstractBridge implements Brizy_Admin_Cloud_BridgeInterface {
/**
* @var Brizy_Admin_Cloud_Client
*/
protected $client;
/**
* Brizy_Admin_Cloud_AbstractUploader constructor.
*
* @param Brizy_Admin_Cloud_Client $client
*/
public function __construct( $client ) {
$this->client = $client;
}
public function getCurrentCloudAccountId() {
return $this->client->getBrizyProject()->getCloudAccountId();
}
}

View File

@@ -0,0 +1,213 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 7/18/18
* Time: 10:48 AM
*/
class Brizy_Admin_Cloud_Api extends Brizy_Admin_AbstractApi {
use Brizy_Admin_Cloud_SyncAware;
const nonce = 'brizy-api';
const AJAX_SIGNIN_ACTION = '-cloud-signin';
const AJAX_SIGNUP_ACTION = '-cloud-signup';
const AJAX_SIGNOUT_ACTION = '-cloud-signout';
const AJAX_RESET_PASSWORD_ACTION = '-cloud-resetpassword';
const AJAX_TRIGGER_SYNC_ACTION = '-cloud-sync';
const AJAX_SYNC_ALLOWED = '-cloud-sync-allowed';
/**
* @var Brizy_Editor_Project
*/
private $project;
/**
* @var Brizy_Admin_Cloud_Client
*/
private $cloudClient;
/**
* Brizy_Admin_Cloud_Api constructor.
*
* @param Brizy_Editor_Project $project
*/
public function __construct( $project ) {
$this->project = $project;
$this->setClient( Brizy_Admin_Cloud_Client::instance( $project, new WP_Http() ) );
parent::__construct();
}
/**
* @param Brizy_Editor_Project $project
*
* @return Brizy_Admin_Cloud_Api
* @throws Exception
*/
public static function _init( $project ) {
static $instance;
if ( ! $instance ) {
$instance = new self( $project );
}
return $instance;
}
protected function initializeApiActions() {
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
add_action( $pref . self::AJAX_SIGNIN_ACTION, array( $this, 'actionSignIn' ) );
add_action( $pref . self::AJAX_SIGNUP_ACTION, array( $this, 'actionSignUp' ) );
add_action( $pref . self::AJAX_SIGNOUT_ACTION, array( $this, 'actionSignOut' ) );
add_action( $pref . self::AJAX_RESET_PASSWORD_ACTION, array( $this, 'actionResetPassword' ) );
add_action( $pref . self::AJAX_TRIGGER_SYNC_ACTION, array( $this, 'actionSync' ) );
add_action( $pref . self::AJAX_SYNC_ALLOWED, array( $this, 'actionSyncAllowed' ) );
}
public function actionSignIn() {
$this->verifyNonce( self::nonce );
$data = file_get_contents( "php://input" );
if ( ( $data = json_decode( $data ) ) === false ) {
$this->error( 400, 'Bad request' );
}
if ( $token = $this->getClient()->signIn( $data->email, $data->password ) ) {
// this is important when you delete block from cloud the local blocks
// will be deleted based on this valued
$this->project->setCloudAccountId( $token );
$this->project->setCloudToken( $token );
$containers = $this->getClient()->getContainers();
if ( isset( $containers[0] ) ) {
$this->project->setCloudContainer( $containers[0]->id );
} else {
$this->error( 400, 'SingIn failed. Invalid container.' );
}
$this->project->saveStorage();
$this->success( [] );
} else {
$this->error( 400, 'SingIn failed' );
}
}
public function actionSignUp() {
$this->verifyNonce( self::nonce );
$data = file_get_contents( "php://input" );
if ( ( $data = json_decode( $data ) ) === false ) {
$this->error( 400, 'Bad request' );
}
if ( $token = $this->getClient()->signUp( $data->firstName, $data->lastName, $data->email, $data->password, $data->confirmPassword ) ) {
// this is important when you delete block from cloud the local blocks
// will be deleted based on this valued
$this->project->setCloudAccountId( $token );
$this->project->setCloudToken( $token );
$containers = $this->getClient()->getContainers();
if ( isset( $containers[0] ) ) {
$this->project->setCloudContainer( $containers[0]->id );
} else {
$this->error( 400, 'Unable to obtain the container.' );
}
$this->project->saveStorage();
$this->success( [] );
} else {
$this->error( 400, 'Sing Up failed' );
}
}
public function actionSignOut() {
$this->verifyNonce( self::nonce );
// clear version in case something gets wonrg.
Brizy_Admin_Cloud_Client::clearVersionCache();
// this is important when you delete block from cloud the local blocks
// will be deleted based on this valued
$this->project->setCloudAccountId( null );
$this->project->setCloudToken( null );
$this->project->saveStorage();
wp_clear_scheduled_hook( Brizy_Admin_Cloud_Cron::BRIZY_CLOUD_CRON_KEY );
$this->success( [] );
}
public function actionResetPassword() {
$this->verifyNonce( self::nonce );
$data = file_get_contents( "php://input" );
if ( ( $data = json_decode( $data ) ) === false ) {
$this->error( 400, 'Bad request' );
}
if ( ! $data->email ) {
$this->error( 400, 'Invalid email' );
}
if ( $token = $this->getClient()->resetPassword( $data->email ) ) {
$this->success( [] );
} else {
$this->error( 400, 'Reset password failed' );
}
}
public function actionSync() {
try {
if ( ! $this->project->getCloudToken() ) {
$this->error( 400, 'Unauthorized' );
}
$merged = array_merge( $this->syncLayouts(0, true ), $this->syncBlocks(0, true ) );
return $this->success( [ 'synchronized' => count( $merged ) ] );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Sync failed', [ $e ] );
$this->error( 500, 'Sync failed' );
}
}
public function actionSyncAllowed() {
try {
$versions = $this->getClient()->getCloudEditorVersions();
$response = [];
$response['isSyncAllowed'] = $versions['sync'] == BRIZY_SYNC_VERSION;
return $this->success( $response );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Sync failed', [ $e ] );
$this->error( 400, 'Sync unauthorized.' );
}
}
/**
* @return null
*/
protected function getRequestNonce() {
return $this->param( 'hash' );
}
}

View File

@@ -0,0 +1,176 @@
<?php
/**
* Class Brizy_Admin_Cloud_BlockUploader
*/
class Brizy_Admin_Cloud_BlockBridge extends Brizy_Admin_Cloud_AbstractBridge
{
use Brizy_Editor_Asset_AttachmentAware;
/**
* @param Brizy_Editor_Block $block
*
* @return mixed|void
* @throws Exception
*/
public function export($block)
{
$media = json_decode($block->getMedia());
if (!$media || !isset($media->fonts)) {
throw new Exception('No fonts property in media object');
}
if (!$media || !isset($media->images)) {
throw new Exception('No images property in media object');
}
$bridge = new Brizy_Admin_Cloud_MediaBridge($this->client);
foreach ($media->images as $uid) {
try {
$bridge->export($uid);
} catch (Exception $e)
{
Brizy_Logger::instance()->critical('Failed to export block media: ' . $e->getMessage(), [$e]);
}
}
$bridge = new Brizy_Admin_Cloud_MediaUploadsBridge($this->client);
foreach ($media->uploads as $uid) {
try {
$bridge->export($uid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to export block uploads: ' . $e->getMessage(), [$e]);
}
}
$bridge = new Brizy_Admin_Cloud_FontBridge($this->client);
foreach ($media->fonts as $fontUid) {
try {
$bridge->export($fontUid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to export block font: ' . $e->getMessage(), [$e]);
}
}
$bridge = new Brizy_Admin_Cloud_ScreenshotBridge($this->client);
$bridge->export($block);
$cloudBlockObject = $this->client->createOrUpdateBlock($block);
if ($cloudBlockObject) {
$block->setSynchronized($this->getCurrentCloudAccountId(), $cloudBlockObject->uid);
}
$block->saveStorage();
}
/**
* @param $blockId
*
* @return mixed|void
* @throws Exception
*/
public function import($blockId)
{
global $wpdb;
$blocks = $this->client->getBlocks(['uid' => $blockId]);
if (!isset($blocks[0])) {
Brizy_Logger::instance()->critical('Failed to import: Unable to obtain the block from cloud ' . $blockId);
return;
}
$block = (array)$blocks[0];
try {
// create local block
$wpdb->query('START TRANSACTION ');
$name = md5(time());
$post = wp_insert_post(array(
'post_title' => $name,
'post_name' => $name,
'post_status' => 'publish',
'post_type' => Brizy_Admin_Blocks_Main::CP_SAVED
));
if ($post) {
$brizyPost = Brizy_Editor_Block::get($post, $block['uid']);
if (isset($block['media'])) {
$brizyPost->setMedia($block['media']);
}
if (isset($block['meta'])) {
$brizyPost->setMeta($block['meta']);
}
$brizyPost->set_editor_data($block['data']);
$brizyPost->set_uses_editor(true);
$brizyPost->set_needs_compile(true);
$brizyPost->setDataVersion(1);
$brizyPost->setSynchronized($this->getCurrentCloudAccountId(), $block['id']);
$brizyPost->save();
// import fonts
if (isset($block['media'])) {
$blockMedia = json_decode($block['media']);
$fontBridge = new Brizy_Admin_Cloud_FontBridge($this->client);
if (isset($blockMedia->fonts)) {
foreach ($blockMedia->fonts as $cloudFontUid) {
try {
$fontBridge->import($cloudFontUid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to import block media: ' . $e->getMessage(), [$e]);
}
}
}
$mediaBridge = new Brizy_Admin_Cloud_MediaBridge($this->client);
$mediaBridge->setBlockId($post);
if (isset($blockMedia->images)) {
foreach ($blockMedia->images as $mediaUid) {
try {
$mediaBridge->import($mediaUid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to import block media: ' . $e->getMessage(), [$e]);
}
}
}
$mediaUploadBridge = new Brizy_Admin_Cloud_MediaUploadsBridge($this->client);
$mediaUploadBridge->setBlockId($post);
if (isset($blockMedia->uploads)) {
foreach ($blockMedia->uploads as $mediaUpload) {
try {
$mediaUploadBridge->import($mediaUpload);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to import block uploads: ' . $e->getMessage(), [$e]);
}
}
}
}
}
$wpdb->query('COMMIT');
} catch (Exception $e) {
$wpdb->query('ROLLBACK');
Brizy_Logger::instance()->critical('Failed to import block ' . $blockId, [$e]);
}
}
/**
* @param Brizy_Editor_Block $block
*
* @return mixed|void
* @throws Exception
*/
public function delete($block)
{
if ($block->getCloudId($this->getCurrentCloudAccountId())) {
$this->client->deleteBlock($block->getCloudId($this->getCurrentCloudAccountId()));
}
}
}

View File

@@ -0,0 +1,26 @@
<?php
/**
* Interface Brizy_Admin_Cloud_UploaderInterface
*/
interface Brizy_Admin_Cloud_BridgeInterface {
/**
* @return mixed
*/
public function export( $entity );
/**
* @param $entity
*
* @return mixed
*/
public function import( $entity );
/**
* @param $entity
*
* @return mixed
*/
public function delete( $entity );
}

View File

@@ -0,0 +1,916 @@
<?php
class Brizy_Admin_Cloud_Client extends WP_Http
{
use Brizy_Editor_Asset_AttachmentAware;
const TRANSIENT_KEY = 'brizy_cloud_editor_versions';
/**
* @var Brizy_Editor_Project
*/
private $brizyProject;
/**
* @var WP_Http
*/
private $http;
/**
* @var integer
*/
private $library;
/**
* @var Brizy_Admin_Cloud_Client
*/
static private $instance;
/**
* @param $project
* @param $http
*
* @return Brizy_Admin_Cloud_Client
*/
public static function instance($project, $http)
{
static $instance;
if (self::$instance) {
return self::$instance;
}
return self::$instance = new self($project, $http);
}
/**
* Brizy_Admin_Cloud_Client constructor.
*
* @param Brizy_Editor_Project $project
* @param WP_Http $http
*/
private function __construct($project, $http)
{
$this->brizyProject = $project;
$this->http = $http;
add_action('brizy-updated', ['Brizy_Admin_Cloud_Client', 'clearVersionCache']);
do_action('brizy-activated', ['Brizy_Admin_Cloud_Client', 'clearVersionCache']);
}
public static function clearVersionCache()
{
delete_transient(self::TRANSIENT_KEY);
}
/**
* @return Brizy_Editor_Project
*/
public function getBrizyProject()
{
return $this->brizyProject;
}
/**
* @param Brizy_Editor_Project $brizyProject
*
* @return Brizy_Admin_Cloud_Client
*/
public function setBrizyProject($brizyProject)
{
$this->brizyProject = $brizyProject;
return $this;
}
/**
* @return WP_Http
*/
public function getHttp()
{
return $this->http;
}
/**
* @param WP_Http $http
*
* @return Brizy_Admin_Cloud_Client
*/
public function setHttp($http)
{
$this->http = $http;
return $this;
}
/**
* @param $uid
*
* @return string
*/
public function getScreenshotUrl($uid)
{
$url = Brizy_Config::getEditorBaseUrls() . Brizy_Config::CLOUD_SCREENSHOT;
return sprintf($url, $uid);
}
/**
* @param $screenUid
* @param $filePath
*
* @return bool
*/
public function createScreenshot($screenUid, $filePath)
{
$data = array(
'uid' => $screenUid,
'attachment' => base64_encode(file_get_contents($filePath))
);
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SCREENSHOTS, array(
'headers' => $this->getHeaders(),
'body' => $data
));
$code = wp_remote_retrieve_response_code($response);
if ($code >= 200 && $code <= 300) {
return true;
}
return false;
}
private function getHeaders($aditional = null)
{
$values = $this->getCloudEditorVersions();
return array_merge(array(
//'X-AUTH-APP-TOKEN' => Brizy_Config::CLOUD_APP_KEY,
'X-AUTH-USER-TOKEN' => $this->brizyProject->getMetaValue('brizy-cloud-token'),
'X-EDITOR-VERSION' => $values['editor'],
'X-SYNC-VERSION' => BRIZY_SYNC_VERSION
), is_array($aditional) ? $aditional : array());
}
private function getHeadersWithoutAuthorization($aditional = null)
{
return array_merge(array(
//'X-AUTH-APP-TOKEN' => Brizy_Config::CLOUD_APP_KEY,
'X-SYNC-VERSION' => BRIZY_SYNC_VERSION
), is_array($aditional) ? $aditional : array());
}
public function getLibraries()
{
$response = $this->http->get(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_LIBRARY, array('headers' => $this->getHeaders()));
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
$body = wp_remote_retrieve_body($response);
$libraries = json_decode($body);
if (count($libraries) == 0) {
throw new Exception('No libraries provided');
}
return $libraries;
}
return null;
}
/**
* @param $email
* @param $password
*
* @return array|bool|WP_Error
*/
public function signIn($email, $password)
{
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SIGNIN, array(
'headers' => $this->getHeadersWithoutAuthorization(array(
'Content-type' => 'application/x-www-form-urlencoded'
)),
'body' => array(
'email' => $email,
'password' => $password
),
'timeout' => 30
));
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
$jsonResponse = json_decode($response['body']);
// update cloud editor versions
$this->getCloudEditorVersions(true);
return $jsonResponse->token;
}
return false;
}
/**
* @param string $firstName
* @param string $lastName
* @param string $email
* @param string $password
* @param string $confirmPassword
*
* @return bool
*/
public function signUp($firstName, $lastName, $email, $password, $confirmPassword)
{
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SIGNUP, array(
'headers' => $this->getHeadersWithoutAuthorization(array(
'Content-type' => 'application/x-www-form-urlencoded'
)),
'body' => array(
'first_name' => $firstName,
'last_name' => $lastName,
'email' => $email,
'new_password' => $password,
'confirm_password' => $confirmPassword,
)
));
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
$jsonResponse = json_decode($response['body']);
return $jsonResponse->token;
}
return false;
}
/**
* @param $email
*
* @return bool
*/
public function resetPassword($email)
{
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_RESET_PASSWORD, array(
'headers' => $this->getHeaders(array(
'Content-type' => 'application/x-www-form-urlencoded'
)),
'body' => array(
'email' => $email,
)
));
$code = wp_remote_retrieve_response_code($response);
return $code >= 200 && $code < 300;
}
public function getCloudEditorVersions($ignoreCache = false)
{
$value = get_transient('brizy_cloud_editor_versions');
if ($value && !$ignoreCache) {
return $value;
}
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_EDITOR_VERSIONS;
$response = $this->http->get($url);
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
$value = (array)json_decode($response['body']);
set_transient('brizy_cloud_editor_versions', $value, 3600);
} else {
throw new Exception(wp_remote_retrieve_response_message($response));
}
return $value;
}
public function getContainers()
{
return $this->getCloudEntity(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_CONTAINERS, []);
}
public function getProjects($filters)
{
return $this->getCloudEntity(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_PROJECTS, $filters);
}
public function getProject($id)
{
$url = sprintf(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_PROJECTS . "/%d", (int)$id);
$response = $this->http->get($url, array('headers' => $this->getHeaders()));
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
return json_decode($response['body']);
}
return null;
}
public function createProject($container, $name)
{
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_PROJECTS, array(
'headers' => $this->getHeaders(),
'body' => array(
'name' => $name,
'container' => $container,
'globals' => null,
'site_id' => null
)
));
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
return json_decode($response['body']);
}
return false;
}
public function getBlocks($filters = array())
{
return $this->getCloudEntityByContainer(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SAVEDBLOCKS, $filters);
}
/**
* @param $id
*
* @return array|mixed|object|null
*/
public function getBlockByUid($uid)
{
$blocks = $this->getBlocks(['uid' => $uid]);
return array_pop($blocks);
}
/**
* @param $id
*
* @return array|mixed|object|null
*/
public function getBlock($id)
{
$blocks = $this->getCloudEntityByContainer(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SAVEDBLOCKS . "/{$id}", []);
return array_pop($blocks);
}
/**
* @param Brizy_Editor_Block $block
*
* @return bool
* @throws Exception
*/
public function createOrUpdateBlock($block)
{
$cloudBlockData = array(
'container' => $this->brizyProject->getCloudContainer(),
'meta' => $block->getMeta(),
'media' => $block->getMedia(),
'data' => $block->get_editor_data(),
'uid' => $block->getUid(),
'dataVersion' => 1
);
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SAVEDBLOCKS;
$cloudUid = $block->getCloudId($this->brizyProject->getCloudAccountId());
$cloudBlock = null;
if (!$cloudUid && ($cloudBlock = $this->getBlockByUid($block->getUid()))) {
$cloudUid = $cloudBlock->uid;
}
if (!$cloudUid) {
$response = $this->http->post($url, array(
'headers' => $this->getHeaders(),
'body' => $cloudBlockData
));
} else {
$cloudBlockData['dataVersion'] = $cloudBlock->dataVersion + 1;
$response = $this->http->request($url . "/" . $cloudBlock->id, array(
'method' => 'PUT',
'headers' => $this->getHeaders(),
'body' => $cloudBlockData
));
}
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
// update cloud editor versions
$this->getCloudEditorVersions(true);
Brizy_Logger::instance()->critical('Cloud api exception', [$response]);
throw new Exception(wp_remote_retrieve_response_message($response));
}
return json_decode(wp_remote_retrieve_body($response));
}
/**
* @param $blockId
*
* @return bool
* @throws Exception
*/
public function deleteBlock($blockId)
{
$query = http_build_query(['container' => $this->brizyProject->getCloudContainer()]);
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_SAVEDBLOCKS . "/" . $blockId . "?" . $query;
$response = $this->http->request($url, array('method' => 'DELETE', 'headers' => $this->getHeaders()));
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
throw new Exception('Invalid code return by cloud api');
}
return $code == 200;
}
/**
* @param $filters
*
* @return array|mixed|object|null
*/
public function getPopups($filters = array())
{
return $this->getCloudEntity(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_POPUPS, $filters);
}
/**
* @param $uid
*
* @return mixed
*/
public function getPopupByUid($uid)
{
$popups = $this->getPopups(['uid' => $uid]);
return array_pop($popups);
}
/**
* @param Brizy_Editor_Popup $popup
*
* @return bool
* @throws Exception
*/
public function createOrUpdatePopup($popup)
{
$cloudBlockData = array(
'container' => $this->brizyProject->getCloudContainer(),
'meta' => $popup->getMeta(),
'data' => $popup->get_editor_data(),
'is_autosave' => 0,
'uid' => $popup->getUid(),
'dataVersion' => 1
);
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_POPUPS;
$cloudUid = $popup->getCloudId($this->brizyProject->getCloudAccountId());
if ($cloudUid) {
$response = $this->http->request($url, array(
'method' => 'PUT',
'headers' => $this->getHeaders(),
'body' => $cloudBlockData
));
} else {
$response = $this->http->post($url . "/" . $cloudUid, array(
'headers' => $this->getHeaders(),
'body' => $cloudBlockData
));
}
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
$this->getCloudEditorVersions(true);
Brizy_Logger::instance()->critical('Cloud api exception', [$response]);
throw new Exception('Invalid code return by cloud api');
}
return json_decode(wp_remote_retrieve_body($response));
}
/**
* @param $popupId
*
* @return bool
* @throws Exception
*/
public function deletePopup($popupId)
{
$query = http_build_query(['container' => $this->brizyProject->getCloudContainer()]);
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_POPUPS . "/" . $popupId . "?" . $query;
$response = $this->http->request($url, array('method' => 'DELETE', 'headers' => $this->getHeaders()));
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
throw new Exception('Invalid code return by cloud api');
}
return $code == 200;
}
/**
* @param $filters
*
* @return array|mixed|object|null
*/
public function getLayouts($filters = array())
{
return $this->getCloudEntity(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_LAYOUTS, $filters);
}
/**
* @param $uid
*
* @return mixed
*/
public function getLayoutByUid($uid)
{
$layouts = $this->getLayouts(['uid' => $uid]);
return array_pop($layouts);
}
/**
* @param $id
*
* @return array|mixed|object|null
*/
public function getLayout($id)
{
return $this->getCloudEntityByContainer(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_LAYOUTS . "/" . $id, []);
}
/**
* @param Brizy_Editor_Layout $layout
*
* @return bool
* @throws Exception
*/
public function createOrUpdateLayout($layout)
{
$cloudBlockData = array(
'container' => $this->brizyProject->getCloudContainer(),
'meta' => $layout->getMeta(),
'media' => $layout->getMedia(),
'data' => $layout->get_editor_data(),
'uid' => $layout->getUid(),
'dataVersion' => 1
);
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_LAYOUTS;
$cloudUid = $layout->getCloudId($this->brizyProject->getCloudAccountId());
$cloudLayout = null;
if (!$cloudUid && ($cloudLayout = $this->getLayoutByUid($layout->getUid()))) {
$cloudUid = $cloudLayout->uid;
}
if (!$cloudUid) {
$response = $this->http->post($url, array(
'headers' => $this->getHeaders(),
'body' => $cloudBlockData
));
} else {
$cloudBlockData['dataVersion'] = $cloudLayout->dataVersion + 1;
$response = $this->http->request($url . "/" . $cloudLayout->id, array(
'method' => 'PUT',
'headers' => $this->getHeaders(),
'body' => $cloudBlockData,
));
}
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
$this->getCloudEditorVersions(true);
Brizy_Logger::instance()->critical('Cloud api exception', [$response]);
throw new Exception('Invalid code return by cloud api');
}
return json_decode(wp_remote_retrieve_body($response));
}
/**
* @param $layoutId
*
* @return bool
* @throws Exception
*/
public function deleteLayout($layoutId)
{
$query = http_build_query(['container' => $this->brizyProject->getCloudContainer()]);
$url = Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_LAYOUTS . "/" . $layoutId . "?" . $query;
$response = $this->http->request($url, array('method' => 'DELETE', 'headers' => $this->getHeaders()));
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
throw new Exception('Invalid code return by cloud api');
}
return $code == 200;
}
/**
* @param $uid
*
* @return bool
* @throws Exception
*/
public function isMediaUploaded($uid)
{
$cloud_entity_by_container = $this->getCloudEntity(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_MEDIA, ['name' => $uid]);
return is_array($cloud_entity_by_container) && count($cloud_entity_by_container) > 0;
}
/**
* @param $uid
*
* @return bool
* @throws Exception
*/
public function isCustomFileUploaded($fileUid, $customFileName)
{
// download file and store it in wp
$urlBuilder = new Brizy_Editor_UrlBuilder();
$external_asset_url = $urlBuilder->external_custom_file($fileUid, $customFileName);
$response = $this->http->get($external_asset_url);
$code = wp_remote_retrieve_response_code($response);
if($code>=500) {
throw new \Exception('Unable to determine if the files was uploaded or not.');
}
return $code==200;
}
/**
* @param $file
*
* @return bool
* @throws Exception
*/
public function uploadMedia($uid, $file)
{
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_MEDIA, array(
'headers' => $this->getHeaders(),
'body' => array(
'attachment' => base64_encode(file_get_contents($file)),
'name' => $uid,
'filename' => basename($file)
)
));
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
throw new Exception('Invalid code return by cloud api');
}
return true;
}
public function uploadCustomFile($uid, $file)
{
$body = array(
'attachment' => base64_encode(file_get_contents($file)),
'uid' => $uid,
'filename' => basename($file),
'container' => $this->brizyProject->getCloudContainer(),
);
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_CUSTOM_FILES, array(
'headers' => $this->getHeaders(),
'body' => $body
));
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
throw new Exception('Invalid code return by cloud api');
}
return true;
}
/**
* @param $font
*
* Ex:
* [
* 'id' => 'askdalskdlaksd',
* 'family' => 'proxima-nova',
* 'type' => 'uploaded',
* 'weights' => [
* '400' => [
* 'ttf' => codecept_data_dir( 'fonts/pn-regular-webfont.ttf' ),
* 'eot' => codecept_data_dir( 'fonts/pn-regular-webfont.eot' ),
* 'woff' => codecept_data_dir( 'fonts/pn-regular-webfont.woff' ),
* 'woff2' => codecept_data_dir( 'fonts/pn-regular-webfont.woff2' ),
* ],
* '500' => [
* 'eot' => codecept_data_dir( 'fonts/pn-medium-webfont.eot' ),
* 'woff' => codecept_data_dir( 'fonts/pn-medium-webfont.woff' ),
* 'woff2' => codecept_data_dir( 'fonts/pn-medium-webfont.woff2' ),
* ],
* '700' => [
* 'eot' => codecept_data_dir( 'fonts/pn-bold-webfont.eot' ),
* 'woff' => codecept_data_dir( 'fonts/pn-bold-webfont.woff' ),
* 'woff2' => codecept_data_dir( 'fonts/pn-bold-webfont.woff2' ),
* ],
* ]
* ];
*
* @return bool
* @throws Exception
*/
public function createFont($font)
{
$params = array(
'container' => $this->brizyProject->getCloudContainer(),
'uid' => $font['id'],
'family' => $font['family'],
);
// prepare font data
foreach ($font['weights'] as $weigth => $files) {
foreach ($files as $type => $file) {
$params["files[$weigth][$type]"] = new CURLFile($file);
}
}
unset($font['weights']);
$file_upload_request = function ($handle_or_parameters, $request = '', $url = '') use ($params) {
$this->updateWPHTTPRequest($handle_or_parameters, $params);
};
// handle cURL requests
add_action('http_api_curl', $file_upload_request, 10);
// handle fsockopen
add_action('requests-fsockopen.before_send', $file_upload_request, 10, 3);
$response = $this->http->post(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_FONTS, array(
'headers' => $this->getHeaders(['Content-Type' => 'multipart/form-data']),
'body' => $params,
'timeout' => 40
));
remove_action('http_api_curl', $file_upload_request);
remove_action('requests-fsockopen.before_send', $file_upload_request);
$code = wp_remote_retrieve_response_code($response);
if ($code >= 400) {
throw new Exception('Invalid code return by cloud api');
}
return json_decode(wp_remote_retrieve_body($response));
}
public function getFont($uid)
{
$response = $this->getCloudEntity(Brizy_Config::CLOUD_ENDPOINT . Brizy_Config::CLOUD_FONTS . "/{$uid}");
if (is_array($response)) {
return $response;
}
return null;
}
/**
* @param $endpoint
* @param $filters
*
* @return array|mixed|object|null
*/
private function getCloudEntity($endpoint, $filters = array())
{
$http_build_query = http_build_query($filters);
if ($http_build_query) {
$http_build_query = '?' . $http_build_query;
}
$url = $endpoint . $http_build_query;
$response = $this->http->get($url, array('headers' => $this->getHeaders()));
$code = wp_remote_retrieve_response_code($response);
if ($code == 200) {
return (array)json_decode($response['body']);
}
return null;
}
/**
* @param $endpoint
* @param $filters
*
* @return array|mixed|object|null
*/
private function getCloudEntityByContainer($endpoint, $filters = array())
{
$filters = array_merge($filters, ['container' => $this->brizyProject->getCloudContainer()]);
return $this->getCloudEntity($endpoint, $filters);
}
private function updateWPHTTPRequest(&$handle_or_parameters, $form_body_arguments)
{
if (function_exists('curl_init') && function_exists('curl_exec')) {
curl_setopt($handle_or_parameters, CURLOPT_POSTFIELDS, $form_body_arguments);
} elseif (function_exists('fsockopen')) {
$form_fields = [];
$form_files = [];
foreach ($form_body_arguments as $name => $value) {
if (file_exists($value)) {
// Not great for large files since it dumps into memory but works well for small files
$form_files[$name] = file_get_contents($value);
} else {
$form_fields[$name] = $value;
}
}
function build_data_files($boundary, $fields, $files)
{
$data = '';
$eol = "\r\n";
$delimiter = '-------------' . $boundary;
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . "\"" . $eol . $eol
. $content . $eol;
}
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
//. 'Content-Type: image/png'.$eol
. 'Content-Transfer-Encoding: binary' . $eol;
$data .= $eol;
$data .= $content . $eol;
}
$data .= "--" . $delimiter . "--" . $eol;
return $data;
}
$boundary = uniqid("", true);
$handle_or_parameters = build_data_files($boundary, $form_fields, $form_files);
}
}
}

View File

@@ -0,0 +1,61 @@
<?php
class Brizy_Admin_Cloud_Cron {
use Brizy_Admin_Cloud_SyncAware;
const BRIZY_CLOUD_CRON_KEY = 'brizy-cloud-synchronize';
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self( Brizy_Admin_Cloud_Client::instance( Brizy_Editor_Project::get(), new WP_Http() ) );
}
return $instance;
}
/**
* Brizy_Admin_Cloud_Cron constructor.
*/
public function __construct( $client ) {
$this->setClient( $client );
add_action( self::BRIZY_CLOUD_CRON_KEY, array( $this, 'syncBlocksAction' ) );
add_action( self::BRIZY_CLOUD_CRON_KEY, array( $this, 'syncLayoutsAction' ) );
add_filter( 'cron_schedules', array( $this, 'addBrizyCloudCronSchedules' ) );
if ( ! wp_next_scheduled( self::BRIZY_CLOUD_CRON_KEY ) ) {
$interval = is_user_logged_in() ? '5minute' : 'hourly';
if ( is_user_logged_in() ) {
wp_schedule_event( time(), $interval, self::BRIZY_CLOUD_CRON_KEY );
}
}
}
public function syncLayoutsAction() {
Brizy_Logger::instance()->debug('Sync layouts cron called');
return $this->syncLayouts(1);
}
public function syncBlocksAction() {
Brizy_Logger::instance()->debug('Sync blocks cron called');
return $this->syncBlocks(1);
}
public function addBrizyCloudCronSchedules( $schedules ) {
// Adds once weekly to the existing schedules.
$schedules['5minute'] = array(
'interval' => 300,
'display' => __( 'Once in 5 minutes' )
);
return $schedules;
}
}

View File

@@ -0,0 +1,103 @@
<?php
/**
* Class Brizy_Admin_Cloud_FontBridge
*/
class Brizy_Admin_Cloud_FontBridge extends Brizy_Admin_Cloud_AbstractBridge {
/**
* @var Brizy_Admin_Fonts_Manager
*/
private $fontManager;
/**
* Brizy_Admin_Cloud_FontBridge constructor.
*
* @param Brizy_Admin_Cloud_Client $client
*/
public function __construct( $client ) {
parent::__construct( $client );
$this->fontManager = new Brizy_Admin_Fonts_Manager();
}
/**
* @param $fontUid
*
* @return mixed|void
* @throws Exception
*/
public function export( $fontUid ) {
$fontData = $this->fontManager->getFontForExport( $fontUid );
if ( ! $fontData ) {
throw new \Exception( "Unable to find font {$fontUid}" );
}
if ( ! $this->client->getFont( $fontUid ) ) {
$this->client->createFont( $fontData );
}
}
/**
* @param $fontUid
*
* @return mixed|void
* @throws Exception
*/
public function import( $fontUid ) {
if ( $font = $this->fontManager->getFont( $fontUid ) ) {
return $font;
}
$font = $this->client->getFont( $fontUid );
$family = $font['family'];
$weights = $font['files'];
$newWeights = array();
foreach ( $weights as $weight => $weightType ) {
foreach ( $weightType as $type => $fileUrl ) {
$newWeights[ $weight ][ $type ] = $this->downloadFileToTemporaryFile( $fileUrl );
}
}
return $this->fontManager->createFont( $fontUid, $family, $newWeights, 'uploaded' );
}
private function downloadFileToTemporaryFile( $url ) {
$filePath = tempnam( sys_get_temp_dir(), basename( $url ) );
$content = Brizy_Editor_Asset_StaticFile::get_asset_content( $url );
$result = file_put_contents( $filePath, $content );
if ( $result === false ) {
Brizy_Logger::instance()->critical( 'Filed to write font content',
[
'url' => $url,
'filePath' => $filePath
] );
throw new Exception( 'Filed to write font content' );
}
return array(
'name' => basename( $url ),
'type' => Brizy_Public_AssetProxy::get_mime( $filePath ),
'tmp_name' => $filePath,
'error' => 0,
'size' => filesize( $filePath )
);
}
/**
* @param $fontUid
*
* @return mixed|void
* @throws Exception
*/
public function delete( $fontUid ) {
throw new Exception( 'Not implemented' );
}
}

View File

@@ -0,0 +1,178 @@
<?php
/**
* Class Brizy_Admin_Cloud_BlockUploader
*/
class Brizy_Admin_Cloud_LayoutBridge extends Brizy_Admin_Cloud_AbstractBridge
{
/**
* @param Brizy_Editor_Block $layout
*
* @return mixed|void
* @throws Exception
*/
public function export($layout)
{
$media = json_decode($layout->getMedia());
if (!$media || !isset($media->fonts)) {
throw new Exception('No fonts property in media object');
}
if (!$media || !isset($media->images)) {
throw new Exception('No images property in media object');
}
$bridge = new Brizy_Admin_Cloud_MediaBridge($this->client);
foreach ($media->images as $uid) {
try {
$bridge->export($uid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to export layout media: ' . $e->getMessage(), [$e]);
continue;
}
}
$bridge = new Brizy_Admin_Cloud_MediaUploadsBridge($this->client);
foreach ($media->uploads as $uid) {
try {
$bridge->export($uid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to export layout uploads: ' . $e->getMessage(), [$e]);
}
}
$bridge = new Brizy_Admin_Cloud_FontBridge($this->client);
foreach ($media->fonts as $fontUid) {
try {
$bridge->export($fontUid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to export layout font: ' . $e->getMessage(), [$e]);
continue;
}
}
$bridge = new Brizy_Admin_Cloud_ScreenshotBridge($this->client);
$bridge->export($layout);
$layoutObject = $this->client->createOrUpdateLayout($layout);
if ($layoutObject) {
$layout->setSynchronized($this->getCurrentCloudAccountId(), $layoutObject->uid);
}
$layout->saveStorage();
}
/**
* @param $layoutId
*
* @return mixed|void
* @throws Exception
*/
public function import($layoutId)
{
global $wpdb;
$layouts = $this->client->getLayouts(['uid' => $layoutId]);
if (!isset($layouts[0])) {
Brizy_Logger::instance()->critical('Failed to import: Unable to obtain the layout from cloud ' . $layoutId);
return;
}
try {
$wpdb->query('START TRANSACTION ');
$layout = (array)$layouts[0];
$name = md5(time());
$post = wp_insert_post(array(
'post_title' => $name,
'post_name' => $name,
'post_status' => 'publish',
'post_type' => Brizy_Admin_Layouts_Main::CP_LAYOUT
));
if ($post) {
$brizyPost = Brizy_Editor_Layout::get($post, $layout['uid']);
if (isset($layout['media'])) {
$brizyPost->setMedia($layout['media']);
}
if (isset($layout['meta'])) {
$brizyPost->setMeta($layout['meta']);
}
$brizyPost->set_editor_data($layout['data']);
$brizyPost->set_uses_editor(true);
$brizyPost->set_needs_compile(true);
$brizyPost->saveStorage();
$brizyPost->setDataVersion(1);
$brizyPost->setSynchronized($this->getCurrentCloudAccountId(), $layout['uid']);
$brizyPost->save();
// import fonts
if (isset($layout['media'])) {
$blockMedia = json_decode($layout['media']);
$fontBridge = new Brizy_Admin_Cloud_FontBridge($this->client);
if (isset($blockMedia->fonts)) {
foreach ($blockMedia->fonts as $cloudFontUid) {
try {
$fontBridge->import($cloudFontUid);
} catch (Exception $e) {
}
}
}
$mediaBridge = new Brizy_Admin_Cloud_MediaBridge($this->client);
$mediaBridge->setBlockId($post);
if (isset($blockMedia->images)) {
foreach ($blockMedia->images as $mediaUid) {
try {
$mediaBridge->import($mediaUid);
} catch (Exception $e) {
}
}
}
$mediaUploadBridge = new Brizy_Admin_Cloud_MediaUploadsBridge($this->client);
$mediaUploadBridge->setBlockId($post);
if (isset($blockMedia->uploads)) {
foreach ($blockMedia->uploads as $mediaUid) {
try {
$mediaUploadBridge->import($mediaUid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to import layout uploads: ' . $e->getMessage(), [$e]);
}
}
}
}
}
$wpdb->query('COMMIT');
} catch (Exception $e) {
$wpdb->query('ROLLBACK');
Brizy_Logger::instance()->critical('Failed to import layout ' . $layoutId, [$e]);
}
}
/**
* @param Brizy_Editor_Block $layout
*
* @return mixed|void
* @throws Exception
*/
public function delete($layout)
{
if ($layout->getCloudId($this->getCurrentCloudAccountId())) {
$this->client->deleteLayout($layout->getCloudId($this->getCurrentCloudAccountId()));
}
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* Class Brizy_Admin_Cloud_BlockUploader
*/
class Brizy_Admin_Cloud_MediaBridge extends Brizy_Admin_Cloud_AbstractBridge {
use Brizy_Editor_Asset_AttachmentAware;
/**
* This is the block id for which we are importing the media
* If this is not set the import will fail.
*
* @var int
*/
private $blockId;
/**
* @param $mediaUid
*
* @return mixed|void
* @throws Exception
*/
public function export( $mediaUid ) {
$mediaId = (int) $this->getAttachmentByMediaName( $mediaUid );
if ( ! $mediaId ) {
throw new Exception( "Unable to find media {$mediaUid}" );
}
if ( $this->client->isMediaUploaded( $mediaUid ) ) {
return true;
}
$filePath = get_attached_file( $mediaId );
$this->client->uploadMedia( $mediaUid, $filePath );
}
/**
* @param $mediaUid
*
* @return mixed|void
* @throws Exception
*/
public function import( $mediaUid ) {
if ( ! $this->blockId ) {
throw new Exception( 'The block id is not set.' );
}
// enable svg upload
$svnUpload = new Brizy_Admin_Svg_Main();
$jsonUpload = new Brizy_Admin_Json_Main();
$svnUploadEnabled = Brizy_Editor_Storage_Common::instance()->get( 'svg-upload', false );
$jsonUploadEnabled = Brizy_Editor_Storage_Common::instance()->get( 'json-upload', false );
if ( ! $svnUploadEnabled ) {
$svnUpload->enableSvgUpload();
}
if ( ! $jsonUploadEnabled ) {
$jsonUpload->enableJsonUpload();
}
$media_cacher = new Brizy_Editor_CropCacheMedia( $this->client->getBrizyProject() );
$media_cacher->download_original_image( $mediaUid, false );
// disabled it if was disabled before
if ( ! $svnUploadEnabled ) {
$svnUpload->disableSvgUpload();
}
if ( ! $jsonUploadEnabled ) {
$jsonUpload->disableJsonUpload();
}
}
/**
* @param $layoutId
*
* @return mixed|void
* @throws Exception
*/
public function delete( $layoutId ) {
throw new Exception( 'Not implemented' );
}
/**
* @param int $blockId
*
* @return Brizy_Admin_Cloud_MediaBridge
*/
public function setBlockId( $blockId ) {
$this->blockId = (int) $blockId;
return $this;
}
}

View File

@@ -0,0 +1,139 @@
<?php
/**
* Class Brizy_Admin_Cloud_MediaUploadsBridges
*/
class Brizy_Admin_Cloud_MediaUploadsBridge extends Brizy_Admin_Cloud_AbstractBridge
{
use Brizy_Editor_Asset_AttachmentAware;
use Brizy_Editor_Asset_StaticFileTrait;
/**
* This is the block id for which we are importing the media
* If this is not set the import will fail.
*
* @var int
*/
private $blockId;
/**
* @param $mediaUid
*
* @return mixed|void
* @throws Exception
*/
public function export($mediaUpload)
{
list($uploadUid,$uploadName) = explode('|||', $mediaUpload);
$mediaId = (int)$this->getAttachmentByMediaName($uploadUid);
if (!$mediaId) {
throw new Exception("Unable to find media {$uploadUid}");
}
if ($this->client->isCustomFileUploaded($uploadUid,$uploadName)) {
return true;
}
// upload file
$filePath = get_attached_file($mediaId);
$this->client->uploadCustomFile($uploadUid, $filePath);
}
/**
* @param $mediaUid
*
* @return mixed|void
* @throws Exception
*/
public function import($mediaUpload)
{
if (!$this->blockId) {
throw new Exception('The block id is not set.');
}
list($fileUid, $customFileName) = explode('|||', $mediaUpload);
// enable svg upload
// enable svg upload
$svnUpload = new Brizy_Admin_Svg_Main();
$jsonUpload = new Brizy_Admin_Json_Main();
$svnUploadEnabled = Brizy_Editor_Storage_Common::instance()->get( 'svg-upload', false );
$jsonUploadEnabled = Brizy_Editor_Storage_Common::instance()->get( 'json-upload', false );
if ( ! $svnUploadEnabled ) {
$svnUpload->enableSvgUpload();
}
if ( ! $jsonUploadEnabled ) {
$jsonUpload->enableJsonUpload();
}
// download file and store it in wp
$urlBuilder = new Brizy_Editor_UrlBuilder();
$external_asset_url = $urlBuilder->external_custom_file($fileUid, $customFileName);
$original_asset_path = $urlBuilder->brizy_upload_path("/custom_files/" . $customFileName);
$original_asset_path_relative = $urlBuilder->brizy_upload_relative_path("/custom_files/" . $customFileName);
if (!file_exists($original_asset_path)) {
// I assume that the media was already attached.
if (!$this->store_file($external_asset_url, $original_asset_path)) {
// unable to save the attachment
Brizy_Logger::instance()->error('Unable to store original media file', array(
'source' => (string)$external_asset_url,
'destination' => $original_asset_path
));
throw new Exception('Unable to cache custom file upload');
}
}
$attachmentId = $this->create_attachment($customFileName, $original_asset_path, $original_asset_path_relative, null, $fileUid);
if ($attachmentId === 0 || is_wp_error($attachmentId)) {
Brizy_Logger::instance()->error('Unable to create custom file attachment', array(
'customFile' => (string)$external_asset_url,
'original_asset_path' => (string)$original_asset_path,
'original_asset_path_relative' => (string)$original_asset_path_relative,
));
throw new Exception('Unable to attach media');
}
// disabled it if was disabled before
if ( ! $svnUploadEnabled ) {
$svnUpload->disableSvgUpload();
}
if ( ! $jsonUploadEnabled ) {
$jsonUpload->disableJsonUpload();
}
}
/**
* @param $blockId
*
* @return mixed|void
* @throws Exception
*/
public function delete($blockId)
{
throw new Exception('Not implemented');
}
/**
* @param int $blockId
*
* @return Brizy_Admin_Cloud_MediaBridge
*/
public function setBlockId($blockId)
{
$this->blockId = (int)$blockId;
return $this;
}
}

View File

@@ -0,0 +1,163 @@
<?php
/**
* Class Brizy_Admin_Cloud_BlockUploader
*/
class Brizy_Admin_Cloud_PopupBridge extends Brizy_Admin_Cloud_AbstractBridge
{
/**
* @param Brizy_Editor_Block $popup
*
* @return mixed|void
* @throws Exception
*/
public function export($popup)
{
// check if the assets are uploaded in cloud
// upload them if needed
// create the block in cloud
$media = json_decode($popup->getMedia());
if (!$media || !isset($media->fonts)) {
throw new Exception('No fonts property in media object');
}
if (!$media || !isset($media->images)) {
throw new Exception('No images property in media object');
}
$bridge = new Brizy_Admin_Cloud_MediaBridge($this->client);
foreach ($media->images as $uid) {
try {
$bridge->export($uid);
} catch (Exception $e) {
continue;
}
}
$bridge = new Brizy_Admin_Cloud_MediaUploadsBridge($this->client);
foreach ($media->uploads as $uid) {
try {
$bridge->export($uid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to export popup uploads: ' . $e->getMessage(), [$e]);
}
}
$bridge = new Brizy_Admin_Cloud_FontBridge($this->client);
foreach ($media->fonts as $fontUid) {
try {
$bridge->export($fontUid);
} catch (Exception $e) {
continue;
}
}
$popupObject = $this->client->createOrUpdatePopup($popup);
if ($popupObject) {
$popup->setSynchronized($this->getCurrentCloudAccountId(), $popupObject->uid);
}
$popup->saveStorage();
}
/**
* @param $popupId
*
* @return mixed|void
* @throws Exception
*/
public function import($popupId)
{
global $wpdb;
$popups = $this->client->getPopups(['uid' => $popupId]);
if (!isset($popups[0])) {
return;
}
$popup = $popups[0];
try {
$wpdb->query('START TRANSACTION ');
$name = md5(time());
$post = wp_insert_post(array(
'post_title' => $name,
'post_name' => $name,
'post_status' => 'publish',
'post_type' => Brizy_Admin_Popups_Main::CP_POPUP
));
if ($post) {
$brizyPost = Brizy_Editor_Popup::get($post, $popup['uid']);
$brizyPost->setMeta($popup['meta']);
$brizyPost->setCloudId($popup['id']);
$brizyPost->set_editor_data($popup['data']);
$brizyPost->set_uses_editor(true);
$brizyPost->set_needs_compile(true);
$brizyPost->setDataVersion(1);
$brizyPost->save();
// import fonts
if (isset($layout['media'])) {
$blockMedia = json_decode($popup['media']);
$fontBridge = new Brizy_Admin_Cloud_FontBridge($this->client);
if (isset($blockMedia->fonts)) {
foreach ($blockMedia->fonts as $cloudFontUid) {
try {
$fontBridge->import($cloudFontUid);
} catch (Exception $e) {
}
}
}
$mediaBridge = new Brizy_Admin_Cloud_MediaBridge($this->client);
$mediaBridge->setBlockId($post);
if (isset($blockMedia->images)) {
foreach ($blockMedia->images as $mediaUid) {
try {
$mediaBridge->import($mediaUid);
} catch (Exception $e) {
}
}
}
$mediaUploadBridge = new Brizy_Admin_Cloud_MediaUploadsBridge($this->client);
$mediaUploadBridge->setBlockId($post);
if (isset($blockMedia->uploads)) {
foreach ($blockMedia->uploads as $mediaUid) {
try {
$mediaUploadBridge->import($mediaUid);
} catch (Exception $e) {
Brizy_Logger::instance()->critical('Failed to import layout uploads: ' . $e->getMessage(), [$e]);
}
}
}
}
}
$wpdb->query('COMMIT');
} catch (Exception $e) {
$wpdb->query('ROLLBACK');
Brizy_Logger::instance()->critical('Importing layout ' . $popupId . ' failed', [$e]);
}
}
/**
* @param Brizy_Editor_Block $layout
*
* @return mixed|void
* @throws Exception
*/
public function delete($layout)
{
$this->client->deletePopup($layout->getCloudId());
}
}

View File

@@ -0,0 +1,59 @@
<?php
class Brizy_Admin_Cloud_Proxy {
const ACTION = 'brizy_cloud_proxy';
/**
* Brizy_Admin_Cloud_Proxy constructor.
*/
public function __construct() {
add_action( 'wp_ajax_' . self::ACTION, array( $this, 'handleRequest' ) );
}
/**
* @throws Exception
*/
public function handleRequest() {
$vars = $_GET;
$project = Brizy_Editor_Project::get();
// redirect the request
$token = $project->getMetaValue( 'brizy-cloud-token' );
$cloudProjectId = $project->getMetaValue( 'brizy-cloud-project' );
if ( ! isset( $vars['endpoint'] ) ) {
wp_send_json_error( null, 400 );
exit;
}
if ( ! $token || ! $cloudProjectId || ! isset( $vars['endpoint'] ) ) {
wp_send_json_error( null, 401 );
exit;
}
$http = new WP_Http();
$url = Brizy_Config::CLOUD_ENDPOINT . "/api/" . $vars['endpoint'];
$response = $http->request( $url, array(
'headers' => array(
'X-AUTH-APP-TOKEN' => Brizy_Config::CLOUD_APP_KEY,
'X-AUTH-USER-TOKEN' => $token
),
'body' => $_REQUEST['request'],
'method' => $_SERVER['REQUEST_METHOD'],
) );
$status = wp_remote_retrieve_response_code( $response );
if ( $response instanceof WP_Error ) {
wp_send_json_error( wp_remote_retrieve_response_message( $response ), $status );
exit;
}
wp_send_json_success( wp_remote_retrieve_body( $response ), $status );
exit;
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Class Brizy_Admin_Cloud_BlockUploader
*/
class Brizy_Admin_Cloud_ScreenshotBridge extends Brizy_Admin_Cloud_AbstractBridge {
use Brizy_Editor_Asset_AttachmentAware;
/**
* @param Brizy_Editor_Block $block
*
* @return mixed|void
* @throws Exception
*/
public function export( $block ) {
$meta = json_decode( $block->getMeta() );
$screenUid = $meta->_thumbnailSrc;
$manager = new Brizy_Editor_Screenshot_Manager( new Brizy_Editor_UrlBuilder( $this->client->getBrizyProject() ) );
$screenPath = $manager->getScreenshot( $screenUid );
if ( $screenPath ) {
$this->client->createScreenshot( $screenUid, $screenPath );
}
}
/**
* @param Brizy_Editor_Block $block
*
* @return mixed|void
* @throws Exception
*/
public function import( $block ) {
throw new Exception('Import screenshots not implemented yet');
}
/**
* @param Brizy_Editor_Block $layout
*
* @return mixed|void
* @throws Exception
*/
public function delete( $layout ) {
$this->client->deleteBlock( $layout->getCloudId() );
}
}

View File

@@ -0,0 +1,144 @@
<?php
trait Brizy_Admin_Cloud_SyncAware {
/**
* @var Brizy_Admin_Cloud_Client
*/
protected $client;
/**
* @return Brizy_Admin_Cloud_Client
*/
public function getClient() {
return $this->client;
}
/**
* @param Brizy_Admin_Cloud_Client $client
*
* @return Brizy_Admin_Cloud_SyncAware
*/
public function setClient( $client ) {
$this->client = $client;
return $this;
}
protected function syncLayouts( $limit = 0, $throwException = false ) {
$layoutIds = $this->getLayoutsForSync( $limit );
$synchronized = [];
foreach ( $layoutIds as $lId ) {
try {
if ( $this->syncLayout( $lId->ID ) ) {
$synchronized[] = $lId->ID;
}
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Failed to sync layout',
[
'blockId' => $lId->ID,
$e
] );
if ( $throwException ) {
throw $e;
}
}
}
return $synchronized;
}
protected function syncBlocks( $limit = 0, $throwException = false ) {
$postIds = $this->getBlocksForSync( $limit );
$synchronized = [];
foreach ( $postIds as $block ) {
try {
if ( $this->syncBlock( $block->ID ) ) {
$synchronized[] = $block->ID;
}
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Failed to sync block',
[
'blockId' => $block->ID
] );
if ( $throwException ) {
throw $e;
}
}
}
return $synchronized;
}
protected function syncBlock( $blockId ) {
$brizyBlock = Brizy_Editor_Block::get( $blockId );
$cloud_account_id = $this->getClient()->getBrizyProject()->getCloudAccountId();
if ( $brizyBlock &&
$brizyBlock->isSynchronizable( $cloud_account_id ) &&
!$brizyBlock->isSynchronized( $cloud_account_id ) ) {
$updater = new Brizy_Admin_Cloud_BlockBridge( $this->client );
$updater->export( $brizyBlock );
return true;
}
}
protected function syncLayout( $layoutId ) {
$brizyLayout = Brizy_Editor_Layout::get( $layoutId );
$cloud_account_id = $this->getClient()->getBrizyProject()->getCloudAccountId();
if ( $brizyLayout &&
$brizyLayout->isSynchronizable( $cloud_account_id ) &&
!$brizyLayout->isSynchronized( $cloud_account_id ) ) {
$updater = new Brizy_Admin_Cloud_LayoutBridge( $this->client );
$updater->export( $brizyLayout );
return true;
}
}
protected function getLayoutsForSync( $limit = 0 ) {
global $wpdb;
$savedBlockType = Brizy_Admin_Layouts_Main::CP_LAYOUT;
$limitQuery = "";
if ( $limit !== 0 ) {
$limitQuery = " LIMIT " . ( (int) $limit );
}
$postIds = $wpdb->get_results(
"SELECT ID FROM {$wpdb->posts} p
WHERE p.post_type='{$savedBlockType}'
{$limitQuery}" );
return $postIds;
}
protected function getBlocksForSync( $limit = 0 ) {
global $wpdb;
$savedBlockType = Brizy_Admin_Blocks_Main::CP_SAVED;
$limitQuery = "";
if ( $limit !== 0 ) {
$limitQuery = " LIMIT " . ( (int) $limit );
}
$postIds = $wpdb->get_results(
"SELECT ID FROM {$wpdb->posts} p
WHERE p.post_type='{$savedBlockType}'
{$limitQuery}
"
);
return $postIds;
}
}

View File

@@ -0,0 +1,162 @@
<?php
class Brizy_Admin_DashboardWidget extends Brizy_Admin_AbstractWidget {
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
}
public function __construct() {
parent::__construct();
global $wp_meta_boxes;
$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
$widget_id = $this->internalGetId();
$ours = [
$widget_id => $dashboard[ $widget_id ],
];
$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
}
/**
* @return string
*/
public function getId() {
return 'dashboard';
}
/**
* @return string
*/
public function getName() {
return sprintf( __( '%s Overview', 'brizy' ), Brizy_Editor::get()->get_name() );
}
public function render() {
try {
$news = $this->getNews();
} catch ( Exception $e ) {
$news = $e->getMessage();
}
echo Brizy_Admin_View::render( 'dashboard', array(
'news' => Brizy_Admin_View::render( 'dashboard-news', [ 'news' => $news ] ),
'posts' => $this->renderBrizyPosts()
) );
}
/**
* @return array
* @throws Exception
*/
private function getNews() {
$transient_key = 'brizy_feed_news';
if ( ! ( $news = get_transient( $transient_key ) ) ) {
$request = wp_remote_get( 'https://www.brizy.io/blog' );
if ( is_wp_error( $request ) ) {
throw new Exception( $request->get_error_message() );
} elseif ( 200 !== wp_remote_retrieve_response_code( $request ) ) {
throw new Exception( wp_remote_retrieve_response_message( $request ) );
} elseif ( empty( $request['body'] ) ) {
throw new Exception( esc_html__( 'There is no body in the remote server response.', 'brizy' ) );
}
$dom = Brizy_Parser_Pquery::parseStr( $request['body'] );
$news = [];
$titles = $dom->query( '.brz-wp-title .brz-a .brz-wp-title-content' );
$links = $dom->query( '.brz-wp-title .brz-a' );
$excerpts = $dom->query( '.brz-posts .brz-posts__item .brz-css-qtnxu' );
if ( count( $titles ) !== 5 || count( $links ) !== 5 || count( $excerpts ) !== 5 ) {
throw new Exception( __( 'Parsing failed!', 'brizy' ) );
}
foreach ( $titles as $title ) {
$news[]['title'] = $title->getInnerText();
}
foreach ( $links as $i => $link ) {
if ( isset( $news[ $i ] ) ) {
$news[ $i ]['url'] = esc_url( 'https://www.brizy.io' . $link->getAttribute( 'href' ) );
}
}
foreach ( $excerpts as $i => $excerpt ) {
if ( isset( $news[ $i ] ) ) {
$news[ $i ]['excerpt'] = wp_trim_words( wp_strip_all_tags( $excerpt->getInnerText() ), 40, '...' );
}
}
set_transient( $transient_key, $news, 5 * DAY_IN_SECONDS );
}
return $news;
}
/**
* @throws Exception
*/
private function parseQuery( $selector, $dom, &$news, $key, $callback ) {
$items = $dom->query( $selector );
if ( ! $items || count( $items ) !== 5 ) {
throw new Exception( __( 'Parsing failed!', 'brizy' ) );
}
foreach ( $items as $i => $item ) {
if ( isset( $news[ $i ] ) ) {
$news[ $i ][$key] = wp_strip_all_tags( $item->{$callback}() );
}
}
}
/**
* @return string
*/
private function renderBrizyPosts() {
$query = array(
'post_type' => array_diff( Brizy_Editor::get()->supported_post_types(), [ 'brizy-global-block', 'brizy-saved-block', 'brizy-global-block' ] ),
'post_status' => [ 'publish', 'draft' ],
'meta_key' => 'brizy',
'orderby' => 'modified'
);
$posts = get_posts( $query );
$brizy_posts = [];
foreach ( $posts as $apost ) {
try {
if ( ! Brizy_Editor_Entity::isBrizyEnabled( $apost ) ) {
continue;
}
$brizy_posts[] = [
'edit_url' => add_query_arg( [ Brizy_Editor::prefix('-edit') => '' ], get_permalink( $apost ) ),
'title' => get_the_title( $apost ),
'date' => get_the_modified_date( '', $apost )
];
if ( 6 === count( $brizy_posts ) ) {
break;
}
} catch ( Exception $e ) {
continue;
}
}
return Brizy_Admin_View::render( 'dashboard-posts', array( 'posts' => $brizy_posts ) );
}
}

View File

@@ -0,0 +1,129 @@
<?php
abstract class Brizy_Admin_Entity_AbstractManager implements Brizy_Admin_Entity_ManagerInterface {
/**
* Convert WP_Post to a Block/Layout or something else
*
* @param $post
*
* @param null $uid
*
* @return mixed
*/
abstract protected function convertWpPostToEntity( $post, $uid = null );
/**
* @param $type
* @param $uid
*
* @return Brizy_Editor_Block|Brizy_Editor_Post|Brizy_Editor_Popup|mixed|null
* @throws Exception
* @todo: refactor this as a single sql query
*
*/
protected function getEntityUidAndType( $uid, $type ) {
$entities = get_posts( array(
'post_type' => $type,
'post_status' => 'any',
'meta_key' => 'brizy_post_uid',
'meta_value' => $uid,
'numberposts' => - 1,
'orderby' => 'ID',
'order' => 'DESC',
) );
if ( isset( $entities[0] ) ) {
$entity = $this->convertWpPostToEntity( $entities[0] );
} else {
$entity = null;
}
return $entity;
}
/**
* @param $type
* @param array $args
*
* @return Brizy_Editor_Block|Brizy_Editor_Post|mixed|null
* @todo: refactor this as a single sql query
*/
protected function getEntitiesByType( $type, $args = array() ) {
$filterArgs = array(
'post_type' => $type,
'posts_per_page' => - 1,
'post_status' => 'publish',
'orderby' => 'ID',
'order' => 'ASC',
);
$filterArgs = array_merge( $filterArgs, $args );
$posts = get_posts( $filterArgs );
$entities = [];
foreach ( $posts as $apost ) {
$entities[] = $this->convertWpPostToEntity( $apost );
}
return $entities;
}
protected function createEntityByType( $uid, $type, $status = 'publish' ) {
if($this->getEntityUidAndType($uid,$type)) {
throw new Exception('Duplicate entity uid. Please refresh the page and try again');
}
$name = md5( time() );
$apost = wp_insert_post( array(
'post_title' => $name,
'post_name' => $name,
'post_status' => $status,
'post_type' => $type
) );
if ( $apost ) {
$brizyPost = $this->convertWpPostToEntity( $apost, $uid );
$brizyPost->set_uses_editor( true );
$brizyPost->set_needs_compile( true );
$brizyPost->setDataVersion( 1 );
return $brizyPost;
}
return null;
}
/**
* @param Brizy_Editor_Entity $entity
*/
public function deleteEntity( Brizy_Editor_Entity $entity ) {
do_action( 'brizy_before_entity_delete', $entity );
wp_delete_post( $entity->getWpPostId() );
}
/**
* @param Brizy_Editor_Entity $entity
*/
public function trashEntity( Brizy_Editor_Entity $entity ) {
do_action( 'brizy_before_entity_delete', $entity );
wp_trash_post( $entity->getWpPostId() );
}
/**
* @param Brizy_Editor_Entity[] $entities
* @param array $fields
*
* @return array
*/
public function createResponseForEntities( $entities, $fields = [] ) {
$response = [];
foreach ( $entities as $entity ) {
$response[] = $entity->createResponse( $fields );
}
return $response;
}
}

View File

@@ -0,0 +1,11 @@
<?php
interface Brizy_Admin_Entity_ManagerInterface {
public function getEntities( $args );
public function getEntity( $args );
public function createEntity( $uid, $status='publish' );
public function deleteEntity( Brizy_Editor_Entity $entity );
}

View File

@@ -0,0 +1,172 @@
<?php defined( 'ABSPATH' ) or die();
class Brizy_Admin_Feedback {
/**
* Brizy_Admin_Feedback constructor.
*/
public function __construct() {
add_action( 'wp_ajax_brizy-dismiss-notice', [ $this, 'ajax_dismiss_notice' ] );
add_action( 'wp_ajax_brizy-send-feedback', [ $this, 'ajax_send_feedback' ] );
add_action( 'admin_notices', [ $this, 'admin_notices' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'admin_footer', [ $this, 'admin_footer' ] );
}
public function admin_notices() {
if ( 'dismissed' == get_user_meta( get_current_user_id(), 'brizy-notice-rating', true ) || get_transient( 'brizy-notice-rating' ) ) {
return;
}
?>
<div class="brz-notice notice is-dismissible">
<div class="brz-notice-container">
<div class="brz-notice-image">
<img src="<?php echo plugins_url( 'static/img/logo.svg', __FILE__ ) ?>" alt="brizy-logo">
</div>
<div class="brz-notice-content">
<div class="brz-notice-heading">
<?php esc_html_e( 'Hello! Seems like you are using Brizy to build your website - Thanks a lot!', 'brizy' ); ?>
</div>
<?php esc_html_e( 'Could you please do us a BIG favor and give it a 5-star rating on WordPress? This would boost our motivation and help other users make a comfortable decision while choosing the Brizy plugin.', 'brizy' ); ?>
<br/>
<div class="brz-review-notice-container">
<a href="https://wordpress.org/support/plugin/brizy/reviews/?filter=5#new-post" class="brz-review-deserve button-primary" target="_blank">
<?php esc_html_e( 'Ok, you deserve it', 'brizy' ); ?>
</a>
<span class="dashicons dashicons-calendar"></span>
<a href="#" class="brz-review-later">
<?php esc_html_e( 'Nope, maybe later', 'brizy' ); ?>
</a>
<span class="dashicons dashicons-smiley"></span>
<a href="#" class="brz-review-done">
<?php esc_html_e( 'I already did', 'brizy' ); ?>
</a>
</div>
</div>
</div>
</div>
<?php
}
public function ajax_dismiss_notice() {
check_ajax_referer( 'brizy-admin-nonce', 'nonce' );
if ( $_POST['repeat'] == 'true' ) {
set_transient( 'brizy-notice-rating', true, WEEK_IN_SECONDS );
} else {
update_user_meta( get_current_user_id(), 'brizy-notice-rating', 'dismissed' );
}
wp_send_json_success();
}
public function ajax_send_feedback() {
check_ajax_referer( 'brizy-admin-nonce', 'nonce' );
parse_str( $_POST['form'], $form );
$reason_key = $form['reason_key'];
$body = [
'version' => BRIZY_VERSION,
'site_lang' => get_bloginfo( 'language' ),
'feedback_key' => $reason_key
];
if ( ! empty( $form[ 'reason_' . $reason_key ] ) ) {
$body['feedback'] = sanitize_text_field( $form[ 'reason_' . $reason_key ] );
}
wp_remote_post( 'http://test.themefuse.com/', [
'timeout' => 30,
'body' => $body,
] );
wp_send_json_success();
}
public function admin_enqueue_scripts() {
if ( ! $this->is_plugins_page() ) {
return;
}
wp_enqueue_script( 'jquery-ui-dialog' );
wp_enqueue_style( 'wp-jquery-ui-dialog' );
}
public function admin_footer() {
if ( ! $this->is_plugins_page() ) {
return;
}
$deactivate_reasons = [
'no_longer_needed' => [
'title' => __( 'I no longer need the plugin', 'brizy' ),
'input_placeholder' => '',
],
'found_a_better_plugin' => [
'title' => __( 'I found a better plugin', 'brizy' ),
'input_placeholder' => __( 'Please share which plugin', 'brizy' ),
],
'couldnt_get_the_plugin_to_work' => [
'title' => __( 'I couldn\'t get the plugin to work', 'brizy' ),
'input_placeholder' => '',
],
'temporary_deactivation' => [
'title' => __( 'It\'s a temporary deactivation', 'brizy' ),
'input_placeholder' => '',
],
'brizy_pro' => [
'title' => __( 'I have Brizy Pro', 'brizy' ),
'input_placeholder' => '',
'alert' => __( 'Wait! Don\'t deactivate Brizy. You have to activate both Brizy and Brizy Pro in order for the plugin to work.', 'brizy' ),
],
'other' => [
'title' => __( 'Other', 'brizy' ),
'input_placeholder' => __( 'Please share the reason', 'brizy' ),
],
];
?>
<div id="brz-deactivate-feedback-dialog" class="hidden">
<div class="brz-deactivate-feedback-dialog-header">
<img class="brz-deactivate-feedback-dialog-logo" src="<?php echo plugins_url( 'static/img/logo.svg', __FILE__ ) ?>" alt="brizy-logo">
<span class="brz-deactivate-feedback-dialog-header-title"><?php echo __( 'Quick Feedback', 'brizy' ); ?></span>
</div>
<form class="brz-deactivate-feedback-dialog-form" method="post">
<div class="brz-deactivate-feedback-dialog-form-caption">
<?php echo __( 'If you have a moment, please share why you are deactivating Brizy:', 'brizy' ); ?>
</div>
<div class="brz-deactivate-feedback-dialog-form-body">
<?php foreach ( $deactivate_reasons as $reason_key => $reason ) : ?>
<div class="brz-deactivate-feedback-dialog-input-wrapper">
<input id="brz-deactivate-feedback-<?php echo esc_attr( $reason_key ); ?>" class="brz-deactivate-feedback-dialog-input" type="radio" name="reason_key" value="<?php echo esc_attr( $reason_key ); ?>" />
<label for="brz-deactivate-feedback-<?php echo esc_attr( $reason_key ); ?>" class="brz-deactivate-feedback-dialog-label"><?php echo esc_html( $reason['title'] ); ?></label>
<?php if ( ! empty( $reason['input_placeholder'] ) ) : ?>
<input class="brz-feedback-text hidden" type="text" name="reason_<?php echo esc_attr( $reason_key ); ?>" placeholder="<?php echo esc_attr( $reason['input_placeholder'] ); ?>" />
<?php endif; ?>
<?php if ( ! empty( $reason['alert'] ) ) : ?>
<div class="brz-feedback-text-alert brz-feedback-text hidden"><?php echo esc_html( $reason['alert'] ); ?></div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</form>
</div>
<?php
}
private function is_plugins_page() {
global $pagenow;
return 'plugins.php' === $pagenow;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* @todo: move all mkdir calls here.
*
* Class Brizy_FileSystem
*/
class Brizy_Admin_FileSystem {
/**
* @param $pageUploadPath
*/
static public function deleteAllDirectories( $pageUploadPath ) {
try {
$dIterator = new DirectoryIterator( $pageUploadPath );
foreach ( $dIterator as $entry ) {
if ( ! $entry->isDot() && $entry->isDir() ) {
$subDirIterator = new RecursiveDirectoryIterator( $entry->getRealPath(), RecursiveDirectoryIterator::SKIP_DOTS );
$files = new RecursiveIteratorIterator( $subDirIterator, RecursiveIteratorIterator::CHILD_FIRST );
foreach ( $files as $file ) {
if ( ! $file->isDir() ) {
@unlink( $file->getRealPath() );
}
}
self::deleteFilesAndDirectory( $entry->getRealPath() );
}
}
} catch ( Exception $e ) {
return false;
}
}
/**
* @param $pageUploadPath
*/
static public function deleteFilesAndDirectory( $pageUploadPath ) {
try {
$dIterator = new DirectoryIterator( $pageUploadPath );
foreach ( $dIterator as $entry ) {
if ( $entry->isDot() ) {
continue;
}
if ( $entry->isDir() ) {
$subDirIterator = new RecursiveDirectoryIterator( $entry->getRealPath(), RecursiveDirectoryIterator::SKIP_DOTS );
$files = new RecursiveIteratorIterator( $subDirIterator, RecursiveIteratorIterator::CHILD_FIRST );
foreach ( $files as $file ) {
if ( ! $file->isDir() ) {
@unlink( $file->getRealPath() );
}
}
@rmdir( $entry->getRealPath() );
} else {
@unlink( $entry->getRealPath() );
}
}
@rmdir( $pageUploadPath );
} catch ( Exception $e ) {
return false;
}
}
}

View File

@@ -0,0 +1,114 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Admin_Flash {
const BRIZY_NOTICE_TRANSIENT_KEY = 'brizy-admin-notices';
/**
* @var Brizy_Admin_Flash
*/
private static $instance;
const INFO = 'info';
const WARNING = 'waring';
const SUCCESS = 'success';
const ERROR = 'error';
/**
* @var array
*/
private $notices = array();
public static function instance() {
if ( self::$instance ) {
return self::$instance;
}
return self::$instance = new self();
}
public function initialize() {
//add_action( 'wp_loaded', array( $this, '_action_render_notices' ) );
add_action( 'admin_notices', array( $this, '_action_render_notices' ),100 );
add_action( 'network_admin_notices', array( $this, '_action_render_notices' ),100 );
add_action( 'shutdown', array( $this, '_action_store_notices' ) );
$this->load_notices();
}
public function _action_render_notices() {
foreach ( $this->notices as $notice ) {
echo Brizy_Admin_View::render( 'notice', $notice );
}
$this->notices = array();
}
public function _action_store_notices() {
if ( ! empty( $this->notices ) ) {
set_transient( self::BRIZY_NOTICE_TRANSIENT_KEY, $this->notices, 120 );
}
}
protected function load_notices() {
$notices = get_transient( self::BRIZY_NOTICE_TRANSIENT_KEY );
if ( $notices ) {
$this->notices = $notices;
delete_transient( self::BRIZY_NOTICE_TRANSIENT_KEY );
}
}
public function add( $message, $type ) {
$this->notices[ md5( $message ) ] = array(
'message' => $message,
'type' => $type,
);
}
public function add_info( $message ) {
$this->add( $message, self::INFO );
}
public function add_warning( $message ) {
$this->add( $message, self::WARNING );
}
public function add_success( $message ) {
$this->add( $message, self::SUCCESS );
}
public function add_error( $message ) {
$this->add( $message, self::ERROR );
}
public function count() {
return count( $this->notices );
}
public function has( $hash ) {
return isset( $this->notices[ $hash ] );
}
public function has_notice_type( $type ) {
$array_filter = array_filter( $this->notices, function ( $var ) use ( $type ) {
return $var['type'] == $type;
} );
return count( $array_filter ) > 0;
}
public function get( $hash ) {
if ( $this->has( $hash ) ) {
return $this->notices[ $hash ];
}
return null;
}
}

View File

@@ -0,0 +1,148 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 7/18/18
* Time: 10:48 AM
*/
class Brizy_Admin_Fonts_Api extends Brizy_Admin_AbstractApi {
const nonce = 'brizy-api';
const AJAX_CREATE_FONT_ACTION = '-create-font';
const AJAX_DELETE_FONT_ACTION = '-delete-font';
const AJAX_GET_FONTS_ACTION = '-get-fonts';
/**
* @var Brizy_Admin_Fonts_Manager
*/
private $fontManager;
/**
* @return Brizy_Admin_Fonts_Api
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* Brizy_Admin_Fonts_Api constructor.
*/
public function __construct() {
$this->fontManager = new Brizy_Admin_Fonts_Manager();
parent::__construct();
}
/**
* @return null
*/
protected function getRequestNonce() {
return $this->param( 'hash' );
}
protected function initializeApiActions() {
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
add_action( $pref . self::AJAX_CREATE_FONT_ACTION, array( $this, 'actionCreateFont' ) );
add_action( $pref . self::AJAX_DELETE_FONT_ACTION, array( $this, 'actionDeleteFont' ) );
add_action( $pref . self::AJAX_GET_FONTS_ACTION, array( $this, 'actionGetFonts' ) );
}
public function actionGetFonts() {
$this->verifyNonce( self::nonce );
$manager = new Brizy_Admin_Fonts_Manager();
$this->success( $manager->getAllFonts() );
}
public function actionCreateFont() {
try {
$this->verifyNonce( self::nonce );
if ( ! ( $fontUidId = $this->param( 'id' ) ) ) {
$this->error( 400, 'Invalid font uid' );
}
if ( ! ( $family = $this->param( 'family' ) ) ) {
$this->error( 400, 'Invalid font family' );
}
if ( ! ( $fontType = $this->param( 'type' ) ) ) {
$fontType = 'uploaded';
}
if ( ! isset( $_FILES['fonts'] ) ) {
$this->error( 400, 'Invalid font files' );
}
$existingFont = $this->fontManager->getFontByFamily( $fontUidId, $family, $fontType );
if ( $existingFont ) {
$this->error( 400, 'This font family already exists.' );
}
try {
$files = array();
// create font attachments
foreach ( $_FILES['fonts']['name'] as $weight => $attachments ) {
foreach ( $attachments as $type => $file ) {
$files[ $weight ][ $type ] = array(
'name' => $_FILES['fonts']['name'][ $weight ][ $type ],
'type' => $_FILES['fonts']['type'][ $weight ][ $type ],
'tmp_name' => $_FILES['fonts']['tmp_name'][ $weight ][ $type ],
'error' => $_FILES['fonts']['error'][ $weight ][ $type ],
'size' => $_FILES['fonts']['size'][ $weight ][ $type ]
);
}
}
$fontPostId = $this->fontManager->createFont( $fontUidId, $family, $files, $fontType );
} catch ( Exception $e ) {
Brizy_Logger::instance()->debug( 'Create font ERROR', [ $e ] );
$this->error( 400, $e->getMessage() );
}
$fontUidId = get_post_meta( $fontPostId, 'brizy_post_uid', true );
$font = $this->fontManager->getFont( $fontUidId );
$this->success( $font );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), [ $exception ] );
$this->error( 400, $exception->getMessage() );
}
}
public function actionDeleteFont() {
$this->verifyNonce( self::nonce );
if ( ! ( $fontId = $this->param( 'id' ) ) ) {
$this->error( 400, 'Invalid font id' );
}
$manager = new Brizy_Admin_Fonts_Manager();
try {
$manager->deleteFont( $fontId );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), [ $exception ] );
$this->error( $exception->getCode(), $exception->getMessage() );
}
$this->success( [] );
}
}

View File

@@ -0,0 +1,6 @@
<?php
class Brizy_Admin_Fonts_Exception_DuplicateFont extends Exception
{
}

View File

@@ -0,0 +1,165 @@
<?php
class Brizy_Admin_Fonts_Handler extends Brizy_Public_AbstractProxy {
const ENDPOINT = '-font';
/**
* @return array
*/
protected function get_endpoint_keys() {
return array( Brizy_Editor::prefix( self::ENDPOINT ) );
}
/**
* @return mixed|void
* @throws Twig_Error_Loader
* @throws Twig_Error_Runtime
* @throws Twig_Error_Syntax
*/
public function process_query() {
global $wp_query;
$vars = $wp_query->query_vars;
// Check if user is not querying API
$ENDPOINT = Brizy_Editor::prefix( self::ENDPOINT );
if ( ! isset( $vars[ $ENDPOINT ] ) || ! is_string( $vars[ $ENDPOINT ] ) ) {
return;
}
session_write_close();
$fontQueries = $this->explodeFont( $vars[ $ENDPOINT ] );
if ( count( $fontQueries ) == 0 ) {
return;
}
$contexts = array();
foreach ( $fontQueries as $fontUid => $weights ) {
$contexts[ $fontUid ] = array();
$fontPost = $this->getFont( $fontUid );
if ( ! $fontPost ) {
continue;
}
foreach ( $weights as $weight ) {
$contexts[ $fontUid ][ $weight ] = $this->getFontWeightFileUrls( $fontPost->ID, $weight );
}
}
header( 'Content-Type: text/css' );
$twigEngine = Brizy_TwigEngine::instance( path_join( BRIZY_PLUGIN_PATH, "admin/fonts/views" ) );
$twigEngine->getEnvironment()
->addFilter( new Twig_SimpleFilter( 'fontStyle', function ( $weight ) {
$weight = preg_replace( "/\d+/", "", $weight );
if ( trim( $weight ) == "" ) {
return 'normal';
}
return $weight;
} ) );
$twigEngine->getEnvironment()
->addFilter( new Twig_SimpleFilter( 'fontType', function ( $type ) {
if ( $type == 'ttf' ) {
return 'truetype';
} else {
return $type;
}
} ) );
$twigEngine->getEnvironment()->addFilter( new Twig_SimpleFilter( 'fontWeight', function ( $weight ) {
return trim( preg_replace( "/[^\d]+/", "", $weight ) );
} ) );
echo $twigEngine->render( 'fonts.css.twig', array(
'fonts' => $contexts
) );
exit;
}
/**
* @param $request
*
* @return array
*/
private function explodeFont( $request ) {
$fonts = explode( "|", $request );
$fontsParsed = array();
foreach ( $fonts as $fontRequest ) {
$font = explode( ':', $fontRequest );
$fontsParsed[ $font[0] ] = explode( ',', $font['1'] );
}
return $fontsParsed;
}
/**
* @param $uid
*
* @return mixed|null
*/
private function getFont( $uid ) {
$fonts = get_posts( [
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'brizy_post_uid',
'value' => $uid
)
),
] );
if ( is_array( $fonts ) && isset( $fonts[0] ) ) {
return $fonts[0];
}
return null;
}
/**
* @param $fontId
* @param $weight
*
* @return array|bool
*/
function getFontWeightFileUrls( $fontId, $weight ) {
$args = array(
'meta_query' => array(
array(
'key' => 'brizy-font-weight',
'value' => $weight
)
),
'post_type' => 'attachment',
'post_parent' => $fontId
);
$posts = get_posts( $args );
if ( ! $posts || is_wp_error( $posts ) ) {
return false;
}
$result = array();
foreach ( $posts as $post ) {
$type = get_post_meta( $post->ID, 'brizy-font-file-type', true );
$result[ $type ] = wp_get_attachment_url( $post->ID );
}
return $result;
}
}

View File

@@ -0,0 +1,118 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/11/19
* Time: 10:59 AM
*/
class Brizy_Admin_Fonts_Main {
const CP_FONT = 'brizy-font';
const SVG_MIME = 'image/svg+xml';
/**
* @return Brizy_Admin_Fonts_Main
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* BrizyPro_Admin_Popups constructor.
*/
public function __construct() {
$urlBuilder = new Brizy_Editor_UrlBuilder();
$handler = new Brizy_Admin_Fonts_Handler( $urlBuilder, null );
if ( Brizy_Editor_User::is_user_allowed() ) {
add_action( 'wp_loaded', array( $this, 'initializeActions' ) );
add_filter( 'upload_mimes', array( $this, 'addFontTypes' ) );
add_filter( 'wp_check_filetype_and_ext', array( $this, 'wp_check_filetype_and_ext' ), 10, 4 );
}
}
public function initializeActions() {
Brizy_Admin_Fonts_Api::_init();
}
public function addFontTypes( $mime_types ) {
$mime_types['ttf'] = 'application/x-font-ttf';
$mime_types['eot'] = 'application/vnd.ms-fontobject';
$mime_types['woff'] = 'application/x-font-woff';
$mime_types['woff2'] = 'application/x-font-woff2';
return $mime_types;
}
/**
* @param $data
* @param $file
* @param $filename
* @param $mimes
* @param $real_mime
*
* @return array
*/
public function wp_check_filetype_and_ext( $data, $file, $filename, $mimes ) {
if ( ! $data['ext'] ) {
// Do basic extension validation and MIME mapping
$wp_filetype = wp_check_filetype( $filename, $mimes );
$ext = $wp_filetype['ext'];
$type = $wp_filetype['type'];
if ( $ext === 'ttf' ) {
return array( 'ext' => $ext, 'type' => 'application/x-font-ttf', 'proper_filename' => false );
}
if ( $ext === 'eot' ) {
return array( 'ext' => $ext, 'type' => 'application/vnd.ms-fontobject', 'proper_filename' => false );
}
if ( $ext === 'woff' ) {
return array( 'ext' => $ext, 'type' => 'application/x-font-woff', 'proper_filename' => false );
}
if ( $ext === 'woff2' ) {
return array( 'ext' => $ext, 'type' => 'application/x-font-woff2', 'proper_filename' => false );
}
}
return $data;
}
public static function registerCustomPosts() {
$labels = array(
'name' => _x( 'Fonts', 'post type general name' ),
);
register_post_type( self::CP_FONT,
array(
'labels' => $labels,
'public' => false,
'has_archive' => false,
'description' => __bt( 'brizy', 'Brizy' ) . ' ' . __( 'font', 'brizy' ) . '.',
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => false,
'capability_type' => 'page',
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'supports' => array( 'title', 'page-attributes' )
)
);
}
}

View File

@@ -0,0 +1,349 @@
<?php
class Brizy_Admin_Fonts_Manager {
/**
* Get all fonts as arrays
*
* @return array
*/
public function getAllFonts() {
global $wpdb;
$fonts = get_posts( array(
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'post_status' => 'publish',
'numberposts' => - 1,
'orderby' => 'ID',
'order' => 'ASC',
) );
$result = array();
foreach ( $fonts as $font ) {
$weights = $wpdb->get_results( $wpdb->prepare(
"SELECT m.meta_value FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} m ON m.post_id=p.ID && m.meta_key='brizy-font-weight'
WHERE p.post_parent=%d
",
array( $font->ID ) ), ARRAY_A
);
$result[] = array(
'id' => get_post_meta( $font->ID, 'brizy_post_uid', true ),
'family' => $font->post_title,
'type' => get_post_meta( $font->ID, 'brizy-font-type', true ),
'weights' => array_values( array_unique( array_map( function ( $v ) {
return $v['meta_value'];
}, $weights ) ) )
);
}
return $result;
}
/**
* @param $uid
*
* @return array|null
*/
public function getFont( $uid ) {
global $wpdb;
$fonts = get_posts( array(
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'post_status' => 'publish',
'meta_key' => 'brizy_post_uid',
'meta_value' => $uid,
'numberposts' => - 1,
'orderby' => 'ID',
'order' => 'DESC',
) );
if ( isset( $fonts[0] ) ) {
$font = $fonts[0];
} else {
return null;
}
return $this->getFontReturnData( $font );
}
/**
* @param $uid
*
* @return array|null
*/
public function getFontForExport( $uid ) {
global $wpdb;
$fonts = get_posts( array(
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'post_status' => 'publish',
'meta_key' => 'brizy_post_uid',
'meta_value' => $uid,
'numberposts' => - 1,
'orderby' => 'ID',
'order' => 'DESC',
) );
if ( isset( $fonts[0] ) ) {
$font = $fonts[0];
} else {
return null;
}
$fontData = $this->getFontReturnData( $font );
$files = $wpdb->get_results(
$wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} p WHERE p.post_parent=%d", array( $font->ID ) ),
ARRAY_A );
$weightFiles = array();
foreach ( $files as $fileId ) {
$weight = get_post_meta( $fileId['ID'], 'brizy-font-weight', true );
$type = get_post_meta( $fileId['ID'], 'brizy-font-file-type', true );
$weightFiles[ $weight ][ $type ] = get_attached_file( $fileId['ID'] );
}
$fontData['weights'] = $weightFiles;
return $fontData;
}
public function getFontByFamily( $uid, $family, $type ) {
$fonts = get_posts( array(
'title' => $family,
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'post_status' => 'publish',
'meta_key' => 'brizy-font-type',
'meta_value' => $type,
'numberposts' => - 1,
'orderby' => 'ID',
'order' => 'DESC',
) );
if ( isset( $fonts[0] ) ) {
$font = $fonts[0];
if ( $uid == get_post_meta( $font->ID, 'brizy_post_uid', true ) ) {
return $this->getFontReturnData( $font );
}
}
return null;
}
/**
* @param $uid
* @param $family
* @param $fontWeights
* @param $fontType
*
* @return int
* @throws Exception
*/
public function createFont( $uid, $family, $fontWeights, $fontType ) {
global $wpdb;
if ( $uid == '' ) {
throw new Exception( 'Invalid font uid' );
}
if ( $family == '' ) {
throw new Exception( 'Invalid font family' );
}
if ( $fontType == '' ) {
throw new Exception( 'Invalid font type' );
}
if ( ! is_array( $fontWeights ) || empty( $fontWeights ) ) {
throw new Exception( 'Invalid font weights' );
}
$font = $this->getFont( $uid );
if ( $font ) {
throw new Brizy_Admin_Fonts_Exception_DuplicateFont( 'This font already exists' );
}
// Need to require these files
if ( ! function_exists( 'media_handle_upload' ) ) {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
require_once( ABSPATH . "wp-admin" . '/includes/file.php' );
require_once( ABSPATH . "wp-admin" . '/includes/media.php' );
}
try {
$wpdb->query( 'START TRANSACTION' );
// create font post
$fontId = wp_insert_post( [
'post_title' => $family,
'post_name' => $family,
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'post_status' => 'publish',
] );
if ( ! $fontId || is_wp_error( $fontId ) ) {
throw new Exception( 'Unable to create font' );
}
update_post_meta( $fontId, 'brizy_post_uid', $uid );
update_post_meta( $fontId, 'brizy-font-type', $fontType );
// create font attachments
foreach ( $fontWeights as $weight => $weightType ) {
if ( count( $weightType ) == 0 ) {
throw new Exception( 'No font files provided' );
}
foreach ( $weightType as $type => $file ) {
$id = media_handle_sideload( $file, $fontId, "Attached font file" );
if ( ! $id || is_wp_error( $id ) ) {
Brizy_Logger::instance()->critical( 'Unable to handle font sideload', [ $id ] );
throw new Exception( 'Unable to handle font side load' );
}
update_post_meta( $id, 'brizy-font-weight', $weight );
update_post_meta( $id, 'brizy-font-file-type', $type );
}
}
$wpdb->query( 'COMMIT' );
return (int) $fontId;
} catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' );
Brizy_Logger::instance()->critical( 'Create font ERROR', [ $e->getMessage() ] );
throw new Exception( 'Unable to create font' );
}
}
/**
* @param $fontUid
*
* @return bool
* @throws Exception
*/
public function deleteFont( $fontUid ) {
global $wpdb;
if ( ! $fontUid ) {
throw new Exception( 'Invalid font uid' );
}
$font = get_posts( [
'post_type' => Brizy_Admin_Fonts_Main::CP_FONT,
'meta_query' => array(
array(
'key' => 'brizy_post_uid',
'value' => $fontUid
)
),
'posts_per_page' => - 1,
'orderby' => 'ID',
'order' => 'DESC',
] );
if ( count( $font ) > 0 ) {
$font = $font[0];
} else {
$font = null;
}
if ( ! $font ) {
throw new Exception( 'Font not found', 404 );
}
try {
$wpdb->query( 'START TRANSACTION ' );
// delete all attachments first
$attachments = get_attached_media( '', $font->ID );
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, 'true' );
}
// delete font
wp_delete_post( $font->ID );
$wpdb->query( 'COMMIT' );
} catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' );
Brizy_Logger::instance()->debug( 'Delete font ERROR', [ $e ] );
throw new Exception( 'Failed to delete font', 400 );
}
return true;
}
/**
* @param wpdb $wpdb
* @param $font
*
* @return array
*/
private function getFontReturnData( $font ) {
global $wpdb;
$weights = $wpdb->get_results( $wpdb->prepare(
"SELECT DISTINCT m.meta_value FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} m ON m.post_id=p.ID && p.post_parent=%d && m.meta_key='brizy-font-weight'
",
array( $font->ID ) ), ARRAY_A
);
return array(
'id' => get_post_meta( $font->ID, 'brizy_post_uid', true ),
'family' => $font->post_title,
'type' => get_post_meta( $font->ID, 'brizy-font-type', true ),
'weights' => array_map( function ( $v ) {
return $v['meta_value'];
}, $weights )
);
}
/**
* @param wpdb $wpdb
* @param $font
*
* @return array
*/
private function getFontReturnDataForExport( $font ) {
global $wpdb;
$weights = $wpdb->get_results( $wpdb->prepare(
"SELECT DISTINCT m.meta_value FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} m ON m.post_id=p.ID && p.post_parent=%d && m.meta_key='brizy-font-weight'
",
array( $font->ID ) ), ARRAY_A
);
return array(
'id' => get_post_meta( $font->ID, 'brizy_post_uid', true ),
'family' => $font->post_title,
'type' => get_post_meta( $font->ID, 'brizy-font-type', true ),
'weights' => array_map( function ( $v ) {
return $v['meta_value'];
}, $weights )
);
}
}

View File

@@ -0,0 +1,13 @@
{% for family,font in fonts %}
/* {{ family }} */
{% for weight,fontData in font %}
{% for type,font_url in fontData %}
@font-face {
font-family: '{{ family }}';
font-style: {{ weight|fontStyle }};
font-weight: {{ weight|fontWeight }};
src: local('{{ family }}'), url({{ font_url }}) format('{{ type | fontType }}');
}
{% endfor %}
{% endfor %}
{% endfor %}

View File

@@ -0,0 +1,356 @@
<?php
class Brizy_Admin_FormEntries {
const CP_FORM_ENTRY = 'brizy-form-entry';
const OPTION_SUBMIT_LOG = 'brizy-form-log';
const NONCE_KEY = 'form-log';
private $enableLog = true;
/**
* @return Brizy_Admin_FormLeads
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* Brizy_Admin_FormLeads constructor.
*/
public function __construct() {
if ( is_admin() && Brizy_Editor_User::is_administrator() ) {
add_action( 'admin_menu', array( $this, 'addSubmenuPage' ), 11 );
//add_action( 'admin_init', array( $this, 'handleEnableButton' ) );
//add_action( 'admin_footer', array( $this, 'addOnOffOption' ) );
add_action( 'admin_footer', array( $this, 'customStylesForList' ) );
add_action( 'admin_init', [ $this, 'export_leads' ] );
add_filter( 'post_row_actions', array( $this, 'filterRowActions' ), 10, 2 );
add_filter( 'manage_' . self::CP_FORM_ENTRY . '_posts_columns', array( $this, 'replaceTitleColumn' ) );
add_action( 'manage_' . self::CP_FORM_ENTRY . '_posts_custom_column', array(
$this,
'manageCustomColumns'
), 10, 2 );
}
$this->enableLog = get_option( self::OPTION_SUBMIT_LOG, true );
if ( $this->enableLog ) {
add_filter( 'brizy_form_submit_data', array( $this, 'form_submit_data' ), 10, 2 );
}
}
public function replaceTitleColumn( $columns ) {
$newColumns = array();
unset( $columns['title'] );
unset( $columns['date'] );
foreach ( $columns as $key => $column ) {
$newColumns[ $key ] = $column;
if ( $key == 'cb' ) {
$newColumns['data'] = __( 'Leads details', 'brizy' );
$newColumns['created_date'] = __( 'Date', 'brizy' );
}
}
return $newColumns;
}
public function manageCustomColumns( $column_name, $post_ID ) {
if ( $column_name == 'data' ) {
$post = get_post( $post_ID );
$data = json_decode( $post->post_content );
// We use html_entity_decode the user can insert text in some languages like German, Hindi, etc.
// and the function json_encode broke the json or encode the characters like this ud83dude00.
if ( isset( $data->formData ) ) {
foreach ( $data->formData as $i => $field ) {
$data->formData[ $i ]->name = html_entity_decode( $field->name, ENT_COMPAT, 'UTF-8' );
$data->formData[ $i ]->value = html_entity_decode( $field->value, ENT_COMPAT, 'UTF-8' );
}
}
echo Brizy_TwigEngine::instance( path_join( BRIZY_PLUGIN_PATH, "admin/views" ) )
->render( 'form-data.html.twig', array( 'data' => $data ) );
}
if ( $column_name == 'created_date' ) {
$post = get_post( $post_ID );
echo get_the_date( '', $post );
}
}
/**
* @param $actions
* @param $post
*
* @return mixed
*/
public function filterRowActions( $actions, $post ) {
$is_allowed = Brizy_Editor_User::is_user_allowed();
if ( ! $is_allowed ) {
return $actions;
}
if ( $post->post_type != self::CP_FORM_ENTRY ) {
return $actions;
}
unset( $actions['edit'] );
unset( $actions['inline hide-if-no-js'] );
unset( $actions['view'] );
unset( $actions['trash'] );
return $actions;
}
public function addSubmenuPage() {
add_submenu_page( Brizy_Admin_Settings::menu_slug(), __( 'Leads', 'brizy' ), __( 'Leads', 'brizy' ), 'manage_options', 'edit.php?post_type=' . self::CP_FORM_ENTRY, null );
}
public function handleEnableButton() {
if ( ! isset( $_REQUEST['hash'] ) || ! wp_verify_nonce( $_REQUEST['hash'], self::NONCE_KEY ) ) {
return;
}
if ( isset( $_REQUEST['enabled-form-log'] ) ) {
update_option( self::OPTION_SUBMIT_LOG, $_REQUEST['enabled-form-log'] == 1 ? true : false );
wp_redirect( admin_url( 'edit.php?post_type=' . self::CP_FORM_ENTRY ) );
exit;
}
}
public function addOnOffOption() {
$screen = get_current_screen();
if ( self::CP_FORM_ENTRY == $screen->post_type ) {
if ( $this->enableLog ) {
$label = __( 'Disable', 'brizy' );
$class = 'disableFormLogs';
$val = 0;
} else {
$label = __( 'Enable ', 'brizy' );
$class = 'enableFormLogs';
$val = 1;
}
$hash = wp_create_nonce( self::NONCE_KEY );
$url = 'edit.php?post_type=' . self::CP_FORM_ENTRY . '&enabled-form-log=' . $val . '&hash=' . $hash;
?>
<script>
jQuery('<a href="<?php echo admin_url( $url )?>" class="page-title-action <?php echo $class;?>"><?php echo $label;?></a>')
.insertBefore(jQuery('.wp-header-end'));
</script>
<style>
.wrap .page-title-action.disableFormLogs {
background: red !important;
color: white !important;
}
.enableFormLogs {
background: green !important;
color: white !important;
}
.subsubsub .publish {
display: none;
}
</style>
<?php
}
}
public function customStylesForList() {
$screen = get_current_screen();
if ( self::CP_FORM_ENTRY == $screen->post_type ) {
$disable = get_posts( [ 'post_type' => self::CP_FORM_ENTRY,
'posts_per_page' => 1
] ) ? '' : ' brz-leads-export-disable';
?>
<style>
.subsubsub {
display: none;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$($(".wrap h1")[0]).append($('#brz-leads-export-tpl-buttons').html());
});
</script>
<template id="brz-leads-export-tpl-buttons">
<a class="brz-leads-export add-new-h2<?php echo $disable; ?>"
href="<?php echo admin_url( 'edit.php?post_type=' . self::CP_FORM_ENTRY . '&brizy-export-leads=' . wp_create_nonce( 'brizy-admin-export-leads' ) ); ?>">
<?php esc_html_e( 'Export to .csv', 'brizy' ); ?>
</a>
</template>
<?php
}
}
public function export_leads() {
if ( ! current_user_can( 'manage_options' ) || ! isset( $_GET['brizy-export-leads'] ) || ! wp_verify_nonce( $_GET['brizy-export-leads'], 'brizy-admin-export-leads' ) ) {
return;
}
$leads = get_posts( [ 'post_type' => self::CP_FORM_ENTRY, 'posts_per_page' => - 1 ] );
if ( ! $leads ) {
return;
}
$cols = [];
$data = [];
foreach ( $leads as $lead ) {
$lead_fields = json_decode( $lead->post_content, true );
if ( empty( $lead_fields['formData'] ) ) {
continue;
}
$data[] = $lead_fields['formData'];
foreach ( $lead_fields['formData'] as $field ) {
if ( ! in_array( $field['label'], $cols ) ) {
$cols[] = $field['label'];
}
}
}
if ( empty( $data ) || empty( $cols ) ) {
return;
}
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename=leads.csv' );
header( 'Pragma: no-cache' );
header( 'Expires: 0' );
$fp = fopen( 'php://output', 'wb' );
fputcsv( $fp, $cols );
$cols = array_flip( $cols );
$range = count( $cols );
foreach ( $data as $lines ) {
$val = array_fill( 0, $range, '' );
foreach ( $lines as $line ) {
$val[ html_entity_decode( $cols[ $line['label'] ], ENT_COMPAT, 'UTF-8' ) ] = html_entity_decode( $line['value'], ENT_COMPAT, 'UTF-8' );
}
fputcsv( $fp, $val );
}
fclose( $fp );
die();
}
/**
* @param $fields
* @param Brizy_Editor_Forms_Form $form
*
* @return mixed
*/
public function form_submit_data( $fields, $form ) {
foreach ( $fields as $i => $field ) {
if ( $field->name == 'g-recaptcha-response' ) {
unset( $fields[ $i ] );
$fields = array_values( $fields );
break;
}
}
$title = '';
foreach ( $fields as $i => $field ) {
if ( strtolower( $field->type ) == 'email' ) {
$title = $field->value;
}
// We use htmlentities the user can insert text in some languages like German, Hindi, etc.
// and the function json_encode broke the json or encode the characters.
$fields[ $i ]->name = htmlentities( $field->name, ENT_COMPAT | ENT_HTML401, 'UTF-8' );
$fields[ $i ]->value = htmlentities( $field->value, ENT_COMPAT | ENT_HTML401, 'UTF-8' );
}
$params = array(
'post_title' => $title,
'post_type' => self::CP_FORM_ENTRY,
'post_status' => 'publish',
'post_content' => json_encode( array( 'formId' => $form->getId(),
'formData' => $fields
), JSON_UNESCAPED_UNICODE )
);
wp_insert_post( $params );
return $fields;
}
static public function registerCustomPost() {
$labels = array(
'name' => _x( 'Leads', 'post type general name', 'brizy' ),
'singular_name' => _x( 'Lead', 'post type singular name', 'brizy' ),
'menu_name' => _x( 'Leads', 'admin menu', 'brizy' ),
'name_admin_bar' => _x( 'Lead', 'add new on admin bar', 'brizy' ),
'add_new' => __( 'Add New', 'brizy' ),
'add_new_item' => __( 'Add New Lead', 'brizy' ),
'new_item' => __( 'New Lead', 'brizy' ),
'edit_item' => __( 'Edit Lead', 'brizy' ),
'view_item' => __( 'View Lead', 'brizy' ),
'all_items' => __( 'Leads', 'brizy' ),
'search_items' => __( 'Search Leads', 'brizy' ),
'parent_item_colon' => __( 'Parent Leads:', 'brizy' ),
'not_found' => __( 'No Leads found.', 'brizy' ),
'not_found_in_trash' => __( 'No Leads found in Trash.', 'brizy' )
);
register_post_type( self::CP_FORM_ENTRY,
array(
'labels' => $labels,
'public' => false,
'has_archive' => false,
'description' => __( 'Leads', 'brizy' ),
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => false, //Brizy_Admin_Settings::menu_slug(),
'query_var' => false,
'rewrite' => array( 'slug' => self::CP_FORM_ENTRY ),
//'map_meta_cap' => true,
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'supports' => array( 'title' ),
'menu_position' => 15,
'capability_type' => 'post',
'capabilities' => array(
'create_posts' => 'do_not_allow', // false < WP 4.5, credit @Ewout
),
'map_meta_cap' => true,
)
);
}
}

View File

@@ -0,0 +1,41 @@
<?php
use Gaufrette\Adapter\Local as OriginalLocalAdapter;
class Brizy_Admin_Guafrette_LocalAdapter extends OriginalLocalAdapter{
private $create;
private $mode;
/**
* @param string $directory Directory where the filesystem is located
* @param bool $create Whether to create the directory if it does not
* exist (default FALSE)
* @param int $mode Mode for mkdir
*
* @throws RuntimeException if the specified directory does not exist and
* could not be created
*/
public function __construct($directory, $create = false, $mode = 0777)
{
$this->directory = Brizy_Admin_Guafrette_Path::normalize($directory);
if (is_link($this->directory)) {
$this->directory = realpath($this->directory);
}
$this->create = $create;
$this->mode = $mode;
}
protected function normalizePath($path)
{
$path = Brizy_Admin_Guafrette_Path::normalize($path);
if (0 !== strpos($path, $this->directory)) {
throw new \OutOfBoundsException(sprintf('The path "%s" is out of the filesystem.', $path));
}
return $path;
}
}

View File

@@ -0,0 +1,46 @@
<?php
use Gaufrette\Util\Path as OriginalPath;
/**
* Path utils.
*
* @author Antoine Hérault <antoine.herault@gmail.com>
*/
class Brizy_Admin_Guafrette_Path extends OriginalPath
{
/**
* Normalizes the given path.
*
* @param string $path
*
* @return string
*/
public static function normalize($path)
{
$path = str_replace('\\', '/', $path);
$prefix = static::getAbsolutePrefix($path);
$path = substr($path, strlen($prefix));
$parts = array_filter(explode('/', $path), 'strlen');
$tokens = array();
foreach ($parts as $part) {
switch ($part) {
case '.':
continue 2;
case '..':
if (0 !== count($tokens)) {
array_pop($tokens);
continue 2;
} elseif (!empty($prefix)) {
continue 2;
}
default:
$tokens[] = $part;
}
}
return $prefix.implode('/', $tokens);
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/11/19
* Time: 10:59 AM
*/
class Brizy_Admin_Json_Main {
/**
* @return Brizy_Admin_Json_Main|mixed
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* Brizy_Admin_Json_Main constructor.
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function __construct() {
if ( Brizy_Editor_Storage_Common::instance()->get( 'json-upload', false ) ) {
$this->enableJsonUpload();
}
}
public function addJsonMimeType($mimes) {
$mimes['json'] = 'application/json';
return $mimes;
}
public function enableJsonUpload() {
add_filter('upload_mimes', [$this,'addJsonMimeType']);
}
public function disableJsonUpload() {
remove_filter('upload_mimes', [$this,'addJsonMimeType']);
}
}

View File

@@ -0,0 +1,344 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 7/18/18
* Time: 10:48 AM
*/
class Brizy_Admin_Layouts_Api extends Brizy_Admin_AbstractApi {
const nonce = 'brizy-api';
const GET_LAYOUT_BY_UID_ACTION = '-get-layout-by-uid';
const GET_LAYOUTS_ACTION = '-get-layouts';
const CREATE_LAYOUT_ACTION = '-create-layout';
const UPDATE_LAYOUT_ACTION = '-update-layout';
const DELETE_LAYOUT_ACTION = '-delete-layout';
const DOWNLOAD_LAYOUTS = '-download-layouts';
const UPLOAD_LAYOUTS = '-upload-layouts';
/**
* @return Brizy_Admin_Layouts_Api
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
protected function getRequestNonce() {
return $this->param( 'hash' );
}
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' ) );
}
public function actionDownloadLayouts() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( 400, 'Invalid layout uid param' );
}
try {
$bockManager = new Brizy_Admin_Layouts_Manager();
$uids = [];
// this is not a very eficien solution if you have a big array of uids
$explode = explode( ',', $this->param( 'uid' ) );
$items = array_map( function ( $auid ) use ( $uids, $bockManager ) {
list( $uid, $isPro ) = explode( ':', $auid );
$uids[] = $uid;
$item = new Brizy_Editor_Zip_ArchiveItem( $uid, $isPro );
if ( $post = $bockManager->getEntity( $uid ) ) {
$item->setPost( $post );
return $item;
}
return null;
}, $explode );
$items = array_filter( $items );
if ( count( $items ) == 0 ) {
$this->error( 404, __( 'There are no layouts to be archived' ) );
}
$zipPath = "Layout-" . date( DATE_ATOM ) . ".zip";
$fontManager = new Brizy_Admin_Fonts_Manager();
$zip = new Brizy_Editor_Zip_Archiver( Brizy_Editor_Project::get(),
$fontManager,
BRIZY_EDITOR_VERSION );
$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-Transfer-Encoding: binary" );
echo file_get_contents( $zipPath );
exit;
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionGetLayoutByUid() {
$this->verifyNonce( self::nonce );
try {
$uid = $this->param( 'uid' );
if ( ! $uid ) {
$this->error( 400, 'Invalid layout id' );
}
$fields = $this->param( 'fields' ) ? $this->param( 'fields' ) : [];
$layoutManager = new Brizy_Admin_Layouts_Manager();
$layout = $layoutManager->getEntity( $this->param( 'uid' ) );
$layout = apply_filters( 'brizy_get_layout', $layout, $this->param( 'uid' ), $layoutManager );
if ( ! $layout ) {
$this->error( 404, 'Block not found' );
}
$this->success( $layout->createResponse( $fields ) );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionGetLayouts() {
$this->verifyNonce( self::nonce );
try {
$layoutManager = new Brizy_Admin_Layouts_Manager();
$fields = $this->param( 'fields' ) ? $this->param( 'fields' ) : [];
$layouts = $layoutManager->getEntities( array() );
$layouts = apply_filters( 'brizy_get_layouts',
$layoutManager->createResponseForEntities( $layouts, $fields ),
$fields,
$layoutManager );
$this->success( $layouts );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionCreateLayout() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( 400, 'Invalid uid' );
}
if ( ! $this->param( 'data' ) ) {
$this->error( 400, 'Invalid data' );
}
if ( ! $this->param( 'meta' ) ) {
$this->error( 400, 'Invalid meta data' );
}
if ( ! $this->param( 'media' ) ) {
$this->error( 400, 'Invalid media data provided' );
}
try {
$editorData = stripslashes( $this->param( 'data' ) );
$layoutManager = new Brizy_Admin_Layouts_Manager();
$layout = $layoutManager->createEntity( $this->param( 'uid' ), 'publish' );
$layout->setMedia( stripslashes( $this->param( 'media' ) ) );
$layout->setMeta( stripslashes( $this->param( 'meta' ) ) );
$layout->set_editor_data( $editorData );
$layout->set_needs_compile( true );
//$layout->setCloudUpdateRequired( true );
$layout->setDataVersion( 1 );
$layout->save();
do_action( 'brizy_layout_created', $layout );
do_action( 'brizy_global_data_updated' );
$this->success( $layout->createResponse() );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionUpdateLayout() {
$this->verifyNonce( self::nonce );
try {
if ( ! $this->param( 'uid' ) ) {
$this->error( '400', 'Invalid uid' );
}
if ( ! $this->param( 'data' ) ) {
$this->error( '400', 'Invalid data' );
}
if ( ! $this->param( 'meta' ) ) {
$this->error( 400, 'Invalid meta data' );
}
if ( ! $this->param( 'dataVersion' ) ) {
$this->error( 400, 'Invalid data version' );
}
$layoutManager = new Brizy_Admin_Layouts_Manager();
$layout = $layoutManager->getEntity( $this->param( 'uid' ) );
if ( ! $layout ) {
$this->error( 400, 'Layout not found' );
}
/**
* @var Brizy_Editor_Layout $layout ;
*/
$layout->setMeta( stripslashes( $this->param( 'meta' ) ) );
$layout->set_editor_data( stripslashes( $this->param( 'data' ) ) );
$layout->setDataVersion( $this->param( 'dataVersion' ) );
if ( (int) $this->param( 'is_autosave' ) ) {
$layout->save( 1 );
} else {
$layout->save();
do_action( 'brizy_layout_updated', $layout );
do_action( 'brizy_global_data_updated' );
}
$this->success( $layout->createResponse() );
} catch ( Exception $exception ) {
$this->error( 400, $exception->getMessage() );
}
}
public function actionDeleteLayout() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'uid' ) ) {
$this->error( '400', 'Invalid uid' );
}
$layoutManager = new Brizy_Admin_Layouts_Manager();
$layout = $layoutManager->getEntity( $this->param( 'uid' ) );
do_action( 'brizy_layout_delete', $this->param( 'uid' ) );
if ( $layout ) {
do_action( 'brizy_layout_deleted', $layout );
do_action( 'brizy_global_data_deleted' );
$layoutManager->deleteEntity( $layout );
$this->success( null );
}
$this->error( '404', 'Layout not found' );
}
// /**
// * @param $uid
// * @param $postType
// *
// * @return string|null
// */
// private function getLayoutIdByUid( $uid ) {
// global $wpdb;
//
// $prepare = $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} p
// JOIN {$wpdb->postmeta} pm ON
// pm.post_id=p.ID and
// meta_key='brizy_post_uid' and
// meta_value='%s'
// ORDER BY p.ID DESC
// LIMIT 1", array( $uid, ) );
//
// return $wpdb->get_var( $prepare );
// }
//
// /**
// * @param $id
// * @param $postType
// *
// * @return Brizy_Editor_Layout|null
// * @throws Brizy_Editor_Exceptions_NotFound
// */
// private function getLayout( $uid ) {
//
// $postId = $this->getLayoutIdByUid( $uid );
//
// if ( $postId ) {
// return Brizy_Editor_Layout::get( $postId );
// }
//
// return null;
//
// }
//
// /**
// * @param $uid
// * @param $status
// * @param $type
// *
// * @return Brizy_Editor_Layout|null
// * @throws Brizy_Editor_Exceptions_NotFound
// */
// private function createLayout( $uid, $status, $type ) {
// $name = md5( time() );
// $post = wp_insert_post( array(
// 'post_title' => $name,
// 'post_name' => $name,
// 'post_status' => $status,
// 'post_type' => $type
// ) );
//
// if ( $post ) {
// $brizyPost = Brizy_Editor_Layout::get( $post, $uid );
// $brizyPost->set_uses_editor( true );
// $brizyPost->set_needs_compile( true );
// $brizyPost->setDataVersion( 1 );
//
// return $brizyPost;
// }
//
// throw new Exception( 'Unable to create layout' );
// }
//
//
// /***
// * @param $postUid
// *
// * @return false|WP_Post|null
// */
// private function deleteLayout( $postUid ) {
//
// $postId = $this->getLayoutIdByUid( $postUid );
//
// return wp_delete_post( $postId );
// }
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/11/19
* Time: 10:59 AM
*/
class Brizy_Admin_Layouts_Main {
const CP_LAYOUT = 'brizy-layout';
/**
* @return Brizy_Admin_Layouts_Main
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
$instance->initialize();
}
return $instance;
}
public function initialize() {
add_action( 'wp_loaded', array( $this, 'initializeActions' ) );
add_filter( 'brizy_supported_post_types', array( $this, 'populateSupportedPosts' ) );
}
static public function registerCustomPosts() {
$labels = array(
'name' => _x( 'Layouts', 'post type general name' ),
);
register_post_type( self::CP_LAYOUT,
array(
'labels' => $labels,
'public' => false,
'has_archive' => false,
'description' => __( 'Layout.', 'brizy' ),
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => false,
'capability_type' => 'page',
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'supports' => array( 'title', 'revisions', 'page-attributes' )
)
);
}
/**
* @param $types
*
* @return array
*/
public function populateSupportedPosts( $types ) {
$types[] = self::CP_LAYOUT;
return $types;
}
public function initializeActions() {
Brizy_Admin_Layouts_Api::_init();
}
}

View File

@@ -0,0 +1,199 @@
<?php
class Brizy_Admin_Layouts_Manager extends Brizy_Admin_Entity_AbstractManager {
/**
* @var string
*/
private $blockType;
/**
* Brizy_Admin_Layouts_Manager constructor.
*
* @throws Exception
*/
public function __construct() {
$this->blockType = Brizy_Admin_Layouts_Main::CP_LAYOUT;
}
/**
* @param $args
*
* @return Brizy_Editor_Layout[]
* @throws Exception
*/
public function getEntities( $args ) {
return $this->getEntitiesByType( $this->blockType, $args );
}
/**
* @param $uid
*
* @return Brizy_Editor_Layout
* @throws Exception
*/
public function getEntity( $uid ) {
return $this->getEntityUidAndType( $uid, $this->blockType );
}
/**
* @param $uid
* @param string $status
*
* @return mixed|null+
*/
public function createEntity( $uid, $status = 'publish' ) {
return $this->createEntityByType( $uid, $this->blockType, $status );
}
/**
* @param $post
* @param null $uid
*
* @return Brizy_Editor_Layout|Brizy_Editor_Post|mixed$uid
* @throws Exception
*/
protected function convertWpPostToEntity( $post, $uid = null ) {
return Brizy_Editor_Layout::get( $post, $uid );
}
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
// /**
// * @param $type
// * @param $arags
// * @param array $fields
// *
// * @return array
// * @throws Brizy_Editor_Exceptions_NotFound
// */
// public function getAllLayouts( $arags, $fields = array() ) {
// $layouts = [];
// try {
// $layouts = $this->getLocalLayouts( $arags, $fields );
//
// $versions = $this->cloud->getCloudEditorVersions();
// $cloudBlocks = $this->cloud->getLayouts( array( 'fields' => array( 'uid', 'meta' ) ) );
//
// if ( $this->cloud && $versions['sync'] == BRIZY_SYNC_VERSION ) {
//
// foreach ( (array) $cloudBlocks as $cblock ) {
// $existingBlock = false;
// foreach ( $layouts as $block ) {
// if ( $cblock->uid == $block['uid'] ) {
// $existingBlock = true;
// }
// }
//
// if ( ! $existingBlock ) {
// $localLayout = $this->getLayoutByUid( $cblock->uid );
//
// if ( $localLayout ) {
// $cblock->synchronized = $localLayout->isSynchronized( $this->cloud->getBrizyProject()->getCloudAccountId() );
// } else {
// $cblock->synchronized = false;
// }
//
// if ( in_array( 'isCloudEntity', $fields ) ) {
// $cblock->isCloudEntity = true;
// }
//
// if ( in_array( 'synchronizable', $fields ) ) {
// $cblock->synchronizable = true;
// }
//
// $cblock->synchronizable = true;
// $layouts[] = (array) $cblock;
// }
// }
// }
// } catch ( Exception $e ) {
//
// }
//
// return $layouts;
// }
// /**
// * @param $uid
// * @param array $fields
// *
// * @return array|mixed|null
// * @throws Exception
// */
// public function getLayoutByUid( $uid, $fields = array() ) {
//
// $layout = $this->getLocalLayout( $uid, $fields );
// $versions = $this->cloud->getCloudEditorVersions();
//
// if ( ! $layout && $this->cloud && $versions['sync'] == BRIZY_SYNC_VERSION ) {
// $bridge = new Brizy_Admin_Cloud_LayoutBridge( $this->cloud );
// $bridge->import( $uid );
//
// $layout = $this->getLocalLayout( $uid, $fields );
// }
//
// return $layout;
// }
//
//
// /**
// * @param array $arags
// * @param array $fields
// *
// * @return array
// * @throws Exception
// */
// public function getLocalLayouts( $arags = array(), $fields = array() ) {
// $filterArgs = array(
// 'post_type' => Brizy_Admin_Layouts_Main::CP_LAYOUT,
// 'posts_per_page' => - 1,
// 'post_status' => 'any',
// 'orderby' => 'ID',
// 'order' => 'ASC',
// );
// $filterArgs = array_merge( $filterArgs, $arags );
//
// $wpBlocks = get_posts( $filterArgs );
// $layouts = array();
//
// foreach ( $wpBlocks as $wpPost ) {
// $layouts[] = \Brizy_Editor_Layout::get( $wpPost )->createResponse( $fields );
// }
//
// return $layouts;
// }
// /**
// * @param $uid
// * @param array $fields
// *
// * @return array|mixed|null
// * @throws Exception
// */
// public function getLocalLayout( $uid, $fields = array() ) {
// $blocks = get_posts( array(
// 'post_type' => Brizy_Admin_Layouts_Main::CP_LAYOUT,
// 'post_status' => 'publish',
// 'meta_key' => 'brizy_post_uid',
// 'meta_value' => $uid,
// 'numberposts' => - 1,
// 'orderby' => 'ID',
// 'order' => 'DESC',
// ) );
//
// if ( isset( $blocks[0] ) ) {
// $block = \Brizy_Editor_Layout::get( $blocks[0] )->createResponse( $fields );
// } else {
// $block = null;
// }
//
// return $block;
// }
}

View File

@@ -0,0 +1,613 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Admin_Main {
public static function instance() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* Brizy_Admin_Main constructor.
*/
protected function __construct() {
if ( ! Brizy_Editor_User::is_user_allowed() ) {
return;
}
// enqueue admin scripts
add_action( 'admin_enqueue_scripts', array( $this, 'action_register_static' ) );
if ( current_user_can( Brizy_Admin_Capabilities::CAP_EDIT_WHOLE_PAGE ) || Brizy_Editor_User::is_administrator() ) {
add_action( 'admin_post__brizy_admin_editor_enable', array(
$this,
'action_request_enable'
) ); // enable editor for a post
add_action( 'admin_post__brizy_admin_editor_disable', array(
$this,
'action_request_disable'
) ); // disable editor for a post
add_action( 'admin_post__brizy_change_template', array(
$this,
'action_change_template'
) ); // action to change template from editor
add_action( 'edit_form_after_title', [ $this, 'action_add_enable_disable_buttons' ], -1 ); // add button to enable disable editor
}
add_action( 'before_delete_post', array( $this, 'action_delete_page' ) );
add_filter( 'page_row_actions', array( $this, 'filter_add_brizy_edit_row_actions' ), 10, 2 );
add_filter( 'post_row_actions', array( $this, 'filter_add_brizy_edit_row_actions' ), 10, 2 );
add_filter( 'admin_body_class', array( $this, 'filter_add_body_class' ), 10, 2 );
add_action( 'admin_head', array( $this, 'hide_editor' ) );
add_action( 'admin_head', array( $this, 'custom_css_btns' ) );
add_action( 'brizy_global_data_updated', array( $this, 'global_data_updated' ) );
add_filter( 'plugin_action_links_' . BRIZY_PLUGIN_BASE, array( $this, 'plugin_action_links' ) );
add_filter( 'display_post_states', array( $this, 'display_post_states' ), 10, 2 );
//add_filter( 'save_post', array( $this, 'save_post' ), 10, 2 );
add_filter( 'wp_import_existing_post', array( $this, 'handleNewProjectPostImport' ), 10, 2 );
add_filter( 'wp_import_post_meta', array( $this, 'handleNewProjectMetaImport' ), 10, 3 );
add_filter( 'wp_import_posts', array( $this, 'handlePostsImport' ) );
add_filter( 'save_post', array( $this, 'save_focal_point' ) );
add_filter( 'admin_post_thumbnail_html', array( $this, 'addFocalPoint' ), 10, 3 );
}
public function addFocalPoint( $content, $postId, $thumbId ) {
if ( ! $thumbId ) {
return $content;
}
$urlBuilder = new Brizy_Editor_UrlBuilder();
$post = get_post( $postId );
$post_type_object = get_post_type_object( $post->post_type );
$twigEngine = Brizy_TwigEngine::instance( BRIZY_PLUGIN_PATH . "/admin/views/" );
$focalPoint = get_post_meta( $postId, 'brizy_attachment_focal_point', true );
if ( ! $focalPoint ) {
$focalPoint = array( 'x' => 50, 'y' => 50 );
}
$params = array(
'focalPoint' => $focalPoint,
'thumbnailId' => $thumbId,
'thumbnailSrc' => wp_get_attachment_image_src( $thumbId, 'original' ),
'postId' => $postId,
'edit_update_label' => __( 'Edit or Update Image' ),
'remove_label' => $post_type_object->labels->remove_featured_image,
'pluginUrl' => $urlBuilder->editor_build_url()
);
return $twigEngine->render( 'featured-image.html.twig', $params );
}
/**
* @param int $postId
*/
public function action_delete_page( $postId = null ) {
try {
if ( wp_is_post_autosave( $postId ) || wp_is_post_revision( $postId ) ) {
return;
}
$urlBuilder = new Brizy_Editor_UrlBuilder( Brizy_Editor_Project::get(), $postId );
$pageUploadPath = $urlBuilder->page_upload_path( "assets/images" );
Brizy_Admin_FileSystem::deleteAllDirectories( $pageUploadPath );
$pageUploadPath = $urlBuilder->page_upload_path( "assets/icons" );
Brizy_Admin_FileSystem::deleteFilesAndDirectory( $pageUploadPath );
} catch ( Exception $e ) {
// ignore this.
}
}
/**
* @param array $post_states
* @param WP_Post $post
*
* @return mixed
*/
public function display_post_states( $post_states, $post ) {
try {
if ( Brizy_Editor_Entity::isBrizyEnabled($post->ID) ) {
$post_states['brizy'] = __( Brizy_Editor::get()->get_name() );
}
} catch ( Exception $e ) {
// ignore this.
}
return $post_states;
}
// public function save_post( $post_id, $post ) {
// try {
//
// $brizy_post = null;
//
// $parent_id = wp_is_post_revision( $post_id );
//
// if ( $parent_id ) {
// $brizy_post = Brizy_Editor_Post::get( $parent_id );
//
// if ( $brizy_post->uses_editor() ) {
// $brizy_post->save( $post_id );
// }
// }
//
// } catch ( Exception $e ) {
// Brizy_Logger::instance()->exception( $e );
//
// return;
// }
// }
/**
* @param $post_id
*/
public function save_focal_point( $post_id ) {
if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) {
return;
}
if ( isset( $_REQUEST['_thumbnail_focal_point_x'], $_REQUEST['_thumbnail_focal_point_y'] ) && $post_id ) {
update_post_meta( $post_id, 'brizy_attachment_focal_point', [
'x' => (int) $_REQUEST['_thumbnail_focal_point_x'],
'y' => (int) $_REQUEST['_thumbnail_focal_point_y']
] );
}
}
public function hide_editor() {
$post_type = get_post_type();
if ( in_array( $post_type, Brizy_Editor::get()->supported_post_types() ) ) {
$p = get_post();
try {
$is_using_brizy = Brizy_Editor_Entity::isBrizyEnabled($p->ID);
} catch ( Exception $e ) {
$is_using_brizy = false;
}
if ( $is_using_brizy ) {
//remove_post_type_support( $post_type, 'editor' );
// hide the default editor
add_filter( 'the_editor', function ( $editor_html ) {
$args = func_get_args();
if ( strpos( $editor_html, 'id="wp-content-editor-container"' ) !== false ) {
return "<div style='display: none'>{$editor_html}</div>";
}
return $editor_html;
} );
}
}
}
public function custom_css_btns() {
$prefix = 'brizy';
if ( class_exists( 'BrizyPro_Admin_WhiteLabel' ) && BrizyPro_Admin_WhiteLabel::_init()->getEnabled() ) {
$prefix = method_exists( 'BrizyPro_Admin_WhiteLabel', 'getPrefix' ) ? BrizyPro_Admin_WhiteLabel::_init()->getPrefix() : get_option( 'brizy_prefix', 'brizy' );
}
$cssId = '#toplevel_page_' . $prefix . '-settings';
$svg = __bt( 'brizy-logo', plugins_url( '../admin/static/img/brizy-logo.svg', __FILE__ ) );
echo
'<style>' .
$cssId . ' .wp-menu-image::before {
background-color: rgba(240,246,252,.6);
content: "\00a0";
-webkit-mask: url(' . $svg . ') no-repeat center;
mask: url(' . $svg . ') no-repeat center;
mask-size: contain;
-webkit-mask-size: contain;
}' .
$cssId . '.wp-has-current-submenu .wp-menu-image::before {
background-color: white;
}' .
$cssId . '.wp-not-current-submenu:hover .wp-menu-image::before {
background-color: #72aee6;
}
</style>';
}
public function plugin_action_links( $links ) {
$settings_link = sprintf( '<a href="%s">%s</a>', admin_url( 'admin.php?page=' . Brizy_Admin_Settings::menu_slug() ), __( 'Settings', 'brizy' ) );
array_unshift( $links, $settings_link );
if ( ! class_exists( 'BrizyPro_Main' ) ) {
$links['go_pro'] = sprintf(
'<a href="%1$s" target="_blank" style="color:#39b54a;font-weight:700;">%2$s</a>',
Brizy_Config::GO_PRO_DASHBOARD_URL,
__( 'Go Pro', 'brizy' )
);
}
return $links;
}
/**
* @internal
*/
public function action_register_static() {
$urlBuilder = new Brizy_Editor_UrlBuilder();
wp_enqueue_style(
Brizy_Editor::get_slug() . '-admin-css',
$urlBuilder->plugin_url( 'admin/static/css/style.css' ),
array(),
BRIZY_VERSION
);
wp_enqueue_script(
Brizy_Editor::get_slug() . '-admin-js',
$urlBuilder->plugin_url( 'admin/static/js/script.js' ),
array( 'jquery', 'underscore' ),
BRIZY_VERSION,
true
);
wp_enqueue_script(
Brizy_Editor::get_slug() . '-admin-featured-image-js',
$urlBuilder->plugin_url( 'admin/static/js/featured-image.js' ),
array( 'jquery', 'underscore' ),
BRIZY_VERSION,
true
);
$get_post_focal = get_post_meta( get_the_ID(), 'brizy_attachment_focal_point', true );
wp_localize_script(
Brizy_Editor::get_slug() . '-admin-js',
'Brizy_Admin_Data',
array(
'url' => admin_url( 'admin-ajax.php' ),
'prefix' => Brizy_Editor::prefix(),
'pluginUrl' => $urlBuilder->editor_build_url(),
'ruleApiHash' => wp_create_nonce( Brizy_Admin_Rules_Api::nonce ),
'id' => get_the_ID(),
'page' => array(
'focalPoint' => $get_post_focal ? $get_post_focal : array( 'x' => 50, 'y' => 50 )
),
'actions' => array(
'enable' => '_brizy_admin_editor_enable',
'disable' => '_brizy_admin_editor_disable',
),
'editorVersion' => BRIZY_EDITOR_VERSION,
'pluginVersion' => BRIZY_VERSION,
'nonce' => wp_create_nonce( 'brizy-admin-nonce' ),
'l10n' => [
'deactivateFeedbackSubmitBtn' => __( 'Submit & Deactivate', 'brizy' ),
'deactivateFeedbackSkipBtn' => __( 'Skip & Deactivate', 'brizy' ),
]
)
);
}
/**
* @internal
*/
public function action_request_enable() {
if ( ! isset( $_REQUEST['post'] ) || ! ( $p = get_post( (int) $_REQUEST['post'] ) ) ) {
Brizy_Admin_Flash::instance()->add_error( 'Invalid Request.' );
wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
exit();
}
try {
$this->enable_brizy_for_post( $p );
} catch ( Exception $e ) {
Brizy_Admin_Flash::instance()->add_error( 'Unable to create the page. Please try again later.' );
wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
}
}
/**
* @internal
*/
public function action_request_disable() {
if ( ! isset( $_REQUEST['post'] ) || ! ( $p = get_post( $_REQUEST['post'] ) ) ) {
Brizy_Admin_Flash::instance()->add_error( 'Invalid Request.' );
wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
exit();
}
try {
do_action( 'brizy_before_disable_for_post', $p );
Brizy_Editor_Entity::setBrizyEnabled($p,false);
do_action( 'brizy_after_disable_for_post', $p );
} catch ( Brizy_Editor_Exceptions_Exception $exception ) {
Brizy_Admin_Flash::instance()->add_error( 'Unable to disabled the editor. Please try again later.' );
}
wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
exit;
}
public function action_change_template() {
if ( ! isset( $_REQUEST['post'], $_REQUEST['template'] ) || ! ( $p = get_post( $_REQUEST['post'] ) ) ) {
Brizy_Admin_Flash::instance()->add_error( 'Invalid Request.' );
wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
exit();
}
try {
Brizy_Editor_Post::get( $p->ID )->set_template( $_REQUEST['template'] );
wp_safe_redirect( Brizy_Editor_Post::get( $p->ID )->edit_url() );
exit;
} catch ( Brizy_Editor_Exceptions_Exception $exception ) {
Brizy_Admin_Flash::instance()->add_error( 'Unable to disabled the editor. Please try again later.' );
}
wp_safe_redirect( $_SERVER['HTTP_REFERER'] );
exit;
}
/**
* @internal
**/
public function action_add_enable_disable_buttons() {
$get_post_type = get_post_type();
$supported_post_types = Brizy_Editor::get()->supported_post_types();
if ( in_array( $get_post_type, $supported_post_types ) ) {
$p = get_post();
try {
$is_using_brizy = Brizy_Editor_Entity::isBrizyEnabled($p->ID);
} catch ( Exception $e ) {
$is_using_brizy = false;
}
echo Brizy_Admin_View::render( 'button', array(
'id' => get_the_ID(),
'post' => $p,
'is_using_brizy' => $is_using_brizy,
'url' => add_query_arg(
array( Brizy_Editor::prefix( '-edit' ) => '' ),
get_permalink( get_the_ID() )
)
) );
}
}
/**
* @param array $actions
* @param WP_Post $post
*
* @return array
**@internal
*
*/
public function filter_add_brizy_edit_row_actions( $actions, $post ) {
$is_allowed = Brizy_Editor_User::is_user_allowed();
if ( ! $is_allowed || ! in_array( get_post_type(), Brizy_Editor::get()->supported_post_types() ) ) {
return $actions;
}
try {
if ( Brizy_Editor_Entity::isBrizyEnabled( $post->ID ) ) {
$editUrl = Brizy_Editor_Entity::getEditUrl($post->ID);
$actions['brizy-edit'] = "<a href='{$editUrl}'>"
. sprintf( __( 'Edit with %s', 'brizy' ), __bt( 'brizy', 'Brizy' ) )
. "</a>";
}
} catch ( Exception $exception ) {
$t = 0;
}
return $actions;
}
/**
* @param string $body
*
* @return string
**@internal
*
*/
public function filter_add_body_class( $body ) {
if ( ! ( $id = get_the_ID() ) ) {
return $body;
}
return $body . ( Brizy_Editor_Entity::isBrizyEnabled( $id ) ? ' brizy-editor-enabled ' : '' );
}
/**
* @param $p
*
* @throws Brizy_Editor_Exceptions_UnsupportedPostType
* @throws Exception
*/
private function enable_brizy_for_post( $p ) {
$post = null;
// obtain the post
try {
$post = Brizy_Editor_Post::get( $p->ID );
} catch ( Exception $exception ) {
}
if ( ! $post ) {
Brizy_Admin_Flash::instance()->add_error( 'Failed to enable the editor for this post.' );
wp_redirect( $_SERVER['HTTP_REFERER'] );
}
try {
$update_post = false;
if ( $p->post_status == 'auto-draft' ) {
$p->post_status = 'draft';
$update_post = true;
}
if ( $p->post_title == __( 'Auto Draft' ) ) {
$p->post_title = __bt( 'brizy', 'Brizy' ) . ' #' . $p->ID;
$update_post = true;
}
if ( false === strpos( $p->post_content, 'brz-root__container' ) ) {
$p->post_content .= '<div class="brz-root__container"></div>';
$update_post = true;
}
if ( $update_post ) {
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 );
$post->set_pro_plugin_version( defined( 'BRIZY_PRO_VERSION' ) ? BRIZY_PRO_VERSION : null );
$post->saveStorage();
do_action( 'brizy_after_enabled_for_post', $p );
// redirect
wp_redirect( $post->edit_url() );
} catch ( Exception $exception ) {
Brizy_Admin_Flash::instance()->add_error( 'Failed to enable the editor for this post.' );
wp_redirect( $_SERVER['HTTP_REFERER'] );
}
exit;
}
public function handlePostsImport( $posts ) {
$incompatibleBrizyPosts = array();
foreach ( $posts as $i => $post ) {
if ( ! isset( $post['postmeta'] ) ) {
continue;
}
foreach ( $post['postmeta'] as $meta ) {
if ( $meta['key'] == 'brizy-post-plugin-version' && ! Brizy_Editor_Data_ProjectMergeStrategy::checkVersionCompatibility( $meta['value'] ) ) {
$incompatibleBrizyPosts[] = array(
'post_title' => $post['post_title'],
'version' => $meta['value']
);
unset( $posts[ $i ] );
}
}
}
if ( count( $incompatibleBrizyPosts ) ) {
foreach ( $incompatibleBrizyPosts as $brizy_post ) {
printf( __( 'Importing Brizy post &#8220;%s&#8221; will be skipped due to incompatible version: %s ', 'brizy' ),
esc_html( $brizy_post['post_title'] ), esc_html( $brizy_post['version'] ) );
echo '<br />';
}
}
return $posts;
}
public function handleNewProjectPostImport( $existing, $post ) {
if ( $post['post_type'] == Brizy_Editor_Project::BRIZY_PROJECT ) {
$currentProject = Brizy_Editor_Project::get();
$currentProjectGlobals = $currentProject->getDecodedData();
$currentProjectPostId = $currentProject->getWpPost()->ID;
$currentProjectStorage = Brizy_Editor_Storage_Project::instance( $currentProjectPostId );
$projectMeta = null;
foreach ( $post['postmeta'] as $meta ) {
if ( $meta['key'] == 'brizy-project' ) {
$projectMeta = maybe_unserialize( $meta['value'] );
break;
}
}
if ( ! $projectMeta ) {
// force import if the project data is not found in current project.
return 0;
}
$projectData = json_decode( base64_decode( $projectMeta['data'] ) );
$mergeStrategy = Brizy_Editor_Data_ProjectMergeStrategy::getMergerInstance( $projectMeta['pluginVersion'] );
$mergedData = $mergeStrategy->merge( $currentProjectGlobals, $projectData );
// create project data backup
$data = $currentProjectStorage->get_storage();
update_post_meta( $currentProjectPostId, 'brizy-project-import-backup-' . md5( time() ), $data );
//---------------------------------------------------------
$currentProject->setDataAsJson( json_encode( $mergedData ) );
$currentProject->saveStorage();
return $currentProjectPostId;
}
return $existing;
}
/**
* @param $postMeta
* @param $post_id
* @param $post
*
* @return null
*/
public function handleNewProjectMetaImport( $postMeta, $post_id, $post ) {
if ( $post['post_type'] == Brizy_Editor_Project::BRIZY_PROJECT ) {
return null;
}
return $postMeta;
}
/**
* Mark all post to be compiled next time
*/
public function global_data_updated() {
Brizy_Editor_Post::mark_all_for_compilation();
}
}

View File

@@ -0,0 +1,126 @@
<?php
class Brizy_Admin_Membership_Membership {
static $instance = null;
/**
* @return Brizy_Admin_Membership_Membership
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
public function __construct() {
add_action( 'admin_bar_init', [ $this, 'admin_bar_init' ] );
}
public function admin_bar_init() {
$pid = Brizy_Editor::get()->currentPostId();
if ( Brizy_Admin_Templates::instance()->getTemplateForCurrentPage() || ( $pid && Brizy_Editor_Entity::isBrizyEnabled( $pid ) ) ) {
add_action( 'admin_bar_menu', [ $this, 'admin_bar_menu' ], 10000 );
add_action( 'wp_head', [ $this, 'wp_head' ] );
}
}
/**
* @return array
*/
public static function roleList() {
$editable_roles = apply_filters( 'editable_roles', wp_roles()->roles );
$wpRoles = [ 'customer', 'shop_manager', 'subscriber', 'contributor', 'author', 'editor', 'administrator' ];
$roles = [];
foreach ( $wpRoles as $role ) {
if ( isset( $editable_roles[ $role ] ) ) {
$roles[] = [
'role' => $role,
'name' => translate_user_role( $editable_roles[ $role ]['name'] )
];
}
}
return apply_filters( 'brizy_avaible_roles', $roles );
}
public function admin_bar_menu( &$wp_admin_bar ) {
if ( is_admin() ) {
return;
}
$roles = self::roleList();
array_unshift( $roles,
[
'name' => esc_html__( 'Default', 'brizy' ),
'role' => 'default'
],
[
'name' => esc_html__( 'Not Logged', 'brizy' ),
'role' => 'not_logged'
],
[
'name' => esc_html__( 'Logged In', 'brizy' ),
'role' => 'logged'
]
);
$rolesList = wp_list_pluck( $roles, 'role' );
$selected = [];
$title = esc_html__( 'View Page By Roles', 'brizy' );
if ( empty( $_GET['role'] ) ) {
$user = wp_get_current_user();
$selected = array_intersect( $user->roles, $rolesList );
} else {
$index = array_search( $_GET['role'], $rolesList );
if ( false !== $index ) {
$selected[] = $roles[ $index ]['role'];
$title = sprintf( esc_html__( 'View Page As %s', 'brizy' ), $roles[ $index ]['name'] );
}
}
$wp_admin_bar->add_menu( [
'id' => $this->get_menu_id(),
'title' => $title
] );
foreach ( $roles as $role ) {
$args = [
'parent' => $this->get_menu_id(),
'id' => Brizy_Editor::prefix( '-membership-view-as-' . $role['role'] ),
'title' => $role['name'],
'href' => add_query_arg( 'role', $role['role'], home_url( $_SERVER['REQUEST_URI'] ) ),
];
if ( in_array( $role['role'], $selected ) ) {
$args['meta'] = [ 'class' => 'active' ];
}
$wp_admin_bar->add_node( $args );
}
}
public function wp_head() {
echo
'<style id="membership-css">' .
'#wp-admin-bar-' . $this->get_menu_id() . ' .active a {
color: #72aee6 !important;
}
</style>';
}
private function get_menu_id() {
return Brizy_Editor::prefix( '-membership-admin-bar-menu' );
}
}

View File

@@ -0,0 +1,181 @@
<?php
class Brizy_Admin_Migrations {
const BRIZY_MIGRATIONS = 'brizy_migrations';
/**
* @var Brizy_Admin_Migrations_GlobalStorage
*/
private $globalStorage;
/**
* @var Brizy_Admin_Migrations_MigrationInterface[]
*/
private $existinMigrations;
/**
* Brizy_Admin_Migrations constructor.
*/
public function __construct() {
$this->existinMigrations = array();
$this->globalStorage = new Brizy_Admin_Migrations_GlobalStorage();
}
/**
* @param $version
*/
public function runMigrations( $version ) {
$migrations = $this->getExistingMigrations();
$latestExecutedMigration = $this->getLatestRunMigration();
$latestExecutedVersion = $latestExecutedMigration->getVersion();
$latestMigrationVersion = end( $migrations );
$version_compare = version_compare( $version, $latestExecutedVersion );
if ( $version_compare === 1 && $latestMigrationVersion->getVersion() != $latestExecutedMigration->getVersion() ) {
$this->upgradeTo( $version );
}
}
/**
* @return Brizy_Admin_Migrations_MigrationInterface[]
*/
private function getExistingMigrations() {
if ( count( $this->existinMigrations ) ) {
return $this->existinMigrations;
}
$migrations = array(
new Brizy_Admin_Migrations_BlockPostTitleMigration,
new Brizy_Admin_Migrations_CleanInvalidBlocksMigration,
new Brizy_Admin_Migrations_CleanLogsMigration,
new Brizy_Admin_Migrations_FormSerializationMigration,
new Brizy_Admin_Migrations_GlobalBlocksToCustomPostMigration,
new Brizy_Admin_Migrations_GlobalVersionsMigration,
new Brizy_Admin_Migrations_GlobalsToDataMigration,
new Brizy_Admin_Migrations_NullMigration,
new Brizy_Admin_Migrations_ProjectToCustomPostMigration,
new Brizy_Admin_Migrations_RulesMigration,
new Brizy_Admin_Migrations_ShortcodesMobileOneMigration,
new Brizy_Admin_Migrations_FixGlobalsToDataMigration,
new Brizy_Admin_Migrations_ScreenshotMigration,
new Brizy_Admin_Migrations_UseEditorMigration,
new Brizy_Admin_Migrations_AttachmentUidMigration,
);
usort( $migrations, function ( $a, $b ) {
return version_compare( $a->getVersion(), $b->getVersion() );
} );
$migrations = array_filter( $migrations, function ( $migration ) {
return in_array( version_compare( $migration->getVersion(), BRIZY_VERSION ), array( - 1, 0 ) );
} );
return $this->existinMigrations = $migrations;
}
/**
* @return Brizy_Admin_Migrations_MigrationInterface|mixed
*/
private function getLatestRunMigration() {
$latest = $this->globalStorage->latestMigration();
if ( ! $latest instanceof Brizy_Admin_Migrations_MigrationInterface ) {
$latest = new Brizy_Admin_Migrations_NullMigration();
}
return $latest;
}
/**
* @param string $version
*/
private function upgradeTo( $version ) {
global $wpdb;
wp_raise_memory_limit( 'image' );
Brizy_Logger::instance()->debug( 'Starting migration process: [upgrading]' );
/**
* @var Brizy_Admin_Migrations_MigrationInterface
*/
$latestExecutedVersion = BRIZY_VERSION;
$latestExecutedMigration = $this->getLatestRunMigration();
if ( $latestExecutedMigration ) {
$latestExecutedVersion = $latestExecutedMigration->getVersion();
}
Brizy_Logger::instance()->debug( "Upgrading to version [{$version}] from version: [{$latestExecutedVersion}]: ", array( $version ) );
/**
* @var Brizy_Admin_Migrations_MigrationInterface[]
*/
$migrationsToRun = $this->getExistingMigrations();
if ( $latestExecutedMigration ) {
$migrationsToRun = array_filter( $migrationsToRun, function ( $migration ) use ( $latestExecutedMigration, $version ) {
$version_compare1 = version_compare( $latestExecutedMigration->getVersion(), $migration->getVersion() );
$version_compare2 = version_compare( $migration->getVersion(), $version );
return $version_compare1 == - 1 && ( $version_compare2 == - 1 || $version_compare2 == 0 );
} );
}
$migrations = array();
foreach ( $migrationsToRun as $m ) {
$migrations[ $m->getVersion() ][] = $m;
}
foreach ( $migrations as $v => $m ) {
//prioritise migrations
usort( $migrations[ $v ], function ( $a, $b ) {
$p1 = $a->getPriority();
$p2 = $b->getPriority();
if ( $p1 == $p2 ) {
return 0;
}
return ( $p1 < $p2 ) ? - 1 : 1;
} );
}
// run migrations
foreach ( $migrations as $versionMigrations ) {
try {
$wpdb->query( 'START TRANSACTION ' );
foreach ( $versionMigrations as $migration ) {
$migrationClass = get_class( $migration );
$migration->execute();
Brizy_Logger::instance()->debug( 'Run migration: ' . $migrationClass, array( $migrationClass ) );
$this->globalStorage->addMigration( $migration )->save();
Brizy_Editor_Project::cleanClassCache();
Brizy_Editor_Post::cleanClassCache();
Brizy_Editor_Block::cleanClassCache();
}
$wpdb->query( 'COMMIT' );
} catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' );
Brizy_Logger::instance()->critical( 'Migration process ERROR', [ $migrationClass, $e->getTraceAsString() ] );
break;
}
}
Brizy_Logger::instance()->debug( 'Migration process successful' );
}
}

View File

@@ -0,0 +1,84 @@
<?php
abstract class Brizy_Admin_Migrations_AbstractStorage {
const KEY = 'brizy-migrations';
/**
* @var Brizy_Admin_Migrations_MigrationInterface[]
*/
protected $data;
/**
* Brizy_Admin_Migations_AbstractStorage constructor.
*/
public function __construct() {
$this->data = array();
$this->loadData();
}
/**
* Save run migrations
*
* @return mixed
*/
abstract protected function storeData();
/**
* @return mixed
*/
abstract protected function loadData();
/**
* @return $this
*/
public function save() {
$this->storeData();
return $this;
}
/**
* @param Brizy_Admin_Migrations_MigrationInterface $migration
*
* @return $this
*/
public function addMigration( Brizy_Admin_Migrations_MigrationInterface $migration ) {
if ( ! $this->hasMigration( $migration ) ) {
$this->data[] = $migration;
}
return $this;
}
/**
* @@return Brizy_Admin_Migrations_MigrationInterface[]
*/
public function getMigrations() {
return $this->data;
}
/**
* @param Brizy_Admin_Migrations_MigrationInterface $amigratoin
*
* @return bool
*/
public function hasMigration( Brizy_Admin_Migrations_MigrationInterface $amigratoin ) {
$aMigrationClass = get_class( $amigratoin );
foreach ( $this->data as $migration ) {
if ( get_class( $migration ) == $aMigrationClass ) {
return true;
}
}
return false;
}
/**
* @return Brizy_Admin_Migrations_MigrationInterface|mixed
*/
public function latestMigration() {
return end( $this->data );
}
}

View File

@@ -0,0 +1,47 @@
<?php
class Brizy_Admin_Migrations_AttachmentUidMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '2.3.21';
}
/**
* @return mixed|void
*/
public function execute() {
try {
global $wpdb;
$invalidAttachments = $wpdb->get_results(
"SELECT
p.ID as post_id,
'brizy_attachment_uid' as meta_key,
wp.meta_value as meta_value
FROM {$wpdb->posts} p
JOIN {$wpdb->postmeta} wp on p.ID = wp.post_id and wp.meta_key='brizy_post_uid'
LEFT JOIN {$wpdb->postmeta} wp2 on p.ID = wp2.post_id and wp2.meta_key='brizy_attachment_uid'
WHERE post_type='attachment' and wp2.meta_value is NULL", ARRAY_A );
if ( is_array( $invalidAttachments ) ) {
foreach ( $invalidAttachments as $id => $insertData ) {
$wpdb->insert($wpdb->postmeta,$insertData);
}
}
} catch ( Exception $e ) {
return;
}
}
}

View File

@@ -0,0 +1,50 @@
<?php
class Brizy_Admin_Migrations_BlockPostTitleMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.82';
}
/**
* @return mixed|void
*/
public function execute() {
try {
global $wpdb;
$invalidBlocks = $wpdb->get_results(
"SELECT p.ID, p.post_title FROM {$wpdb->posts} p
WHERE p.post_type='brizy-global-block' OR p.post_type='brizy-saved-block'" );
if ( is_array( $invalidBlocks ) ) {
foreach ( $invalidBlocks as $id => $block ) {
if ( $block->post_title != '' ) {
continue;
}
$name = md5( time() . $id );
$wpdb->query(
$wpdb->prepare( "UPDATE {$wpdb->posts}
SET `post_title` = %s, `post_name` = %s
WHERE ID=%d ", array( $name, $name, $block->ID ) )
);
}
}
} catch ( Exception $e ) {
return;
}
}
}

View File

@@ -0,0 +1,27 @@
<?php
class Brizy_Admin_Migrations_CleanInvalidBlocksMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.74';
}
/**
* @return mixed|void
*/
public function execute() {
// disable this migration because of suspected data loss
return;
}
public function getPriority() {
return 0;
}
}

View File

@@ -0,0 +1,31 @@
<?php
class Brizy_Admin_Migrations_CleanLogsMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.93';
}
/**
* @return mixed|void
* @throws Exception
*/
public function execute() {
try {
Brizy_Logger::clean();
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_CleanLogsMigration', [] );
throw $e;
}
}
public function getPriority() {
return 10;
}
}

View File

@@ -0,0 +1,38 @@
<?php
class Brizy_Admin_Migrations_DeleteTemplateRulesMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '2.0.13';
}
/**
* Run this method when upgrading.
*
* @return mixed
*/
public function execute() {
try {
global $wpdb;
$wpdb->query( "DELETE m FROM `{$wpdb->prefix}postmeta` m
JOIN `{$wpdb->prefix}posts` p ON p.id=m.post_id and p.post_type NOT IN ('brizy-template','revision')
WHERE meta_key='brizy-rules'" );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_DeletetemplateRulesMigration', [] );
throw $e;
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
class Brizy_Admin_Migrations_FixGlobalsToDataMigration implements Brizy_Admin_Migrations_MigrationInterface {
use Brizy_Admin_Migrations_PostsTrait;
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.97';
}
/**
* @return mixed|void
* @throws Exception
*/
public function execute() {
try {
$projectPost = $this->getProjectPost();
if ( ! $projectPost ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_FixGlobalsToDataMigration. We did not found any projects.', [] );
return;
}
$storage = Brizy_Editor_Storage_Project::instance( $projectPost->ID );
if ( $data = $storage->get( 'data', false ) ) {
update_post_meta( $projectPost->ID, 'brizy-bk-' . get_class( $this ) . '-' . $this->getVersion(), $storage->get_storage() );
$beforeMergeGlobals = json_decode( base64_decode( $data ) );
$editorBuildPath = Brizy_Editor_UrlBuilder::editor_build_path();
$context = new \Brizy\DataToProjectContext( $beforeMergeGlobals, $editorBuildPath );
$projectMigration = new \Brizy\FixDataToProjectTransformer();
$mergedGlobals = $projectMigration->execute( $context );
$storage->set( 'data', base64_encode( json_encode( $mergedGlobals ) ) );
}
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_GlobalsToDataMigration', [ $e ] );
throw $e;
}
}
public function getPriority() {
return 0;
}
}

View File

@@ -0,0 +1,87 @@
<?php
class Brizy_Admin_Migrations_FormSerializationMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.65';
}
/**
* @return int|mixed|WP_Error
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function execute() {
if ( $this->wasExecuted() ) {
return;
}
global $wpdb;
$totalCount = $wpdb->get_var( "SELECT count(*) FROM {$wpdb->postmeta} WHERE meta_key='brizy-project'" );
$offset = 0;
$count = 20;
while ( $offset < $totalCount ) {
$result = @mysqli_query( $wpdb->dbh, "SELECT meta_id,post_id,meta_value FROM {$wpdb->postmeta} WHERE meta_key='brizy-project' LIMIT {$offset}, {$count}" );
if ( $result ) {
if ( $statement = mysqli_prepare( $wpdb->dbh, "UPDATE {$wpdb->postmeta} SET meta_value=? WHERE meta_id=? and post_id=? and meta_key='brizy-project'" ) ) {
while ( ( $row = @mysqli_fetch_array( $result, 1 ) ) ) {
// do stuff here for each result ...
$projectData = maybe_unserialize( $row['meta_value'] );
$meta_id = (int) $row['meta_id'];
$post_id = (int) $row['post_id'];
if ( isset( $projectData['forms'] ) ) {
foreach ( $projectData['forms'] as $id => $form ) {
if ( $form instanceof Brizy_Editor_Forms_Form ) {
$projectData['forms'][ $id ] = $form->convertToOptionValue();
} elseif ( ! is_null( $form ) ) {
$projectData['forms'][ $id ] = $form;
}
}
}
$projectData = maybe_serialize( $projectData );
mysqli_stmt_bind_param( $statement, 'sii', $projectData, $meta_id, $post_id );
mysqli_stmt_execute( $statement );
}
mysqli_stmt_close( $statement );
}
@mysqli_free_result( $result );
}
$offset += 20;
}
}
public function wasExecuted() {
$storage = new Brizy_Admin_Migrations_GlobalStorage();
$migrations = $storage->getMigrations();
foreach ( $migrations as $migration ) {
if ( get_class( $migration ) == get_class( $this ) ) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,95 @@
<?php
class Brizy_Admin_Migrations_GlobalBlocksToCustomPostMigration implements Brizy_Admin_Migrations_MigrationInterface {
use Brizy_Admin_Migrations_PostsTrait;
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.70';
}
/**
* @return int|mixed|WP_Error
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function execute() {
$projectPost = $this->getProjectPost();
if ( ! $projectPost ) {
return;
}
$projectStorage = Brizy_Editor_Storage_Project::instance( $projectPost->ID );
$postMigrationStorage = new Brizy_Admin_Migrations_PostStorage( $projectPost->ID );
$globals = json_decode( base64_decode( $projectStorage->get( 'globals', false ) ) );
if ( is_null($globals) || ! isset( $globals->project ) ) {
return;
}
if ( ! $globals || ( isset( $globals->project ) && empty( $globals->project ) ) ) {
$projectStorage->set( 'globals', base64_encode( json_encode( (object) array() ) ) );
$postMigrationStorage->addMigration( $this )->save();
return;
}
if ( isset( $globals->project->globalBlocks ) ) {
foreach ( get_object_vars( $globals->project->globalBlocks ) as $uid => $data ) {
$post = wp_insert_post( array(
'post_status' => 'publish',
'post_type' => Brizy_Admin_Blocks_Main::CP_GLOBAL
) );
if ( $post ) {
$brizyPost = Brizy_Editor_Block::get( $post, $uid );
$brizyPost->set_editor_data( json_encode( $data ) );
$brizyPost->set_uses_editor( true );
$brizyPost->set_needs_compile( true );
$brizyPost->saveStorage();
}
}
}
if ( isset( $globals->project->savedBlocks ) ) {
foreach ( $globals->project->savedBlocks as $data ) {
$post = wp_insert_post( array(
'post_status' => 'publish',
'post_type' => Brizy_Admin_Blocks_Main::CP_SAVED
) );
if ( $post ) {
$brizyPost = Brizy_Editor_Block::get( $post );
$brizyPost->set_editor_data( json_encode( $data ) );
$brizyPost->set_uses_editor( true );
$brizyPost->set_needs_compile( true );
$brizyPost->saveStorage();
}
}
}
update_post_meta( $projectPost->ID, 'brizy-bk-' . get_class( $this ) . '-' . $this->getVersion(), $globals );
unset( $globals->project->globalBlocks );
unset( $globals->project->savedBlocks );
$projectStorage->set( 'globals', base64_encode( json_encode( $globals->project ) ) );
$postMigrationStorage->addMigration( $this )->save();
}
}

View File

@@ -0,0 +1,28 @@
<?php
class Brizy_Admin_Migrations_GlobalStorage extends Brizy_Admin_Migrations_AbstractStorage {
/**
* Save run migrations
*
* @return mixed
*/
protected function storeData() {
update_option( Brizy_Admin_Migrations_AbstractStorage::KEY, $this->data );
}
/**
* @return mixed|void
* @throws Exception
*/
protected function loadData() {
$this->data = get_option( Brizy_Admin_Migrations_AbstractStorage::KEY, array() );
foreach ( $this->data as $i => $migration ) {
if ( $migration instanceof __PHP_Incomplete_Class ) {
throw new Brizy_Admin_Migrations_UpgradeRequiredException( 'Please update the plugin to the latest version' );
}
}
}
}

View File

@@ -0,0 +1,53 @@
<?php
class Brizy_Admin_Migrations_GlobalVersionsMigration implements Brizy_Admin_Migrations_MigrationInterface {
use Brizy_Admin_Migrations_PostsTrait;
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.45';
}
/**
* @return int|mixed|WP_Error
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function execute() {
try {
$projectPost = $this->getProjectPost();
if ( ! $projectPost ) {
return;
}
$projectStorage = Brizy_Editor_Storage_Project::instance( $projectPost->ID );
$pluginVersion = $projectStorage->get( 'pluginVersion', false );
if ( ! $pluginVersion ) {
// this is going to fix the plugin and editor version
$projectStorage->set( 'pluginVersion', BRIZY_VERSION );
$projectStorage->set( 'editorVersion', BRIZY_EDITOR_VERSION );
$projectStorage->delete( 'version' );
}
} catch ( Exception $e ) {
return;
}
}
}

View File

@@ -0,0 +1,58 @@
<?php
use \Brizy\DataToProjectContext;
use \Brizy\DataToProjectTransformer;
class Brizy_Admin_Migrations_GlobalsToDataMigration implements Brizy_Admin_Migrations_MigrationInterface {
use Brizy_Admin_Migrations_PostsTrait;
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.76';
}
/**
* @return mixed|void
* @throws Exception
*/
public function execute() {
try {
$projectPost = $this->getProjectPost();
if ( ! $projectPost ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_GlobalsToDataMigration. We did not found any projects.', [] );
return;
}
$storage = Brizy_Editor_Storage_Project::instance( $projectPost->ID );
if ( $globals = $storage->get( 'globals', false ) ) {
update_post_meta( $projectPost->ID, 'brizy-bk-' . get_class( $this ) . '-' . $this->getVersion(), $storage->get_storage() );
$beforeMergeGlobals = json_decode( base64_decode( $globals ) );
$editorBuildPath = Brizy_Editor_UrlBuilder::editor_build_path();
$context = new DataToProjectContext( $beforeMergeGlobals, $editorBuildPath );
$projectMigration = new DataToProjectTransformer();
$mergedGlobals = $projectMigration->execute( $context );
$storage->set( 'data', base64_encode( json_encode( $mergedGlobals ) ) );
$storage->delete( 'globals' );
}
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_GlobalsToDataMigration', [ $e ] );
throw $e;
}
}
public function getPriority() {
return 10;
}
}

View File

@@ -0,0 +1,25 @@
<?php
interface Brizy_Admin_Migrations_MigrationInterface {
/**
* Return the version
*
* @return mixed
*/
public function getVersion();
/**
* Run this method when upgrading.
*
* @return mixed
*/
public function execute();
/**
* @return mixed
*/
public function getPriority();
}

View File

@@ -0,0 +1,30 @@
<?php
class Brizy_Admin_Migrations_NullMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '0.0.1';
}
/**
* Run this method when upgrading.
*
* @return mixed
*/
public function execute() {
// this is a null migration
}
}

View File

@@ -0,0 +1,38 @@
<?php
class Brizy_Admin_Migrations_PostStorage extends Brizy_Admin_Migrations_AbstractStorage {
/**
* @var int
*/
protected $postId;
/**
* Brizy_Admin_Migations_PostStorage constructor.
*
* @param int $postId
*/
public function __construct( $postId ) {
$this->postId = (int) $postId;
parent::__construct();
}
/**
* Save run migrations
*
* @return mixed
*/
protected function storeData() {
update_post_meta( $this->postId, Brizy_Admin_Migrations_AbstractStorage::KEY, $this->data );
}
/**
* @return mixed
*/
protected function loadData() {
$get_post_meta = get_post_meta( $this->postId, Brizy_Admin_Migrations_AbstractStorage::KEY, true );
$this->data = is_array( $get_post_meta ) ? $get_post_meta : array();
}
}

View File

@@ -0,0 +1,159 @@
<?php
trait Brizy_Admin_Migrations_PostsTrait {
private static $project;
/**
* @return |null
*/
public function getProjectPost() {
global $wpdb;
if ( self::$project ) {
return self::$project;
}
$row = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$wpdb->posts} p
WHERE p.post_type = %s and p.post_status='publish'
ORDER BY ID DESC LIMIT 1 ", Brizy_Editor_Project::BRIZY_PROJECT ),
OBJECT
);
$projectPost = null;
if ( isset( $row[0] ) ) {
return self::$project = $row[0];
}
return null;
}
/**
* Get posts and meta
*/
public function get_posts_and_meta() {
global $wpdb;
// query all posts (all post_type, all post_status) that have meta_key = 'brizy' and is not 'revision'
return $wpdb->get_results( "
SELECT p.ID, pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = 'brizy'
AND p.post_type != 'revision'
AND p.post_type != 'attachment'
" );
}
/**
* Get Globals posts
*/
public function get_globals_posts() {
global $wpdb;
// query all global posts
return $wpdb->get_results( "
SELECT p.ID, pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = 'brizy-project'
AND p.post_type = 'brizy-project'
" );
}
/**
* Parse array of shortcodes recursive
*/
public function array_walk_recursive_and_delete( array &$array, callable $callback, $userdata = null ) {
foreach ( $array as $key => &$value ) {
if ( is_array( $value ) ) {
$value = $this->array_walk_recursive_and_delete( $value, $callback, $userdata );
// if is shortcode parse recursive
if ( isset( $value['type'], $value['value'] ) ) {
$this->parse_shortcodes( $value );
}
}
}
return $array;
}
/**
* Migrate post
*/
public function migrate_post( $json_value ) {
$old_arr = json_decode( $json_value, true );
if ( is_null( $old_arr ) ) {
return $json_value;
}
$new_arr = $this->array_walk_recursive_and_delete( $old_arr, function ( $value, $key ) {
if ( is_array( $value ) ) {
return empty( $value );
}
if ( isset( $value['type'], $value['value'] ) ) {
// if is shortcode return true
return true;
}
} );
return json_encode( $new_arr );
}
/**
* Parse shortcodes
*/
public function parse_shortcodes( array &$array ) {
// rewrite this function in your class
return $array;
}
/**
* Unset mobile keys
*/
public function unset_prefixed_keys( array &$array, $atts = array() ) {
// merge with default $atts
$atts = array_merge(
array(
"shortcode" => "",
"delete_keys" => array(),
"dependent_keys" => false,
"key_prefix" => "mobile"
),
$atts
);
if ( empty( $atts['shortcode'] ) && empty( $atts['delete_keys'] ) ) {
return $array;
}
if ( $atts['shortcode'] == $array['type'] ) {
$keys_to_remove = array();
foreach ( $atts['delete_keys'] as $key_to_delete ) {
// replace "prefix" with empty string then make first letter lowercase
$key = lcfirst( str_replace( $atts['key_prefix'], "", $key_to_delete ) );
if ( isset( $array['value'][ $key ], $array['value'][ $key_to_delete ] ) && $array['value'][ $key ] === $array['value'][ $key_to_delete ] ) {
$keys_to_remove[] = $key_to_delete;
}
}
// !Atention if the number of keys to delete are not the same to not delete
if ( $atts['dependent_keys'] && count( $keys_to_remove ) != count( $atts['delete_keys'] ) ) {
$keys_to_remove = array();
}
// remove keys
if ( ! empty( $keys_to_remove ) ) {
foreach ( $keys_to_remove as $key_to_remove ) {
unset( $array['value'][ $key_to_remove ] );
}
}
}
return $array;
}
}

View File

@@ -0,0 +1,84 @@
<?php
class Brizy_Admin_Migrations_ProjectToCustomPostMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.30';
}
/**
* @return int|mixed|WP_Error
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function execute() {
if ( $this->isGlobalProjectCreated() ) {
return;
}
$storage = Brizy_Editor_Storage_Common::instance();
$projectData = $storage->get( Brizy_Editor_Project::BRIZY_PROJECT, false );
if ( is_array( $projectData ) ) {
$projectData = unserialize( $projectData['api_project'] );
} elseif ( $projectData instanceof Brizy_Editor_Project ) {
$projectData = $projectData->getApiProject()->get_data();
} else {
return;
}
if ( base64_encode( base64_decode( $projectData['globals'] ) ) !== $projectData['globals'] ) {
$projectData['globals'] = base64_encode( $projectData['globals'] );
}
$post_id = wp_insert_post( array(
'post_type' => Brizy_Editor_Project::BRIZY_PROJECT,
'post_title' => 'Brizy Project',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed'
) );
$newProjectData = array(
'id' => $projectData['id'],
'title' => $projectData['title'],
'globals' => $projectData['globals'],
'name' => $projectData['name'],
'user' => $projectData['user'],
'template' => $projectData['template'],
'created' => $projectData['created'],
'updated' => $projectData['updated'],
'languages' => $projectData['signature'],
'version' => $projectData['version'],
'signature' => $projectData['signature'],
);
$storage = Brizy_Editor_Storage_Project::instance( $post_id );
$storage->loadStorage( $newProjectData );
return $post_id;
}
public function isGlobalProjectCreated() {
global $wpdb;
$projectId = $wpdb->get_var( $wpdb->prepare( " SELECT ID FROM {$wpdb->posts} WHERE post_type=%s", Brizy_Editor_Project::BRIZY_PROJECT ) );
return ! is_null( $projectId ) && $projectId > 0;
}
}

View File

@@ -0,0 +1,47 @@
<?php
class Brizy_Admin_Migrations_RulesMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.54';
}
/**
* @return int|mixed|WP_Error
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function execute() {
$templateIds = $this->getTemplateIds();
foreach ( $templateIds as $templateId ) {
$data = get_post_meta( (int) $templateId->post_id, 'brizy-template-rules', true );
add_post_meta( (int) $templateId->post_id, 'brizy-bk-' . get_class( $this ) . '-' . $this->getVersion(), $data );
add_post_meta( (int) $templateId->post_id, 'brizy-rules', $data );
delete_post_meta( (int) $templateId->post_id, 'brizy-template-rules' );
}
}
/**
* Get posts and meta
*/
public function getTemplateIds() {
global $wpdb;
// query all posts (all post_type, all post_status) that have meta_key = 'brizy' and is not 'revision'
return $wpdb->get_results( "SELECT pm.post_id FROM {$wpdb->postmeta} pm WHERE pm.meta_key = 'brizy-template-rules'" );
}
}

View File

@@ -0,0 +1,82 @@
<?php
class Brizy_Admin_Migrations_ScreenshotMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.123';
}
/**
* Run this method when upgrading.
*
* @return mixed
*/
public function execute() {
// this is a null migration
global $wpdb;
if ( ! class_exists( 'Brizy\BlockScreenshotContext' ) || ! class_exists( 'Brizy\BlockScreenshotTransformer' ) ) {
throw new Exception();
}
$entities = $wpdb->get_results(
"SELECT
p.id as ID
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->posts} pp ON pp.id=p.post_parent
WHERE IF(pp.post_type IS NOT NULL,pp.post_type,p.post_type) in ('brizy-global-block','brizy-saved-block')
" );
foreach ( $entities as $row ) {
if ( metadata_exists( 'post', $row->ID, Brizy_Editor_Block::BRIZY_META ) ) {
continue;
}
try {
$this->migrateEntity( $row->ID );
} catch ( Brizy_Editor_Exceptions_NotFound $e ) {
continue;
}
}
}
/**
* @param $postId
*/
private function migrateEntity( $postId ) {
$storage = Brizy_Editor_Storage_Post::instance( $postId );
$storage_post = $storage->get( Brizy_Editor_Post::BRIZY_POST, true );
if ( ! isset( $storage_post['editor_data'] ) ) {
throw new Exception( 'editor_data not found on block: ' . $postId );
}
if ( ( $dataJson = base64_decode( $storage_post['editor_data'], true ) ) === false ) {
$dataJson = $storage_post['editor_data'];
}
$dataObject = json_decode( $dataJson );
$transformerContext = new \Brizy\BlockScreenshotContext( $dataObject );
$transformer = new \Brizy\BlockScreenshotTransformer();
$transformer->execute( $transformerContext );
$metaJson = json_encode( $transformerContext->getMeta() );
update_metadata( 'post', $postId, Brizy_Editor_Block::BRIZY_META, $metaJson );
}
}

View File

@@ -0,0 +1,448 @@
<?php
class Brizy_Admin_Migrations_ShortcodesMobileOneMigration implements Brizy_Admin_Migrations_MigrationInterface {
use Brizy_Admin_Migrations_PostsTrait;
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.39';
}
/**
* Execute the migration
*/
public function execute() {
$this->posts_migration();
$this->globals_migration();
}
/**
* Posts migration
*/
public function posts_migration() {
$result = $this->get_posts_and_meta();
$class = __CLASS__;
// parse each post
foreach ( $result as $item ) {
$postMigrationStorage = new Brizy_Admin_Migrations_PostStorage( $item->ID );
if ( $postMigrationStorage->hasMigration($this) ) {
continue;
}
$json_value = null;
$instance = Brizy_Editor_Storage_Post::instance($item->ID);
$storage = $instance->get_storage();
$old_meta = $instance->get(Brizy_Editor_Post::BRIZY_POST, false);
if ( is_array($old_meta) ) {
$json_value = base64_decode($old_meta['editor_data']);
}
elseif( is_object($old_meta) ) {
$json_value = $old_meta->get_editor_data();
}
if( !is_null($json_value) ) {
// make a backup to previous version
update_post_meta($item->ID, 'brizy-bk-'.$class.'-'.$this->getVersion(), $storage);
// migrate post
$new_json = $this->migrate_post($json_value);
// set the changed value in DB
if ( is_array($old_meta) ) {
$old_meta['editor_data'] = base64_encode($new_json);
}
elseif( is_object($old_meta) ) {
$old_meta->set_editor_data($new_json);
}
$instance->set(Brizy_Editor_Post::BRIZY_POST, $old_meta);
// set that migration was successful executed
$postMigrationStorage->addMigration($this)->save();
}
}
}
/**
* Globals migration
*/
public function globals_migration() {
$class = __CLASS__;
$result = $this->get_globals_posts();
foreach ($result as $item) {
$postMigrationStorage = new Brizy_Admin_Migrations_PostStorage( $item->ID );
if ( $postMigrationStorage->hasMigration($this) ) {
continue;
}
$instance = Brizy_Editor_Storage_Project::instance( $item->ID );
$storage = $instance->get_storage();
if ( ! isset( $storage['globals'] ) ) {
continue;
}
$json_value = base64_decode($storage['globals']);
if( !is_null($json_value) ) {
// make a backup to previous version
update_post_meta($item->ID, 'brizy-bk-' . $class . '-' . $this->getVersion(), $storage);
// migrate post
$new_json = $this->migrate_post($json_value);
// set the changed value in DB
$storage['globals'] = base64_encode($new_json);
$instance->loadStorage($storage);
// set that migration was successful executed
$postMigrationStorage->addMigration($this)->save();
}
}
}
/**
* Parse shortcodes
*/
public function parse_shortcodes(array &$array) {
// Line
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Line",
"delete_keys" => array(
"mobileWidth",
"mobileBorderWidth"
)
) );
// Spacer
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Spacer",
"delete_keys" => array(
"mobileHeight"
)
) );
// Video
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Video",
"delete_keys" => array(
"mobileSize",
"mobileCoverImageWidth",
"mobileCoverImageHeight"
)
) );
// EmbedCode
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "EmbedCode",
"delete_keys" => array(
"mobileWidth",
"mobileHeight"
)
) );
// Map
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Map",
"delete_keys" => array(
"mobileSize",
"mobileHeight"
)
) );
// SoundCloud
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "SoundCloud",
"delete_keys" => array(
"mobileWidth",
"mobileHeight"
)
) );
// Countdown
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Countdown",
"delete_keys" => array(
"mobileWidth"
)
) );
// ProgressBar
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "ProgressBar",
"delete_keys" => array(
"mobileWidth",
"mobileBorderRadius"
)
) );
// Wrapper
$array = $this->mobile_migation_wrapper_align( $array, "Wrapper" );
// Cloneable
$array = $this->mobile_migation_wrapper_align( $array, "Cloneable" );
// WOOCategories
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WOOCategories",
"delete_keys" => array(
"mobileWidth"
)
) );
// WOOPages
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WOOPages",
"delete_keys" => array(
"mobileWidth"
)
) );
// WOOProducts
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WOOProducts",
"delete_keys" => array(
"mobileWidth"
)
) );
// WPSidebar
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WPSidebar",
"delete_keys" => array(
"mobileWidth"
)
) );
// WPCustomShortcode
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WPCustomShortcode",
"delete_keys" => array(
"mobileWidth"
)
) );
// WOOProductPage
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WOOProductPage",
"delete_keys" => array(
"mobileWidth"
)
) );
// WPNavigation
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "WPNavigation",
"delete_keys" => array(
"mobileWidth",
"mobileItemPadding"
)
) );
// Button
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Button",
"delete_keys" => array(
"mobileBorderRadius"
)
) );
// Tabs
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Tabs",
"delete_keys" => array(
"mobileHorizontalAlign"
)
) );
// Image
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Image",
"delete_keys" => array(
"mobileResize",
"mobileZoom",
"mobileWidth",
"mobileHeight"
)
) );
// Delete image position if all are equal
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Image",
"delete_keys" => array(
"mobilePositionX",
"mobilePositionY"
),
"dependent_keys" => true
) );
// Form
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Form",
"delete_keys" => array(
"mobileHorizontalAlign"
)
) );
// Form fields options
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "FormFields",
"delete_keys" => array(
"mobilePadding",
"mobilePaddingRight",
"mobilePaddingBottom",
"mobilePaddingLeft",
),
"dependent_keys" => true
) );
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "FormFields",
"delete_keys" => array(
"mobileBorderRadius",
"mobilePaddingTop" // top is used as zero from the default json
)
) );
// Form single field options
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "FormField",
"delete_keys" => array(
"mobileWidth",
"mobileHeight"
)
) );
// Icon
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Icon",
"delete_keys" => array(
"mobilePadding",
"mobileBorderRadius"
)
) );
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Icon",
"delete_keys" => array(
"mobileSize",
"mobileCustomSize"
),
"dependent_keys" => true
) );
// Row
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Row",
"delete_keys" => array(
"mobileMedia",
"mobileBgImageWidth",
"mobileBgImageHeight",
"mobileBgImageSrc",
"mobileBgColorHex",
"mobileBgColorOpacity",
"mobileBgColorPalette",
"mobileBgMapZoom"
)
) );
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Row",
"delete_keys" => array(
"mobileBgPositionX",
"mobileBgPositionY"
),
"dependent_keys" => true
) );
// Column
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Column",
"delete_keys" => array(
"mobileBgImageWidth",
"mobileBgImageHeight",
"mobileBgImageSrc",
"mobileBgColorHex",
"mobileBgColorOpacity",
"mobileBgColorPalette"
)
) );
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "Column",
"delete_keys" => array(
"mobileBgPositionX",
"mobileBgPositionY"
),
"dependent_keys" => true
) );
// Section
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "SectionItem",
"delete_keys" => array(
"mobileMedia",
"mobileBgImageWidth",
"mobileBgImageHeight",
"mobileBgImageSrc",
"mobileBgColorHex",
"mobileBgColorOpacity",
"mobileBgColorPalette",
"mobileBgMapZoom"
)
) );
$array = $this->unset_prefixed_keys( $array, array(
"shortcode" => "SectionItem",
"delete_keys" => array(
"mobileBgPositionX",
"mobileBgPositionY"
),
"dependent_keys" => true
) );
return $array;
}
/**
* Special Migration for Wrapper and Cloneable "align"
*/
public function mobile_migation_wrapper_align(array &$array, $shortcode = "") {
if ( empty($shortcode) ) {
return $array;
}
if ( $shortcode == $array['type'] ) {
if ( isset( $array['value']['horizontalAlign'], $array['value']['mobileHorizontalAlign'] ) && $array['value']['horizontalAlign'] === $array['value']['mobileHorizontalAlign'] )
{
unset( $array['value']['mobileHorizontalAlign'] );
}
else
{
// !Attention this need only 1-time execution in JSON (to not apply to the same JSON 2 times)
if ( isset( $array['value']['horizontalAlign'] )
&& ( $array['value']['horizontalAlign'] !== "center" )
&& !isset( $array['value']['mobileHorizontalAlign'] ) )
{
$array['value']['mobileHorizontalAlign'] = "center";
}
}
}
return $array;
}
}

View File

@@ -0,0 +1,35 @@
<?php
class Brizy_Admin_Migrations_SiteSettingsMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '1.0.118';
}
/**
* @return int|mixed|WP_Error
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function execute() {
delete_option('brizy-social-title');
delete_option('brizy-social-description');
delete_option('brizy-custom-css');
delete_option('brizy-header-injection');
delete_option('brizy-footer-injection');
delete_option('brizy-social-thumbnail');
delete_option('brizy-settings-favicon');
}
}

View File

@@ -0,0 +1,6 @@
<?php
class Brizy_Admin_Migrations_UpgradeRequiredException extends Exception {
}

View File

@@ -0,0 +1,44 @@
<?php
class Brizy_Admin_Migrations_UseEditorMigration implements Brizy_Admin_Migrations_MigrationInterface {
/**
* @return int|mixed
*/
public function getPriority() {
return 0;
}
/**
* Return the version
*
* @return mixed
*/
public function getVersion() {
return '2.2.6';
}
/**
* Run this method when upgrading.
*
* @return mixed
*/
public function execute() {
try {
global $wpdb;
$brizyEnabled = Brizy_Editor_Constants::BRIZY_ENABLED;
$var = (int)$wpdb->get_var("SELECT count(meta_id) FROM {$wpdb->postmeta} WHERE meta_key='brizy_enabled'");
if($var > 0) return;
$wpdb->query( "INSERT INTO {$wpdb->postmeta} (post_id,meta_key,meta_value)
SELECT post_id,'brizy_enabled',POSITION('\"brizy-use-brizy\";b:1;' IN meta_value)>0 FROM {$wpdb->postmeta} where meta_key='brizy'" );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( 'Filed migration Brizy_Admin_Migrations_DeletetemplateRulesMigration', [] );
throw $e;
}
}
}

View File

@@ -0,0 +1,190 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Admin_NetworkSettings {
private $selected_post_types;
private $role_list;
private $capability_options;
/**
* @var string
*/
private $screenName;
public static function menu_slug() {
return Brizy_Editor::prefix( '-network-settings' );
}
/**
* @return Brizy_Admin_NetworkSettings
*/
public static function _init() {
static $instance;
return $instance ? $instance : $instance = new self();
}
/**
* Brizy_Admin_NetworkSettings constructor.
*/
private function __construct() {
add_action( 'network_admin_menu', array( $this, 'actionRegisterSettingsPage' ) );
add_action( 'brizy_network_settings_render_tabs', array( $this, 'render_tabs' ) );
add_action( 'brizy_network_settings_render_content', array( $this, 'render_tab_content' ) );
}
/**
* @internal
*/
function actionRegisterSettingsPage() {
$this->screenName = add_menu_page( Brizy_Editor::get()->get_name(),
Brizy_Editor::get()->get_name(),
'read',
self::menu_slug(),
array( $this, 'render' ),
__bt( 'brizy-logo', plugins_url( 'static/img/brizy-logo.svg', __FILE__ ) ),
//plugins_url( '/static/img/brizy-logo.svg', __FILE__ ),
'58'
);
}
private function get_selected_tab() {
return ( ! empty( $_REQUEST['tab'] ) ) ? esc_attr( $_REQUEST['tab'] ) : 'license';
}
private function get_tabs() {
$selected_tab = $this->get_selected_tab();
$tabs = [];
return apply_filters( 'brizy_network_settings_tabs', $tabs, $selected_tab );
}
/**
* Return the list of capabilities including the label
*
* @return mixed|void
*/
public function get_capability_options() {
return apply_filters( 'brizy_settings_capability_options', array(
array( 'capability' => '', 'label' => __( 'No Access' ) ),
array(
'capability' => Brizy_Admin_Capabilities::CAP_EDIT_WHOLE_PAGE,
'label' => __( 'Full Access', 'brizy' )
)
) );
}
/**
* @internal
*/
public function render() {
try {
echo Brizy_Admin_View::render(
'settings/network-view',
array()
);
} catch ( Exception $e ) {
}
}
public function render_tabs() {
$tabs = $this->get_tabs();
foreach ( $tabs as $tab ) {
$is_active_class = $tab['is_selected'] ? 'nav-tab-active' : '';
?>
<a href="<?php echo $tab['href'] ?>"
class="nav-tab <?php echo $is_active_class ?>"><?php echo __( $tab['label'] ) ?></a>
<?php
}
}
public function render_tab_content() {
$tab = $this->get_selected_tab();
echo apply_filters( 'brizy_network_settings_render_tab', '', $tab );
}
}

View File

@@ -0,0 +1,100 @@
<?php defined( 'ABSPATH' ) or die();
class Brizy_Admin_PanelPostContent {
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
protected function __construct() {
add_action( 'rest_request_before_callbacks', [ $this, 'rest_request_before_callbacks' ] );
add_filter( 'content_edit_pre', [ $this, 'content_edit_pre' ], 10, 2 );
}
public function rest_request_before_callbacks( $response ){
$postsTypes = Brizy_Editor::get()->supported_post_types();
foreach( $postsTypes as $postType ) {
add_action( "rest_prepare_{$postType}", [ $this, 'reset_prepare_post' ] );
}
return $response;
}
public function reset_prepare_post( $response ) {
global $post;
if ( ! isset( $response->data['content']['raw'] ) ) {
return $response;
}
$response->data['content']['raw'] = $this->get_compiled_html( $post->ID, $response->data['content']['raw'] );
return $response;
}
/**
* @param $content
*
* @param $postId
*
* @return null|string|string[]
* @throws Exception
*/
public function content_edit_pre( $content, $postId ) {
$post = get_post( $postId );
// do not fix anything for popups/blocksand templates
if ( in_array( $post->post_type, [
Brizy_Admin_Templates::CP_TEMPLATE,
Brizy_Admin_Blocks_Main::CP_GLOBAL,
Brizy_Admin_Blocks_Main::CP_SAVED,
Brizy_Admin_Popups_Main::CP_POPUP
] ) ) {
return $content;
}
return $this->get_compiled_html( $postId, $content );
}
private function get_compiled_html( $postId, $content ) {
if ( ! Brizy_Editor_Entity::isBrizyEnabled( $postId ) ) {
return $content;
}
try {
$editor = Brizy_Editor_Post::get( $postId );
if ( ! $editor->isCompiledWithCurrentVersion() || $editor->get_needs_compile() ) {
$editor->compile_page();
$editor->saveStorage();
$editor->savePost();
global $wpdb;
$query = $wpdb->get_col( "SELECT post_content FROM $wpdb->posts WHERE ID = $postId" );
if ( ! isset( $query[0] ) ) {
return $content;
}
$content = $query[0];
}
} catch ( Exception $e ) {
return $content;
}
return $content;
}
}

View File

@@ -0,0 +1,304 @@
<?php
class Brizy_Admin_Popups_Main
{
const CP_POPUP = 'brizy-popup';
/**
* @return Brizy_Admin_Popups_Main
*/
public static function _init()
{
static $instance;
if ( ! $instance) {
$instance = new self();
$instance->initialize();
}
return $instance;
}
public function initialize()
{
add_action('brizy_after_enabled_for_post', [$this, 'afterBrizyEnabledForPopup']);
if (Brizy_Editor::is_user_allowed()) {
add_action('admin_menu', [$this, 'removePageAttributes']);
}
if ( ! isset($_GET[Brizy_Editor::prefix('-edit')]) && ! isset($_GET[Brizy_Editor::prefix('-edit-iframe')])) {
add_action('wp_enqueue_scripts', [$this, 'enqueuePopupScripts']);
add_action('wp_head', [$this, 'wpHeadAppentPopupHtml']);
add_action('wp_footer', [$this, 'wpFooterAppendPopupHtml']);
add_filter('body_class', [$this, 'bodyClassFrontend'], 11);
}
}
public function enqueuePopupScripts()
{
foreach ($this->getMatchingBrizyPopups() as $popup) {
$needs_compile = ! $popup->isCompiledWithCurrentVersion() || $popup->get_needs_compile();
if ($needs_compile) {
$popup->compile_page();
$popup->saveStorage();
$popup->savePost();
}
Brizy_Public_AssetEnqueueManager::_init()->enqueuePost($popup);
}
}
public function wpHeadAppentPopupHtml()
{
$headHtml = $this->getPopupsHtml(null, null, 'head');
if (empty($headHtml)) {
return;
}
$content = apply_filters(
'brizy_content',
$headHtml,
Brizy_Editor_Project::get(),
null,
'head'
);
echo do_shortcode($content);
}
public function wpFooterAppendPopupHtml()
{
$bodyHtml = $this->getPopupsHtml(null, null, 'body');
if (empty($bodyHtml)) {
return;
}
$content = apply_filters(
'brizy_content',
$bodyHtml,
Brizy_Editor_Project::get(),
null,
'footer'
);
echo do_shortcode($content);
}
public function bodyClassFrontend($classes)
{
if ( ! $this->getMatchingBrizyPopups() || false !== array_search('brz', $classes)) {
return $classes;
}
$classes[] = 'brz';
return $classes;
}
public function removePageAttributes()
{
remove_meta_box('pageparentdiv', self::CP_POPUP, 'side');
}
static public function registerCustomPosts()
{
$labels = array(
'name' => _x('Popups', 'post type general name', 'brizy'),
'singular_name' => _x('Popup', 'post type singular name', 'brizy'),
'menu_name' => _x('Popups', 'admin menu', 'brizy'),
'name_admin_bar' => _x('Popup', 'add new on admin bar', 'brizy'),
'add_new' => __('Add New', 'brizy'),
'add_new_item' => __('Add New Popup', 'brizy'),
'new_item' => __('New Popup', 'brizy'),
'edit_item' => __('Edit Popup', 'brizy'),
'view_item' => __('View Popup', 'brizy'),
'all_items' => __('Popups', 'brizy'),
'search_items' => __('Search Popups', 'brizy'),
'parent_item_colon' => __('Parent Popups:', 'brizy'),
'not_found' => __('No Popups found.', 'brizy'),
'not_found_in_trash' => __('No Popups found in Trash.', 'brizy'),
'attributes' => __('Popup attributes:', 'brizy'),
);
register_post_type(
self::CP_POPUP,
array(
'labels' => $labels,
'public' => false,
'has_archive' => false,
'description' => __('Popups', 'brizy'),
'publicly_queryable' => Brizy_Editor_User::is_user_allowed(),
'show_ui' => defined('BRIZY_PRO_VERSION'),
'show_in_menu' => Brizy_Admin_Settings::menu_slug(),
'query_var' => false,
'rewrite' => array('slug' => 'brizy-popup'),
'capability_type' => 'page',
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'can_export' => true,
'supports' => array('title', 'post_content', 'revisions'),
)
);
remove_post_type_support(self::CP_POPUP, 'page-attributes');
add_filter(
'brizy_supported_post_types',
function ($posts) {
$posts[] = self::CP_POPUP;
return $posts;
}
);
}
/**
* @param $post
*
* @throws Exception
*/
public function afterBrizyEnabledForPopup($post)
{
if ($post->post_type === Brizy_Admin_Popups_Main::CP_POPUP) {
$manager = new Brizy_Admin_Rules_Manager();
if (count($manager->getRules($post->ID)) == 0) {
$manager->saveRules(
$post->ID,
array(
new Brizy_Admin_Rule(null, Brizy_Admin_Rule::TYPE_INCLUDE, '', '', array()),
)
);
}
}
}
/**
* @param $content
* @param $project
* @param $wpPost
* @param string $context
*
* @return string|string[]|null
* @throws Brizy_Editor_Exceptions_NotFound
* @throws Brizy_Editor_Exceptions_ServiceUnavailable
*/
public function getPopupsHtml($project, $wpPost, $context)
{
$content = "";
$popups = $this->getMatchingBrizyPopups($wpPost);
foreach ($popups as $brizyPopup) {
/**
* @var Brizy_Editor_Post $brizyPopup ;
*/
if ($brizyPopup->get_needs_compile()) {
$brizyPopup->compile_page();
$brizyPopup->saveStorage();
$brizyPopup->savePost();
}
$compiledPage = $brizyPopup->get_compiled_page();
if ($context == 'head') {
$content = $this->insertHead($content, $compiledPage->get_head());
}
if ($context == 'body') {
$content = $this->insertBody($content, $compiledPage->get_body());
}
}
return $content;
}
private function insertHead($target, $headContent)
{
if (empty($headContent)) {
return $target;
}
return $target."\n\n<!-- POPUP HEAD -->\n{$headContent}\n<!-- POPUP HEAD END-->\n\n";
}
private function insertBody($target, $bodyContent)
{
if (empty($bodyContent)) {
return $target;
}
return $target."\n\n<!-- POPUP BODY -->\n{$bodyContent}\n<!-- POPUP BODY END-->\n\n";
}
/**
* @param null $wpPost
*
* @return array
*/
public function getMatchingBrizyPopups($wpPost = null)
{
if ($wpPost) {
$applyFor = Brizy_Admin_Rule::POSTS;
$entityType = $wpPost->post_type;
$entityValues[] = $wpPost->ID;
} else {
list($applyFor, $entityType, $entityValues) = Brizy_Admin_Rules_Manager::getCurrentPageGroupAndTypeForPopoup(
);
}
return $this->findMatchingPopups($applyFor, $entityType, $entityValues);
}
/**
* @param $applyFor
* @param $entityType
* @param $entityValues
*
* @return array
*/
private function findMatchingPopups($applyFor, $entityType, $entityValues)
{
$resultPopups = array();
$allPopups = get_posts(
array(
'post_type' => self::CP_POPUP,
'numberposts' => -1,
'post_status' => 'publish',
)
);
$allPopups = Brizy_Admin_Rules_Manager::sortEntitiesByRuleWeight(
$allPopups,
[
'type' => $applyFor,
'entityType' => $entityType,
'entityValues' => $entityValues,
]
);
$ruleManager = new Brizy_Admin_Rules_Manager();
foreach ($allPopups as $aPopup) {
$ruleSet = $ruleManager->getRuleSet($aPopup->ID);
try {
if ($ruleSet->isMatching($applyFor, $entityType, $entityValues)) {
$resultPopups[] = Brizy_Editor_Post::get($aPopup);
}
} catch (\Exception $e) {
continue; // we catch here the exclusions
}
}
return $resultPopups;
}
}

View File

@@ -0,0 +1,70 @@
<?php
abstract class Brizy_Admin_Post_AbstractMonitor {
/**
* @var string
*/
protected $postType;
/**
* @var string[]
*/
protected $postMetaKeys;
/**
* @param $postId
* @param $postType
*
* @return mixed
*/
abstract public function shouldStoreMetaRevision( $postId, $postType );
/**
* Brizy_Admin_Post_AbstractMonitor constructor.
*
* @param $postType
* @param array $postMetaKeys
*/
public function __construct( $postType, $postMetaKeys = array() ) {
$this->postType = $postType;
$this->postMetaKeys = $postMetaKeys;
}
/**
* @return mixed
*/
public function getPostType() {
return $this->postType;
}
/**
* @param $postType
*
* @return $this
*/
public function setPostType( $postType ) {
$this->postType = $postType;
return $this;
}
/**
* @return string[]
*/
public function getPostMetaKeys() {
return $this->postMetaKeys;
}
/**
* @param string[] $postMetaKeys
*
* @return Brizy_Admin_Post_AbstractMonitor
*/
public function setPostMetaKeys( $postMetaKeys ) {
$this->postMetaKeys = $postMetaKeys;
return $this;
}
}

View File

@@ -0,0 +1,38 @@
<?php
class Brizy_Admin_Post_BrizyPostsMonitor extends Brizy_Admin_Post_AbstractMonitor {
/**
* Brizy_Admin_Post_BrizyPostsMonitor constructor.
*/
public function __construct() {
parent::__construct( null, array(
'brizy',
'brizy-post-compiler-version',
'brizy-post-editor-version',
'brizy_post_uid',
'brizy-rules',
'brizy_data_version'
) );
}
/**
* @param $postId
* @param $postType
*
* @return bool|mixed
*/
public function shouldStoreMetaRevision( $postId, $postType ) {
return $this->isUsingBrizy( $postId );
}
/**
* @param $postId
*
* @return bool
*/
protected function isUsingBrizy( $postId ) {
$get_post_meta = get_post_meta( $postId, Brizy_Editor_Storage_Post::META_KEY, true );
return ! ! $get_post_meta;
}
}

View File

@@ -0,0 +1,8 @@
<?php
class Brizy_Admin_Post_PostTypeMonitor extends Brizy_Admin_Post_AbstractMonitor {
public function shouldStoreMetaRevision( $postId, $postType ) {
return $this->postType == $postType;
}
}

View File

@@ -0,0 +1,22 @@
<?php
class Brizy_Admin_Post_ProjectPostMonitor extends Brizy_Admin_Post_AbstractMonitor {
/**
* Brizy_Admin_Post_ProjectPostMonitor constructor.
*/
public function __construct() {
parent::__construct( 'brizy-project', array( 'brizy-project','brizy_data_version' ) );
}
/**
* @param $postId
* @param $postType
*
* @return bool|mixed
*/
public function shouldStoreMetaRevision( $postId, $postType ) {
return $this->postType == $postType;
}
}

View File

@@ -0,0 +1,263 @@
<?php
/**
* Class Brizy_Admin_Post_RevisionManager
*/
class Brizy_Admin_Post_RevisionManager {
/**
* @var Brizy_Admin_Post_AbstractMonitor[]
*/
protected $monitors = array();
/**
* Brizy_Admin_Post_RevisionManager constructor.
*/
public function __construct() {
add_action( 'wp_restore_post_revision', array( $this, 'restorePostRevisionMeta' ), 11, 2 );
if ( ! defined( 'WP_POST_REVISIONS' ) || ( defined( 'WP_POST_REVISIONS' ) && WP_POST_REVISIONS !== false ) ) {
add_action( 'save_post', array( $this, 'savePost' ), 11, 2 );
}
}
/**
* @return Brizy_Admin_Post_AbstractMonitor[]
*/
public function getMonitors() {
return $this->monitors;
}
/**
* @param Brizy_Admin_Post_AbstractMonitor[] $monitors
*
* @return Brizy_Admin_Post_RevisionManager
*/
public function setMonitors( $monitors ) {
$this->monitors = $monitors;
return $this;
}
/**
* @param Brizy_Admin_Post_AbstractMonitor $monitor
*
* @return Brizy_Admin_Post_RevisionManager
*/
public function addMonitor( $monitor ) {
$this->monitors[] = $monitor;
return $this;
}
/**
* @param $postId
* @param $type
*
* @return bool
*/
public function getMatchingMonitor( $postId, $type ) {
foreach ( $this->monitors as $monitor ) {
if ( $monitor->shouldStoreMetaRevision( $postId, $type ) ) {
return $monitor;
}
}
return false;
}
/**
* @param $postId
* @param $post
*/
public function savePost( $postId, $post, $update = false ) {
$postParentId = wp_is_post_revision( $postId );
$postType = get_post_type( $post->post_parent );
// ignore all posts that are not watched
if ( $postParentId && $monitor = $this->getMatchingMonitor( $postParentId, $postType ) ) {
// copy meta data only for existing posts
$this->copyMetaDataToRevision( $postParentId, $postId, $monitor );
}
}
/**
* @param int $postId
* @param int $revisionId
*/
public function restorePostRevisionMeta( $postId, $revisionId ) {
$postType = get_post_type( $postId );
// ignore all posts that are not watched
if ( $monitor = $this->getMatchingMonitor( $postId, $postType ) ) {
// copy meta data only for existing posts
$this->restoreRevisionMetaDataToPost( $postId, $revisionId, $monitor );
}
}
/**
* This method will add all meta data entries from $post to $revision post
*
* @param int $post
* @param int $revision
* @param Brizy_Admin_Post_AbstractMonitor $monitor
*/
private function copyMetaDataToRevision( $post, $revision, $monitor ) {
global $wpdb;
$tablePostMeta = $wpdb->postmeta;
$meta_key_count = count( $monitor->getPostMetaKeys() );
$meta_keys_params = rtrim( str_repeat( '%s,', $meta_key_count ), ',' );
$params = array( (int) $revision, (int) $post );
$this->cleanMetaData( $post, $revision, $monitor );
$query = "INSERT INTO {$tablePostMeta} (post_Id, meta_key, meta_value)
SELECT %d, meta_key, meta_value
FROM {$tablePostMeta}
WHERE post_id=%d";
if ( $meta_key_count > 0 ) {
$query .= " and meta_key IN ({$meta_keys_params})";
$params = array_merge( $params, $monitor->getPostMetaKeys() );
} else {
$query .= " and meta_key NOT IN ('_edit_last','_edit_lock','_thumbnail_id','_wp_attached_file','_wp_attachment_metadata')";
}
$wpdb->query( $wpdb->prepare( $query, $params ) );
if ( $meta_key_count > 0 && false !== array_search( 'brizy', $monitor->getPostMetaKeys() ) ) {
$storage = Brizy_Editor_Storage_Post::instance( $revision );
$data = $storage->get( Brizy_Editor_Post::BRIZY_POST );
$data['compiled_html'] = '';
$data['compiled_html_body'] = '';
$data['compiled_html_head'] = '';
$storage->set( Brizy_Editor_Post::BRIZY_POST, $data );
$wpdb->update(
$wpdb->posts,
[ 'post_content' => '<div class="brz-root__container"><!-- version:' . time() . ' --></div>' ],
[ 'ID' => $revision ],
[ '%s' ]
);
}
}
private function cleanMetaData( $post, $revision, $monitor ) {
global $wpdb;
$params = array( (int) $revision );
$meta_key_count = count( $monitor->getPostMetaKeys() );
$meta_keys_params = rtrim( str_repeat( '%s,', $meta_key_count ), ',' );
$tablePostMeta = "{$wpdb->prefix}postmeta";
$query = "DELETE FROM {$tablePostMeta} WHERE post_id=%d and meta_key IN ({$meta_keys_params})";
$params = array_merge( $params, $monitor->getPostMetaKeys() );
$wpdb->query( $wpdb->prepare( $query, $params ) );
}
/**
* This method will add all meta data entries from $revision to $post
*
* @param int $post
* @param int $revision
* @param Brizy_Admin_Post_AbstractMonitor $monitor
*/
private function restoreRevisionMetaDataToPost( $post, $revision, $monitor ) {
global $wpdb;
try {
$tablePostMeta = "{$wpdb->prefix}postmeta";
$wpdb->query( "START TRANSACTION" );
$revisionMetaValues = $this->getRevisionMetaValues( $revision, $monitor );
if ( $revisionMetaValues === false ) {
throw new Exception();
}
foreach ( $revisionMetaValues as $meta ) {
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}postmeta WHERE post_id=%d and meta_key=%s", $post, $meta->meta_key ) );
$res = $wpdb->query( $wpdb->prepare( "INSERT INTO {$tablePostMeta} (post_id,meta_key,meta_value) VALUES (%d,%s,%s)", $post, $meta->meta_key, $meta->meta_value ) );
if ( $res === false ) {
throw new Exception();
}
}
Brizy_Editor_Post::cleanClassCache();
$brizyPost = Brizy_Editor_Post::get( $post );
if ( $brizyPost->uses_editor() ) {
$brizyPost->set_needs_compile( true );
$brizyPost->saveStorage();
}
$wpdb->query( 'COMMIT' );
} catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' );
}
}
/**
* @param int $post
* @param Brizy_Admin_Post_AbstractMonitor $monitor
*/
private function cleanMetakeys( $post, $monitor ) {
global $wpdb;
$meta_key_count = count( $monitor->getPostMetaKeys() );
$params = array( (int) $post );
$meta_keys_params = rtrim( str_repeat( '%s,', $meta_key_count ), ',' );
$query = "DELETE FROM {$wpdb->prefix}postmeta WHERE post_id=%d";
if ( $meta_key_count > 0 ) {
$query .= " and meta_key IN ({$meta_keys_params})";
$params = array_merge( $params, $monitor->getPostMetaKeys() );
} else {
$query .= " and meta_key NOT IN ('_edit_last','_edit_lock','_thumbnail_id','_wp_attached_file','_wp_attachment_metadata')";
}
$wpdb->query( $wpdb->prepare( $query, $params ) );
}
/**
* @param $revision
* @param $monitor
*
* @return array|null|object
*/
private function getRevisionMetaValues( $revision, $monitor ) {
global $wpdb;
$meta_key_count = count( $monitor->getPostMetaKeys() );
$params = array( (int) $revision );
$meta_keys_params = rtrim( str_repeat( '%s,', $meta_key_count ), ',' );
$query = "SELECT * FROM {$wpdb->prefix}postmeta WHERE post_id=%d";
if ( $meta_key_count > 0 ) {
$query .= " and meta_key IN ({$meta_keys_params})";
$params = array_merge( $params, $monitor->getPostMetaKeys() );
} else {
$query .= " and meta_key NOT IN ('_edit_last','_edit_lock','_thumbnail_id','_wp_attached_file','_wp_attachment_metadata')";
}
$query = $wpdb->prepare( $query, $params );
return $wpdb->get_results( $query );
}
}

View File

@@ -0,0 +1,20 @@
<?php
interface Brizy_Admin_RuleInterface {
/**
* @param $applyFor
* @param $entityType
* @param $entityValues
*
* @return mixed
*/
public function isMatching( $applyFor, $entityType, $entityValues );
/**
* @param $context
*
* @return mixed
*/
public function getRuleWeight($context);
}

View File

@@ -0,0 +1,100 @@
<?php
class Brizy_Admin_RuleSet implements Brizy_Admin_RuleInterface {
/**
* @var Brizy_Admin_Rule[]
*/
private $rules;
/**
* Brizy_Admin_RuleSet constructor.
*
* @param $rules
*/
public function __construct( $rules ) {
if ( ! is_array( $rules ) ) {
throw new InvalidArgumentException( 'Invalid RuleSet constructor argument' );
}
$this->rules = $rules;
}
/**
* @param $context
*
* @return float|int
*/
public function getRuleWeight( $context ) {
$array_map = array_map( function ( Brizy_Admin_RuleInterface $v ) use ( $context ) {
return $v->getRuleWeight( $context );
}, $this->rules );
return count( $array_map ) > 0 ? max( $array_map ) : 0;
}
/**
* @param $applyFor
* @param null $entityType
* @param $entityValues
*
* @return bool
*/
public function isMatching( $applyFor, $entityType, $entityValues ) {
if ( count( $this->rules ) == 0 ) {
return false;
}
foreach ( $this->rules as $rule ) {
//var_dump($rule->isMatching( $applyFor, $entityType, $entityValues ));
if ( $rule->isMatching( $applyFor, $entityType, $entityValues ) ) {
if($rule->getType() == Brizy_Admin_Rule::TYPE_INCLUDE)
return true;
throw new \Exception('Exclude catch');
//return $rule->getType() == Brizy_Admin_Rule::TYPE_INCLUDE ? true : false;
}
}
return false;
}
/**
* @return Brizy_Admin_Rule[]
*/
public function getRules() {
return $this->rules;
}
/**
* @param Brizy_Admin_Rule[] $rules
*
* @return Brizy_Admin_RuleSet
*/
public function setRules( $rules ) {
$this->rules = $rules;
return $this;
}
/**
* @param Brizy_Admin_Rule[] $rules
*
* @return $this
*/
public function addRules( $rules ) {
foreach ( (array) $rules as $rule ) {
if ( $rule instanceof Brizy_Admin_Rule ) {
$this->rules[] = $rule;
}
}
return $this;
}
}

View File

@@ -0,0 +1,469 @@
<?php
class Brizy_Admin_Rule extends Brizy_Admin_Serializable implements Brizy_Admin_RuleInterface {
const TYPE_INCLUDE = 1;
const TYPE_EXCLUDE = 2;
const ALL = 0;
const POSTS = 1;
const TAXONOMY = 2;
const ARCHIVE = 4;
const TEMPLATE = 8; // author/search/home_page...
const BRIZY_TEMPLATE = 16; // brizy template
const ANY_CHILD_TAXONOMY = 128;
const WOO_SHOP_PAGE = 256;
const DATE_ARCHIVE = self::ARCHIVE | 512;
const YEAR_ARCHIVE = self::DATE_ARCHIVE | 1024;
const MONTH_ARCHIVE = self::DATE_ARCHIVE | 2048;
const DAY_ARCHIVE = self::DATE_ARCHIVE | 4096;
/**
* @var int
*/
protected $id;
/**
* @var int
*/
protected $type;
/**
* @var int
*/
protected $appliedFor;
/**
* @var string
*/
protected $entityType;
/**
* If null the rule will be applied on all entities
*
* @var int[]
*/
protected $entityValues = array();
/**
* @return array|mixed
*/
public function jsonSerialize() {
return $this->convertToOptionValue();
}
/**
* Brizy_Admin_Rule constructor.
*
* @param int $id
* @param int $type
* @param int $applied_for
* @param int $entity_type
* @param array $entities
*/
public function __construct( $id, $type, $applied_for, $entity_type, $entities ) {
if ( ! $id ) {
$this->setId( $this->generateId( $type, $applied_for, $entity_type, $this->getEntitiesAsString() ) );
} else {
$this->setId( $id );
}
$this->setType( $type );
$this->setAppliedFor( $applied_for );
$this->setEntityType( $entity_type );
$this->setEntityValues( array_filter( (array) $entities, array( $this, 'filter' ) ) );
}
function filter( $v ) {
return ! empty( $v );
}
/**
* Return true if the rule matches for the given parameters
*
* @param $applyFor
* @param $entityType
* @param $entityValues
*
* @return bool
*/
public function isMatching( $applyFor, $entityType, $entityValues ) {
$ruleValues = array(
$this->getType(),
$this->getAppliedFor(),
$this->getEntityType(),
$this->getEntityValues(),
);
$checkValues = array(
self::TYPE_INCLUDE, // include
$applyFor,
$entityType,
$entityValues,
);
// return if the rule is for exclude
// if($ruleValues[0]!=$checkValues[0]) {
// return false;
// }
$entity_values = $this->getEntityValues();
// check is the rule is matching all
if($ruleValues[0]==self::TYPE_INCLUDE && !$ruleValues[1])
return true;
// exception for home page that has two behaviors.. as page and as a template
if ( $applyFor == self::TEMPLATE &&
$entityType == 'front_page' &&
$this->getAppliedFor() == self::POSTS &&
$this->getEntityType() == 'page' &&
isset( $entity_values[0] ) &&
$entity_values[0] == get_option( 'page_on_front' ) ) {
return true;
}
// check post author
if ( isset( $entity_values[0] ) && isset( $entityValues[0] ) && ( $values = explode( '|', $entity_values[0] ) ) && count( $values ) == 2 ) {
if ( $values[0] === 'author' ) {
return get_post_field( 'post_author', $entityValues[0] ) == $values[1];
}
}
// check if post is in a term
if ( isset( $entity_values[0] ) && ( $values = explode( '|', $entity_values[0] ) ) && count( $values ) == 3 ) {
// POSTS
if ( $applyFor == self::POSTS && $this->getAppliedFor() == self::POSTS && $values[0] === 'in' ) {
// check if the post is in taxonomy with name $values[0] and with id $values[1]
return has_term( $values[2], $values[1], $entityValues[0] );
}
// check if post is in a term
if ( $applyFor == self::POSTS && $this->getAppliedFor() == self::POSTS && $values[0] === 'child' ) {
// check if the post is in taxonomy with name $values[0] and with id $values[1]
$tax = get_term_children( $values[2], $values[1] );
foreach ( $tax as $t ) {
if ( has_term( $t, $values[1], $entityValues[0] ) ) {
return true;
}
}
return false;
}
// TAXONOMY
if ( $applyFor == self::TAXONOMY && $this->getAppliedFor() == self::TAXONOMY && $values[0] === 'in' ) {
return $entityValues[0] == $values[2];
}
// check if terms is child of a term
if ( $applyFor == self::TAXONOMY && $this->getAppliedFor() == self::TAXONOMY && $values[0] === 'child' ) {
$tax = get_term_children( $values[2], $values[1] );
return in_array( $entityValues[0], $tax );
}
}
// matching archive rules
if ( isset( $ruleValues[1] ) && isset( $checkValues[1] ) && ( $ruleValues[1] & self::ARCHIVE ) && ( $checkValues[1] & self::ARCHIVE ) ) {
if ($checkValues[1] == $ruleValues[1] ||
$ruleValues[1] == self::DATE_ARCHIVE ||
$ruleValues[1] == self::YEAR_ARCHIVE ||
$ruleValues[1] == self::MONTH_ARCHIVE ||
$ruleValues[1] == self::DAY_ARCHIVE ||
$ruleValues[1] == self::ARCHIVE) {
if(empty($ruleValues[2]) || $ruleValues[2]==$entityType) {
return true;
}
}
}
foreach ( $ruleValues as $i => $value ) {
if($i===0) continue;
if ( is_array( $value ) ) {
// this means that the rule accept any value
if ( count( $ruleValues[ $i ] ) == 0 ) {
break;
}
// check if the value is contained in this rule
if ( count( array_diff( $checkValues[ $i ], $ruleValues[ $i ] ) ) != 0 ) {
return false;
}
} else {
if ( $ruleValues[ $i ] != $checkValues[ $i ] ) {
return false;
}
}
}
return true;
}
/**
* @param Brizy_Admin_Rule $rule
*
* @return bool
*/
public function isEqual( $rule ) {
return $this->getType() == $rule->getType() &&
$this->getAppliedFor() == $rule->getAppliedFor() &&
$this->getEntityType() == $rule->getEntityType() &&
( count( $rule->getEntityValues() ) == count( $this->getEntityValues() ) &&
count( array_diff( $rule->getEntityValues(), $this->getEntityValues() ) ) == 0 );
}
/**
* @return int
*/
public function getId() {
return $this->id;
}
/**
* @param int $id
*
* @return Brizy_Admin_Rule
*/
public function setId( $id ) {
$this->id = $id;
return $this;
}
/**
* @return int
*/
public function getType() {
return (int) $this->type;
}
/**
* @param int $type
*
* @return Brizy_Admin_Rule
*/
public function setType( $type ) {
$this->type = (int) $type;
return $this;
}
/**
* @return int
*/
public function getAppliedFor() {
return $this->appliedFor;
}
/**
* @param int $appliedFor
*
* @return Brizy_Admin_Rule
*/
public function setAppliedFor( $appliedFor ) {
if ( $val = (int) $appliedFor ) {
$this->appliedFor = $val;
}
return $this;
}
/**
* @return string
*/
public function getEntityType() {
return $this->entityType;
}
/**
* @param string $entityType
*
* @return Brizy_Admin_Rule
*/
public function setEntityType( $entityType ) {
$this->entityType = $entityType;
return $this;
}
/**
* @return string[]
*/
public function getEntityValues() {
return $this->entityValues;
}
/**
* @param int[] $entityValues
*
* @return Brizy_Admin_Rule
*/
public function setEntityValues( $entityValues ) {
if ( ! is_array( $entityValues ) ) {
throw new InvalidArgumentException();
}
$this->entityValues = array_values( $entityValues );
return $this;
}
/**
* @return array
*/
public function convertToOptionValue() {
return array(
'id' => $this->getId(),
'type' => $this->getType(),
'appliedFor' => $this->getAppliedFor(),
'entityType' => $this->getEntityType(),
'entityValues' => $this->getEntityValues(),
);
}
public function getRuleWeight( $context ) {
$weight = 0;
if ( $this->getAppliedFor() == self::TEMPLATE && $this->getEntityType() == 'front_page' ) {
$weight += 20;
}
if ( $this->getAppliedFor() == self::TEMPLATE ) {
$weight += 10;
}
if ( $this->getEntityType() === 'product' ) {
$weight += 30;
}
$values = array();
if ( $this->getType() ) {
$values[] = $this->getType();
}
if ( $this->getAppliedFor() ) {
$values[] = $this->getAppliedFor();
}
if ( $this->getEntityType() ) {
$values[] = $this->getEntityType();
}
if ( count( $this->getEntityValues() ) > 0 ) {
$values[] = $this->getEntityType();
}
$weight += count( $values );
if ( isset( $context['type'] ) && $this->getAppliedFor() === $context['type'] ) {
$weight += 1;
}
if ( isset( $context['entityType'] ) && $this->getEntityType() === $context['entityType'] ) {
$weight += 1;
}
if ( isset( $context['entityValues'] ) && $intersection = count(
array_intersect( $context['entityValues'], $this->getEntityValues() )
) ) {
$weight += $intersection;
}
return $weight;
}
/**
* @param $data
*
* @return Brizy_Admin_Rule|void
* @throws Exception
*/
static public function createFromSerializedData( $data ) {
if ( is_null( $data ) ) {
throw new Exception( 'Invalid parameter provided' );
}
return new self(
isset( $data['id'] ) ? $data['id'] : null,
isset( $data['type'] ) && ! empty( $data['type'] ) ? $data['type'] : null,
isset( $data['appliedFor'] ) && ! empty( $data['appliedFor'] ) ? $data['appliedFor'] : null,
isset( $data['entityType'] ) ? $data['entityType'] : null,
isset( $data['entityValues'] ) ? $data['entityValues'] : null
);
}
/**
* @param $data
*
* @return Brizy_Admin_Rule
* @throws Exception
*/
static public function createFromRequestData( $data ) {
if ( is_null( $data ) ) {
throw new Exception( 'Invalid parameter provided' );
}
return new self(
isset( $data['id'] ) ? $data['id'] : null,
isset( $data['type'] ) ? $data['type'] : null,
isset( $data['appliedFor'] ) ? $data['appliedFor'] : null,
isset( $data['entityType'] ) ? $data['entityType'] : null,
isset( $data['entityValues'] ) ? $data['entityValues'] : null
);
}
static public function createFromJsonObject( $json ) {
if ( is_null( $json ) ) {
throw new Exception( 'Invalid parameter provided' );
}
return new self(
isset( $json->id ) ? $json->id : null,
isset( $json->type ) ? $json->type : null,
isset( $json->appliedFor ) ? $json->appliedFor : null,
isset( $json->entityType ) ? $json->entityType : null,
isset( $json->entityValues ) ? $json->entityValues : null
);
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->convertToOptionValue() );
}
/**
* @param string $delimited
*
* @return string
*/
public function getEntitiesAsString( $delimited = ',' ) {
return implode( $delimited, $this->getEntityValues() );
}
/**
* @return string
*/
private function generateId() {
return md5( implode( '', func_get_args() ) . rand( 1, time() ) );
}
}

View File

@@ -0,0 +1,139 @@
<?php
abstract class Brizy_Admin_Rules_AbstractValidator implements Brizy_Admin_Rules_ValidatorInterface {
/**
* @var int
*/
private $postId;
/**
* @var Brizy_Admin_Rules_Manager
*/
protected $manager;
/**
* Brizy_Admin_Rules_TemplateRuleValidator constructor.
*
* @param int $postId
* @param Brizy_Admin_Rules_Manager $manager
*/
public function __construct( $postId, Brizy_Admin_Rules_Manager $manager ) {
$this->manager = $manager;
$this->postId = (int) $postId;
}
/**
* @param Brizy_Admin_Rule $rule
* @param int $postId
*
* @return mixed
*/
abstract public function validateRuleForPostId( Brizy_Admin_Rule $rule, $postId );
/**
* @param Brizy_Admin_Rule[] $rules
* @param int $postId
*
* @return mixed
*/
abstract public function validateRulesForPostId( $rules, $postId );
/**
* @param Brizy_Admin_Rule $rule
* @param Brizy_Admin_RuleSet $targetRuleSet
*
* @return mixed
* @throws Brizy_Admin_Rules_ValidationException
*/
public function validateRule( Brizy_Admin_Rule $rule, $targetRuleSet ) {
foreach ( $targetRuleSet->getRules() as $arule ) {
if ( $rule->isEqual( $arule ) ) {
throw new Brizy_Admin_Rules_ValidationException( $arule->getId(), 'The rule is already used' );
}
}
return true;
}
/**
* @param $rules
* @param Brizy_Admin_RuleSet $targetRuleSet
*
* @return mixed
* @throws Brizy_Admin_Rules_ValidationException
*/
public function validateRules( $rules, $targetRuleSet ) {
$errors = array();
foreach ( $targetRuleSet->getRules() as $arule ) {
foreach ( $rules as $newRule ) {
if ( $newRule->isEqual( $arule ) ) {
throw new Brizy_Admin_Rules_ValidationException( $arule->getId(), 'The rule is already used' );
}
}
}
if ( count( $errors ) > 0 ) {
return $errors;
}
return array();
}
/**
* @param array $args
*
* @return Brizy_Admin_RuleSet
* @throws Exception
*/
protected function getRulesSetByWPQuery( $args = array() ) {
$defaults = array(
'posts_per_page' => - 1,
'post_status' => array( 'publish', 'pending', 'draft', 'future', 'private', 'inherit' )
);
$r = wp_parse_args( $args, $defaults );
$templates = get_posts( $r );
$rules = array();
foreach ( $templates as $template ) {
$tRules = $this->manager->getRules( $template->ID );
$rules = array_merge( $rules, $tRules );
}
$rules = self::sortRules( $rules );
return new Brizy_Admin_RuleSet( $rules );
}
/**
* @param Brizy_Admin_Rule[] $rules
*
* @return mixed
*/
static public function sortRules( $rules ) {
// sort the rules by how specific they are
usort( $rules, function ( $a, $b ) {
/**
* @var Brizy_Admin_Rule $a ;
* @var Brizy_Admin_Rule $b ;
*/
$la = $a->getRuleWeight([]);
$lb = $b->getRuleWeight([]);
if ( $lb == $la ) {
return 0;
}
return $la < $lb ? 1 : - 1;
} );
return $rules;
}
}

View File

@@ -0,0 +1,794 @@
<?php
class Brizy_Admin_Rules_Api extends Brizy_Admin_AbstractApi
{
const nonce = Brizy_Editor_API::nonce;
const CREATE_RULES_ACTION = '_add_rules';
const CREATE_RULE_ACTION = '_add_rule';
const UPDATE_RULES_ACTION = '_update_rules';
const DELETE_RULE_ACTION = '_delete_rule';
const LIST_RULE_ACTION = '_list_rules';
const VALIDATE_RULE = '_validate_rule';
const RULE_GROUP_LIST = '_rule_group_list';
const RULE_POSTS_GROUP_LIST = '_rule_posts_group_list';
const RULE_ARCHIVE_GROUP_LIST = '_rule_archive_group_list';
const RULE_TEMPLATE_GROUP_LIST = '_rule_template_group_list';
/**
* @var Brizy_Admin_Rules_Manager
*/
private $manager;
/**
* Brizy_Admin_Rules_Api constructor.
*
* @param Brizy_Admin_Rules_Manager $manager
*/
public function __construct($manager)
{
$this->manager = $manager;
parent::__construct();
}
/**
* @return Brizy_Admin_Rules_Api
*/
public static function _init()
{
static $instance;
if (!$instance) {
$instance = new self(new Brizy_Admin_Rules_Manager());
}
return $instance;
}
protected function getRequestNonce()
{
return $this->param('hash');
}
protected function initializeApiActions()
{
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
add_action($pref . self::CREATE_RULE_ACTION, array($this, 'actionCreateRule'));
add_action($pref . self::CREATE_RULES_ACTION, array($this, 'actionCreateRules'));
add_action($pref . self::UPDATE_RULES_ACTION, array($this, 'actionUpdateRules'));
add_action($pref . self::DELETE_RULE_ACTION, array($this, 'actionDeleteRule'));
add_action($pref . self::LIST_RULE_ACTION, array($this, 'actionGetRuleList'));
add_action($pref . self::VALIDATE_RULE, array($this, 'actionValidateRule'));
add_action($pref . self::RULE_GROUP_LIST, array($this, 'getGroupList'));
add_action($pref . self::RULE_POSTS_GROUP_LIST, array($this, 'getPostsGroupsList'));
add_action($pref . self::RULE_ARCHIVE_GROUP_LIST, array($this, 'getArchiveGroupsList'));
add_action($pref . self::RULE_TEMPLATE_GROUP_LIST, array($this, 'getTemplateGroupsList'));
}
/**
* @return null|void
*/
public function actionGetRuleList()
{
$this->verifyNonce(self::nonce);
$postId = (int)$this->param('post');
if (!$postId) {
wp_send_json_error((object)array('message' => 'Invalid template'), 400);
}
try {
$rules = $this->manager->getRules($postId);
$this->success($rules);
} catch (Exception $e) {
Brizy_Logger::instance()->error($e->getMessage(), [$e]);
$this->error(400, $e->getMessage());
}
return null;
}
public function actionValidateRule()
{
$this->verifyNonce(self::nonce);
$postId = (int)$this->param('post');
$postType = get_post_type($postId);
if (!$postId) {
$this->error(400, "Validation" . 'Invalid post');
}
$ruleData = file_get_contents("php://input");
try {
$rule = $this->manager->createRuleFromJson($ruleData, $postType);
$ruleValidator = Brizy_Admin_Rules_ValidatorFactory::getValidator($postId);
if (!$ruleValidator) {
$this->error(400, 'Unable to get the rule validator for this post type');
}
$ruleValidator->validateRuleForPostId($rule, $postId);
wp_send_json_success($rule, 200);
} catch (Brizy_Admin_Rules_ValidationException $e) {
wp_send_json_error(array('message' => $e->getMessage(), 'rule' => $e->getRuleId()), 400);
} catch (Exception $e) {
$this->error(400, "Validation" . $e->getMessage());
}
}
public function actionCreateRule()
{
$this->verifyNonce(self::nonce);
$postId = (int)$this->param('post');
$ignoreDataVersion = (int)$this->param('ignoreDataVersion');
$dataVersion = (int)$this->param('dataVersion');
$postType = get_post_type($postId);
if (!$postId) {
$this->error(400, "Validation" . 'Invalid post');
}
if (!$dataVersion && $ignoreDataVersion === 0) {
$this->error(400, "Validation" . 'Invalid data version');
}
$ruleData = file_get_contents("php://input");
try {
$rule = $this->manager->createRuleFromJson($ruleData, $postType);
} catch (Exception $e) {
$this->error(400, "Validation" . $e->getMessage());
}
try {
// validate rule
$ruleValidator = Brizy_Admin_Rules_ValidatorFactory::getValidator($postId);
if (!$ruleValidator) {
$this->error(400, 'Unable to get the rule validator for this post type');
}
$ruleValidator->validateRuleForPostId($rule, $postId);
if (!$ignoreDataVersion) {
$post = Brizy_Editor_Entity::get($postId);
$post->setDataVersion($dataVersion);
$post->save(0);
}
$this->manager->addRule($postId, $rule);
} catch (Brizy_Editor_Exceptions_DataVersionMismatch $e) {
$this->error(400, 'Invalid data version');
} catch (Brizy_Admin_Rules_ValidationException $e) {
wp_send_json_error(array('message' => $e->getMessage(), 'rule' => $e->getRuleId()), 400);
} catch (Exception $e) {
$this->error(400, $e->getMessage());
}
wp_send_json_success($rule, 200);
}
public function actionCreateRules()
{
$this->verifyNonce(self::nonce);
$postId = (int)$this->param('post');
$ignoreDataVersion = (int)$this->param('ignoreDataVersion');
$dataVersion = (int)$this->param('dataVersion');
$postType = get_post_type($postId);
if (!$postId) {
$this->error(400, 'Invalid post');
}
if (!$dataVersion && $ignoreDataVersion === 0) {
$this->error(400, "Validation" . 'Invalid data version');
}
$rulesData = file_get_contents("php://input");
try {
$rules = $this->manager->createRulesFromJson($rulesData, $postType);
if (count($rules) == 0) {
$this->error(400, "No rules found.");
}
} catch (Exception $e) {
$this->error(400, $e->getMessage());
}
// validate rule
$validator = Brizy_Admin_Rules_ValidatorFactory::getValidator($postId);
if (!$validator) {
$this->error(400, 'Unable to get the rule validator for this post type');
}
try {
$validator->validateRulesForPostId($rules, $postId);
if (!$ignoreDataVersion) {
$post = Brizy_Editor_Entity::get($postId);
$post->setDataVersion($dataVersion);
$post->save(0);
}
foreach ($rules as $newRule) {
$this->manager->addRule($postId, $newRule);
}
} catch (Brizy_Editor_Exceptions_DataVersionMismatch $e) {
$this->error(400, 'Invalid data version');
} catch (Brizy_Admin_Rules_ValidationException $e) {
wp_send_json_error(array(
'rule' => $e->getRuleId(),
'message' => $e->getMessage()
), 400);
}
$this->success($rules);
return null;
}
public function actionUpdateRules()
{
$this->verifyNonce(self::nonce);
$postId = (int)$this->param('post');
$ignoreDataVersion = (int)$this->param('ignoreDataVersion');
$dataVersion = (int)$this->param('dataVersion');
$postType = get_post_type($postId);
if (!$postId || !in_array($postType, [
Brizy_Admin_Templates::CP_TEMPLATE,
Brizy_Admin_Popups_Main::CP_POPUP
])) {
wp_send_json_error((object)array('message' => 'Invalid template'), 400);
}
if (!$dataVersion && $ignoreDataVersion === 0) {
$this->error(400, "Validation" . 'Invalid data version');
}
$rulesData = file_get_contents("php://input");
try {
$rules = $this->manager->createRulesFromJson($rulesData, $postType);
} catch (Exception $e) {
Brizy_Logger::instance()->error($e->getMessage(), [$e]);
$this->error(400, $e->getMessage());
}
// $validator = Brizy_Admin_Rules_ValidatorFactory::getValidator( $postId );
// if ( ! $validator ) {
// $this->error( 400, 'Unable to get the rule validator for this post type' );
// }
try {
if (!$ignoreDataVersion) {
$post = Brizy_Editor_Entity::get($postId);
$post->setDataVersion($dataVersion);
$post->save(0);
}
$this->manager->saveRules($postId, $rules);
} catch (Brizy_Editor_Exceptions_DataVersionMismatch $e) {
$this->error(400, 'Invalid data version');
} catch (Exception $e) {
$this->error(400, 'Unable to save rules');
}
wp_send_json_success($rules, 200);
return null;
}
public function actionDeleteRule()
{
$this->verifyNonce(self::nonce);
$postId = (int)$this->param('post');
$ignoreDataVersion = (int)$this->param('ignoreDataVersion');
$dataVersion = (int)$this->param('dataVersion');
$ruleId = $this->param('rule');
if (!$postId || !$ruleId) {
$this->error(400, 'Invalid request');
}
if (!$dataVersion && $ignoreDataVersion === 0) {
$this->error(400, "Validation" . 'Invalid data version');
}
try {
if (!$ignoreDataVersion) {
$post = Brizy_Editor_Entity::get($postId);
$post->setDataVersion($dataVersion);
$post->save(0);
}
$this->manager->deleteRule($postId, $ruleId);
} catch (Brizy_Editor_Exceptions_DataVersionMismatch $e) {
$this->error(400, 'Invalid data version');
} catch (Exception $e) {
$this->error(400, 'Unable to delete rules');
}
$this->success(null);
}
public function getGroupList()
{
$context = $this->param('context');
$templateType = $this->param('templateType');
$closure = function ($v) {
return array(
'title' => $v->label,
'value' => $v->name,
'groupValue' => $v->groupValue
);
};
$groups = [];
if ($templateType == 'single' || $templateType == 'single_product' || $context == 'popup-rules') {
$groups[] = array(
'title' => 'Pages',
'value' => Brizy_Admin_Rule::POSTS,
'items' => array_map($closure, $this->getCustomPostsList(Brizy_Admin_Rule::POSTS, $templateType, $context))
);
}
if ($templateType == 'product_archive') {
$wooPageItems = $this->getWooPageList(Brizy_Admin_Rule::ARCHIVE, $templateType);
$groups[] =
$templateType == 'product_archive' && count($wooPageItems) && Brizy_Editor_Editor_Editor::get_woocomerce_plugin_info() ? array(
'title' => 'Pages',
'value' => Brizy_Admin_Rule::WOO_SHOP_PAGE,
'items' => $wooPageItems
) : null;
}
if ($templateType == 'archive' || $templateType == 'product_archive' || $context == 'popup-rules') {
$archiveItems = array_map($closure, $this->getArchivesList(Brizy_Admin_Rule::ARCHIVE, $templateType));
$taxonomyItems = array_map($closure, $this->getTaxonomyList(Brizy_Admin_Rule::TAXONOMY, $templateType));
if ($templateType === 'product_archive') {
$archiveItems[] = array(
'title' => 'Search page',
'value' => 'search',
'groupValue' => Brizy_Admin_Rule::TEMPLATE
);
}
$groups[] =
count($taxonomyItems) ? array(
'title' => 'Categories',
'value' => Brizy_Admin_Rule::TAXONOMY,
'items' => $taxonomyItems
) : null;
$groups[] =
count($archiveItems) ? array(
'title' => 'Archives',
'value' => Brizy_Admin_Rule::ARCHIVE,
'items' => $archiveItems
) : null;
}
if ($items = $this->geTemplateList($context, $templateType)) {
$groups[] = array(
'title' => 'Others',
'value' => Brizy_Admin_Rule::TEMPLATE,
'items' => $items
);
}
$groups = array_values(array_filter($groups, function ($o) {
return !is_null($o);
}));
wp_send_json_success($groups, 200);
}
public function getPostsGroupsList()
{
global $wp_post_types;
if (!($post_type = $this->param('postType'))) {
wp_send_json_error('Invalid post type', 400);
}
if (!isset($wp_post_types[$post_type])) {
wp_send_json_error('Post type not found', 400);
}
$postTypeName = $wp_post_types[$post_type]->labels->name;
$taxonomies = get_object_taxonomies($post_type, 'objects');
if (isset($taxonomies['product_visibility'])) {
unset($taxonomies['product_visibility']);
}
$groups = array();
$closureFromTerm = function ($v) {
return array(
'title' => $v->name,
'value' => "in|" . $v->taxonomy . "|" . $v->term_id,
'groupValue' => $v->taxonomy
);
};
$closureChildTerm = function ($v) {
return array(
'title' => $v->name,
'value' => "child|" . $v->taxonomy . "|" . $v->term_id,
'groupValue' => $v->taxonomy
);
};
$closureAuthor = function ($v) use ($postTypeName) {
return array(
'title' => ucfirst($v->data->user_nicename),
'value' => 'author|' . $v->ID,
'groupValue' => 'author'
);
};
$closurePost = function ($v) {
return array(
'title' => $v->post_title,
'value' => $v->ID,
'groupValue' => $v->post_type
);
};
// exclude woocomerce hidden tags
$exclude = ['simple', 'variable', 'grouped', 'external'];
foreach ($taxonomies as $tax) {
$groups[] = array(
'title' => __("From", 'brizy') . " " . $tax->labels->singular_name,
'value' => Brizy_Admin_Rule::POSTS,
'items' => array_map($closureFromTerm, array_filter(get_terms([
'taxonomy' => $tax->name,
'hide_empty' => false,
]), function ($term) use ($exclude) {
return in_array($term->slug, $exclude) ? false : true;
}))
);
if ($tax->hierarchical) {
$groups[] = array(
'title' => __("From any child of", 'brizy') . " " . $tax->labels->singular_name,
'value' => Brizy_Admin_Rule::POSTS,
'items' => array_map($closureChildTerm, get_terms([
'taxonomy' => $tax->name,
'hide_empty' => false
]))
);
}
}
unset($taxonomies);
$groups[] = array(
'title' => 'Specific ' . $postTypeName,
'value' => Brizy_Admin_Rule::POSTS,
'items' => array_map($closurePost, Brizy_Editor_Post::get_post_list(null, $post_type, null, 0, 10000))
);
$groups[] = array(
'title' => 'Specific Author',
'value' => Brizy_Admin_Rule::POSTS,
'items' => array_map($closureAuthor, get_users())
);
$groups = array_values(array_filter($groups, function ($o) {
return !is_null($o);
}));
wp_send_json_success($groups, 200);
}
public function getArchiveGroupsList()
{
if (!($taxonomy = $this->param('taxonomy'))) {
wp_send_json_error('Invalid taxonomy', 400);
}
$groups = [];
$taxonomies = get_taxonomies(array('public' => true, 'show_ui' => true, 'name' => $taxonomy), 'objects');
$closureSingleTerm = function ($v) {
return array(
'title' => $v->name,
'value' => $v->term_id,
'groupValue' => $v->taxonomy
);
};
$closureTerm = function ($v) {
return array(
'title' => $v->name,
'value' => "child|" . $v->taxonomy . "|" . $v->term_id,
'groupValue' => $v->taxonomy
);
};
foreach ($taxonomies as $tax) {
$groups[] = array(
'title' => __("Specific", 'brizy') . " " . $tax->labels->singular_name,
'value' => Brizy_Admin_Rule::TAXONOMY,
'items' => array_map($closureSingleTerm, get_terms([
'taxonomy' => $tax->name,
'hide_empty' => false
]))
);
if ($tax->hierarchical) {
$groups[] = array(
'title' => __("Any child of", 'brizy') . " " . $tax->labels->singular_name,
'value' => Brizy_Admin_Rule::TAXONOMY,
'items' => array_map($closureTerm, get_terms([
'taxonomy' => $tax->name,
'hide_empty' => false
]))
);
}
}
$groups = array_values(array_filter($groups, function ($o) {
return !is_null($o);
}));
wp_send_json_success($groups, 200);
}
public function getTemplateGroupsList()
{
$context = $this->param('context');
$templateType = $this->param('templateType');
$groups = [];
$closureAuthor = function ($v) {
return array(
'title' => $v->user_nicename,
'value' => $v->ID,
'groupValue' => 'author'
);
};
$groups[] = array(
'title' => 'Specific Author',
'value' => Brizy_Admin_Rule::TEMPLATE,
'items' => array_map($closureAuthor, get_users(['fields' => ['ID', 'user_nicename']]))
);
$groups = array_values(array_filter($groups, function ($o) {
return !is_null($o);
}));
wp_send_json_success($groups, 200);
}
private function getCustomPostsList($groupValue, $templateType, $context)
{
$postTypes = get_post_types( [ 'public' => true,'show_ui'=>true ], 'objects' );
$postTypes = array_diff_key( $postTypes, array_flip( [
'attachment',
'elementor_library',
Brizy_Admin_Stories_Main::CP_STORY
] ) );
$postTypes = array_filter( $postTypes, function ( $type ) use ( $groupValue, $templateType, $context ) {
if($context=='template-rules')
{
if ( $type->name == 'product' ) {
return $templateType == 'single_product';
} else {
return $templateType == 'single';
}
}
return $type->public && $type->show_ui;
} );
return array_map(function ($t) use ($groupValue) {
$t->groupValue = $groupValue;
return $t;
}, array_values($postTypes) );
}
private function getWooPageList($groupValue, $templateType)
{
return [
[
'title' => 'Shop Page',
'value' => 'shop_page',
'groupValue' => Brizy_Admin_Rule::WOO_SHOP_PAGE
]
];
}
private function getArchivesList($groupValue, $templateType)
{
global $wp_post_types;
return array_values(array_filter($wp_post_types, function ($type) use ($groupValue, $templateType) {
$type->groupValue = $groupValue;
$is_product = $type->name == 'product';
if ($templateType == 'product_archive') {
return $is_product && $type->public && $type->show_ui && $type->has_archive;
} else {
return !$is_product && $type->public && $type->show_ui && $type->has_archive;
}
}));
}
private function getTaxonomyList($groupValue, $templateType)
{
$terms = get_taxonomies(array('public' => true, 'show_ui' => true), 'objects');
return array_values(array_filter($terms, function ($term) use ($groupValue, $templateType) {
$term->groupValue = $groupValue;
$is_product_term = $term->name == 'product_cat' || $term->name == 'product_tag';
if ($templateType == 'product_archive') {
return $is_product_term;
} else {
return !$is_product_term;
}
}));
}
public function geTemplateList($context, $templateType)
{
$list = array(
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Author page',
'value' => 'author',
'groupValue' => Brizy_Admin_Rule::TEMPLATE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Search page',
'value' => 'search',
'groupValue' => Brizy_Admin_Rule::TEMPLATE
) : null,
$templateType === 'single' || $context == 'popup-rules' ? array(
'title' => 'Front page',
'value' => 'front_page',
'groupValue' => Brizy_Admin_Rule::TEMPLATE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Blog / Posts page',
'value' => 'home_page',
'groupValue' => Brizy_Admin_Rule::TEMPLATE
) : null,
$templateType === 'single' || $context == 'popup-rules' ? array(
'title' => '404 page',
'value' => '404',
'groupValue' => Brizy_Admin_Rule::TEMPLATE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Day Archive page',
'value' => '',
'groupValue' => Brizy_Admin_Rule::DAY_ARCHIVE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Month Archive page',
'value' => '',
'groupValue' => Brizy_Admin_Rule::MONTH_ARCHIVE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Year Archive page',
'value' => '',
'groupValue' => Brizy_Admin_Rule::YEAR_ARCHIVE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Date Archive page',
'value' => '',
'groupValue' => Brizy_Admin_Rule::DATE_ARCHIVE
) : null,
$templateType === 'archive' || $context == 'popup-rules' ? array(
'title' => 'Archive page',
'value' => '',
'groupValue' => Brizy_Admin_Rule::ARCHIVE
) : null,
);
if (($context !== 'template-rules' && $templateType === 'single') || $context == 'popup-rules') {
$list[] = array(
'title' => 'Brizy Templates',
'value' => 'brizy_template',
'groupValue' => Brizy_Admin_Rule::BRIZY_TEMPLATE
);
}
return array_values(array_filter($list, function ($o) {
return !is_null($o);
}));
}
private function get_post_list($searchTerm, $postType, $excludePostType = array())
{
global $wp_post_types;
add_filter('posts_where', array($this, 'brizy_post_title_filter'), 10, 2);
$post_query = array(
'post_type' => $postType,
'posts_per_page' => -1,
'post_status' => $postType == 'attachment' ? 'inherit' : array(
'publish',
'pending',
'draft',
'future',
'private'
),
'orderby' => 'post_title',
'order' => 'ASC'
);
if ($searchTerm) {
$post_query['post_title_term'] = $searchTerm;
}
$posts = new WP_Query($post_query);
$result = array();
foreach ($posts->posts as $post) {
if (in_array($post->post_type, $excludePostType)) {
continue;
}
$result[] = (object)array(
'ID' => $post->ID,
'uid' => $this->create_uid($post->ID),
'post_type' => $post->post_type,
'post_type_label' => $wp_post_types[$post->post_type]->label,
'title' => apply_filters('the_title', $post->post_title),
'post_title' => apply_filters('the_title', $post->post_title)
);
}
remove_filter('posts_where', 'brizy_post_title_filter', 10);
return $result;
}
}

View File

@@ -0,0 +1,396 @@
<?php
class Brizy_Admin_Rules_Manager {
/**
* @return array|null
*/
static function getCurrentPageGroupAndType() {
global $wp_query;
if ( ! isset( $wp_query ) || is_admin() ) {
return null;
}
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = null;
$entityValues = array();
if ( is_404() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = '404';
} elseif ( is_author() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'author';
$author_obj = $wp_query->get_queried_object();
$entityValues[] = $author_obj->ID;
} elseif ( is_search() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'search';
} elseif ( function_exists( 'is_shop' ) && is_shop() ) {
$applyFor = Brizy_Admin_Rule::WOO_SHOP_PAGE;
$entityType = 'shop_page';
} elseif ( is_front_page() && ! is_home() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'front_page';
} elseif ( is_home() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'home_page';
} elseif ( is_category() || is_tag() || is_tax() ) {
$applyFor = Brizy_Admin_Rule::TAXONOMY;
$entityType = $wp_query->queried_object->taxonomy;
$entityValues[] = $wp_query->queried_object_id;
} elseif ( is_day() ) {
$applyFor = Brizy_Admin_Rule::DAY_ARCHIVE;
if ( $wp_query->queried_object ) {
$entityType = $wp_query->queried_object->name;
} else $entityType = 'post';
} elseif ( is_month() ) {
$applyFor = Brizy_Admin_Rule::MONTH_ARCHIVE;
if ( $wp_query->queried_object ) {
$entityType = $wp_query->queried_object->name;
} else $entityType = 'post';
} elseif ( is_year() ) {
$applyFor = Brizy_Admin_Rule::YEAR_ARCHIVE;
if ( $wp_query->queried_object ) {
$entityType = $wp_query->queried_object->name;
} else $entityType = 'post';
} elseif ( is_date() ) {
$applyFor = Brizy_Admin_Rule::DATE_ARCHIVE;
if ( $wp_query->queried_object ) {
$entityType = $wp_query->queried_object->name;
} else $entityType = 'post';
} elseif ( is_archive() || isset($_REQUEST['post_type']) ) {
$applyFor = Brizy_Admin_Rule::ARCHIVE;
if ( $wp_query->queried_object ) {
$entityType = $wp_query->queried_object->name;
} else $entityType = 'post';
} elseif ( ( $wp_query->queried_object instanceof WP_Post || $wp_query->post instanceof WP_Post ) && get_queried_object() ) {
$applyFor = Brizy_Admin_Rule::POSTS;
$entityType = get_queried_object()->post_type;
$entityValues[] = get_queried_object_id();
}
return array( $applyFor, $entityType, $entityValues );
}
/**
* @return array|null
*/
static function getCurrentPageGroupAndTypeForPopoup() {
global $wp_query;
if ( ! isset( $wp_query ) || is_admin() ) {
return null;
}
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = null;
$entityValues = array();
/* if ( is_404() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = '404';
} elseif ( is_author() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'author';
} elseif ( is_search() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'search';
} elseif ( is_front_page() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'front_page';
} elseif ( is_home() ) {
$applyFor = Brizy_Admin_Rule::TEMPLATE;
$entityType = 'home_page';
} else*/
if ( is_category() || is_tag() || is_tax() ) {
$applyFor = Brizy_Admin_Rule::TAXONOMY;
$entityType = $wp_query->queried_object->taxonomy;
$entityValues[] = $wp_query->queried_object_id;
} elseif ( is_archive() ) {
$applyFor = Brizy_Admin_Rule::ARCHIVE;
if ( $wp_query->queried_object ) {
$entityType = $wp_query->queried_object->name;
}
} elseif ( ( $wp_query->queried_object instanceof WP_Post || $wp_query->post instanceof WP_Post ) && get_queried_object() ) {
$applyFor = Brizy_Admin_Rule::POSTS;
$entityType = get_queried_object()->post_type;
$entityValues[] = get_queried_object_id();
}
return array( $applyFor, $entityType, $entityValues );
}
/**
* @param $entities
* @param $context
*
* @return mixed
*/
static function sortEntitiesByRuleWeight( $entities, $context ) {
$ruleManager = new Brizy_Admin_Rules_Manager();
// sort templates by rule set weight
usort( $entities, function ( $t1, $t2 ) use ( $ruleManager, $context ) {
$ruleSetT1 = $ruleManager->getRuleSet( $t1->ID );
$ruleSetT2 = $ruleManager->getRuleSet( $t2->ID );
$rule_weight_t1 = $ruleSetT1->getRuleWeight( $context );
$rule_weight_t2 = $ruleSetT2->getRuleWeight( $context );
if ( $rule_weight_t1 == $rule_weight_t2 ) {
return 0;
}
return ( $rule_weight_t1 < $rule_weight_t2 ) ? 1 : - 1;
} );
return $entities;
}
/**
* @param $jsonString
* @param string $postType
*
* @return Brizy_Admin_Rule
* @throws Exception
*/
public function createRuleFromJson( $jsonString, $postType = Brizy_Admin_Templates::CP_TEMPLATE ) {
$ruleJson = json_decode( $jsonString );
return Brizy_Admin_Rule::createFromJsonObject( $ruleJson );
}
/**
* @param $jsonString
* @param string $postType
*
* @return array
* @throws Exception
*/
public function createRulesFromJson( $jsonString, $postType = Brizy_Admin_Templates::CP_TEMPLATE ) {
$rulesJson = json_decode( $jsonString );
$rules = array();
if ( is_array( $rulesJson ) ) {
foreach ( $rulesJson as $ruleJson ) {
$rules[] = Brizy_Admin_Rule::createFromJsonObject( $ruleJson );
}
}
return $rules;
}
/**
* @param $postId
*
* @return array
* @throws Exception
*/
public function getRules( $postId ) {
$rules = array();
$meta_value = get_post_meta( (int) $postId, 'brizy-rules', true );
// fallback if the migration was not run
if ( ! $meta_value ) {
$meta_value = get_post_meta( (int) $postId, 'brizy-template-rules', true );
}
if ( is_array( $meta_value ) && count( $meta_value ) ) {
foreach ( $meta_value as $v ) {
$brizy_admin_rule = Brizy_Admin_Rule::createFromSerializedData( $v );
$rules[] = $brizy_admin_rule;
}
}
$rules = Brizy_Admin_Rules_AbstractValidator::sortRules( $rules );
return $rules;
}
/**
* @param $postId
* @param Brizy_Admin_Rule[] $rules
*/
public function saveRules( $postId, $rules ) {
$arrayRules = array();
foreach ( $rules as $rule ) {
$arrayRules[] = $rule->convertToOptionValue();
}
update_metadata( 'post', (int) $postId, 'brizy-rules', $arrayRules );
}
/**
* @param $postId
* @param Brizy_Admin_Rule $rule
*/
public function addRule( $postId, $rule ) {
$rules = $this->getRules( $postId );
$rules[] = $rule;
$this->saveRules( $postId, $rules );
}
/**
* @param $postId
* @param $ruleId
*/
public function deleteRule( $postId, $ruleId ) {
$rules = $this->getRules( $postId );
foreach ( $rules as $i => $rule ) {
if ( $rule->getId() == $ruleId ) {
unset( $rules[ $i ] );
}
}
$this->saveRules( $postId, $rules );
}
/**
* @param $postId
* @param Brizy_Admin_Rule[] $rules
*/
public function addRules( $postId, $rules ) {
$current_rules = $this->getRules( $postId );
$result_rules = array_merge( $current_rules, $rules );
$this->saveRules( $postId, $result_rules );
}
/**
* @param $postId
* @param Brizy_Admin_Rule[] $rules
*/
public function setRules( $postId, $rules ) {
$this->saveRules( $postId, $rules );
}
/**
* @param int $postId
*
* @return Brizy_Admin_RuleSet
*/
public function getRuleSet( $postId ) {
return new Brizy_Admin_RuleSet( $this->sortRules( $this->getRules( $postId ) ) );
}
//
public function getAllRulesSet( $args = array(), $postType = Brizy_Admin_Templates::CP_TEMPLATE ) {
$defaults = array(
'post_type' => $postType,
'posts_per_page' => - 1,
'post_status' => array( 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit' )
);
$r = wp_parse_args( $args, $defaults );
$templates = get_posts( $r );
$rules = array();
foreach ( $templates as $template ) {
$tRules = $this->getRules( $template->ID );
$rules = array_merge( $rules, $tRules );
}
$rules = $this->sortRules( $rules );
$ruleSet = new Brizy_Admin_RuleSet( $rules );
return $ruleSet;
}
private function sortRules( $rules ) {
// sort the rules by how specific they are
usort( $rules, function ( $a, $b ) {
/**
* @var Brizy_Admin_Rule $a ;
* @var Brizy_Admin_Rule $b ;
*/
$la = $a->getRuleWeight([]);
$lb = $b->getRuleWeight([]);
if ( $lb == $la ) {
return 0;
}
return $la < $lb ? 1 : - 1;
} );
return $rules;
}
//
// /**
// * @param $postType
// * @param Brizy_Admin_Rule $rule
// *
// * @return object|null
// */
// public function validateRuleByPost( $postId, Brizy_Admin_Rule $rule ) {
// $ruleSet = $this->getAllRulesSet( array(), $postType );
// foreach ( $ruleSet->getRules() as $arule ) {
//
// if ( $rule->isEqual( $arule ) ) {
// return (object) array(
// 'message' => 'The rule is already used',
// 'rule' => $arule->getId()
// );
// }
// }
//
// return null;
// }
// /**
// * @param $postType
// * @param Brizy_Admin_Rule $rule
// *
// * @return object|null
// */
// public function validateRule( $postType, Brizy_Admin_Rule $rule ) {
// $ruleSet = $this->getAllRulesSet( array(), $postType );
// foreach ( $ruleSet->getRules() as $arule ) {
//
// if ( $rule->isEqual( $arule ) ) {
// return (object) array(
// 'message' => 'The rule is already used',
// 'rule' => $arule->getId()
// );
// }
// }
//
// return null;
// }
//
// /**
// * @param $postType
// * @param array $rules
// *
// * @return array
// */
// public function validateRules( $postType, array $rules ) {
// // validate rule
// $ruleSet = $this->getAllRulesSet( array(), $postType );
// $errors = array();
// foreach ( $ruleSet->getRules() as $arule ) {
// foreach ( $rules as $newRule ) {
// if ( $newRule->isEqual( $arule ) ) {
// $errors[] = (object) array(
// 'message' => 'The rule is already used',
// 'rule' => $arule->getId()
// );
// }
// }
// }
//
// if ( count( $errors ) > 0 ) {
// return $errors;
// }
//
// return array();
// }
}

View File

@@ -0,0 +1,43 @@
<?php
class Brizy_Admin_Rules_PopupRuleValidator extends Brizy_Admin_Rules_AbstractValidator {
/**
* @param Brizy_Admin_Rule $rule
* @param int $postId
*
* @return mixed
* @throws Brizy_Admin_Rules_ValidationException
* @throws Exception
*/
public function validateRuleForPostId( Brizy_Admin_Rule $rule, $postId ) {
$ruleSet = $this->getPopupRuleSet( $postId );
return $this->validateRule( $rule, $ruleSet );
}
/**
* @param Brizy_Admin_Rule[] $rules
* @param int $postId
*
* @return mixed
* @throws Brizy_Admin_Rules_ValidationException
*/
public function validateRulesForPostId( $rules, $postId ) {
$ruleSets = $this->getPopupRuleSet( $postId );
return $this->validateRules( $rules, $ruleSets );
}
private function getPopupRuleSet( $postId ) {
$rules = $this->manager->getRules( $postId );
$rules = self::sortRules( $rules );
return new Brizy_Admin_RuleSet( $rules );
}
}

View File

@@ -0,0 +1,35 @@
<?php
class Brizy_Admin_Rules_TemplateRuleValidator extends Brizy_Admin_Rules_AbstractValidator {
/**
* @param Brizy_Admin_Rule $rule
* @param int $postId
*
* @return mixed
* @throws Brizy_Admin_Rules_ValidationException
*/
public function validateRuleForPostId( Brizy_Admin_Rule $rule, $postId ) {
$ruleSets = $this->getRulesSetByWPQuery( [ 'post_type' => get_post_type( $postId ) ] );
return $this->validateRule( $rule, $ruleSets );
}
/**
* @param Brizy_Admin_Rule[] $rules
* @param int $postId
*
* @return mixed
* @throws Brizy_Admin_Rules_ValidationException
*/
public function validateRulesForPostId( $rules, $postId ) {
$ruleSets = $this->getRulesSetByWPQuery( [
'post_type' => get_post_type( $postId ),
'exclude' => [ $postId ]
] );
return $this->validateRules( $rules, $ruleSets );
}
}

View File

@@ -0,0 +1,33 @@
<?php
class Brizy_Admin_Rules_ValidationException extends Exception {
/**
* @var string
*/
private $ruleId;
public function __construct( $ruleId, $message = "", $code = 0, Throwable $previous = null ) {
parent::__construct( $message, $code, $previous );
$this->setRuleId( $ruleId );
}
/**
* @return string
*/
public function getRuleId() {
return $this->ruleId;
}
/**
* @param string $ruleId
*
* @return Brizy_Admin_Rules_ValidationException
*/
public function setRuleId( $ruleId ) {
$this->ruleId = $ruleId;
return $this;
}
}

View File

@@ -0,0 +1,26 @@
<?php
class Brizy_Admin_Rules_ValidatorFactory {
/**
* @param int $postId
*
* @return Brizy_Admin_Rules_PopupRuleValidator|Brizy_Admin_Rules_TemplateRuleValidator|null
*/
static public function getValidator( $postId ) {
$postType = get_post_type( $postId );
switch ( $postType ) {
case Brizy_Admin_Templates::CP_TEMPLATE:
return new Brizy_Admin_Rules_TemplateRuleValidator( $postId, new Brizy_Admin_Rules_Manager() );
break;
case Brizy_Admin_Popups_Main::CP_POPUP:
return new Brizy_Admin_Rules_PopupRuleValidator( $postId, new Brizy_Admin_Rules_Manager() );
break;
default:
return null;
}
}
}

View File

@@ -0,0 +1,23 @@
<?php
interface Brizy_Admin_Rules_ValidatorInterface {
/**
* @param Brizy_Admin_Rule $rule
* @param Brizy_Admin_RuleSet $targetRuleSet
*
* @return mixed
*/
public function validateRule( Brizy_Admin_Rule $rule, $targetRuleSet );
/**
* @param $rules
* @param Brizy_Admin_RuleSet $targetRuleSet
*
* @return mixed
*/
public function validateRules( $rules, $targetRuleSet );
}

View File

@@ -0,0 +1,46 @@
<?php
abstract class Brizy_Admin_Serializable implements Serializable, JsonSerializable {
/**
* @return string
*/
public function serialize() {
$get_object_vars = get_object_vars( $this );
return serialize( $get_object_vars );
}
/**
* @param string $data
*/
public function unserialize( $data ) {
$vars = unserialize( $data );
foreach ( $vars as $prop => $value ) {
$this->$prop = $value;
}
}
/**
* @return mixed
*/
abstract public function convertToOptionValue();
/**
* @param $data
*
* @throws Exception
*/
static public function createFromSerializedData( $data ) {
throw new Exception( 'Not implemented' );
}
/**
* @return array|mixed
*/
public function jsonSerialize() {
return get_object_vars( $this );
}
}

View File

@@ -0,0 +1,585 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Admin_Settings {
private $selected_post_types;
private $role_list;
private $capability_options;
/**
* @var string
*/
private $screenName;
public static function menu_slug() {
return Brizy_Editor::prefix('-settings');
}
/**
* @return Brizy_Admin_Settings
*/
public static function _init() {
static $instance;
return $instance ? $instance : $instance = new self();
}
/**
* Brizy_Admin_Settings constructor.
*/
private function __construct() {
add_action( 'admin_menu', array( $this, 'actionRegisterSettingsPage' ) );
if ( ! is_network_admin() ) {
add_action( 'admin_menu', array( $this, 'actionRegisterSubMenuSettingsPage' ), 9 );
add_action( 'admin_menu', array( $this, 'actionRegisterSubMenuGetHelpLink' ), 20 );
add_action( 'admin_menu', array( $this, 'actionRegisterSubMenuGoProPage' ), 20 );
}
add_action( 'submenu_file', array( $this, 'submenu_file' ), 10, 2 );
add_action( 'current_screen', array( $this, 'action_validate_form_submit' ) );
add_action( 'brizy_settings_role_capability_row', array( $this, 'role_capability_select_row' ) );
add_action( 'brizy_settings_post_type_row', array( $this, 'post_type_row' ) );
add_action( 'brizy_settings_submit', array( $this, 'settings_submit' ) );
add_action( 'brizy_settings_render_tabs', array( $this, 'render_tabs' ) );
add_action( 'brizy_settings_render_content', array( $this, 'render_tab_content' ) );
$this->role_list = self::get_role_list();
$this->capability_options = $this->get_capability_options();
try {
$this->selected_post_types = Brizy_Editor_Storage_Common::instance()->get( 'post-types' );
} catch ( Exception $e ) {
$this->selected_post_types = array( 'post', 'page' );
Brizy_Editor_Storage_Common::instance()->set( 'post-types', $this->selected_post_types );
}
}
/**
* Keep the tempate menu selected
*
* @param $submenu_file
* @param $parent_file
*/
function submenu_file( $submenu_file, $parent_file ) {
global $post_type, $pagenow;
if ( $parent_file !== Brizy_Admin_Settings::menu_slug() || $pagenow !== 'post-new.php' ) {
return $submenu_file;
}
return "edit.php?post_type={$post_type}";
}
/**
* @internal
*/
function actionRegisterSettingsPage() {
if ( ! Brizy_Editor_User::is_user_allowed() || is_network_admin() ) {
return;
}
$this->screenName = add_menu_page( Brizy_Editor::get()->get_name(),
Brizy_Editor::get()->get_name(),
'read',
self::menu_slug(),
array( $this, 'render' ),
'',
'58'
);
}
/**
* @internal
*/
function actionRegisterSubMenuSettingsPage() {
add_submenu_page( self::menu_slug(),
__( 'Settings', 'brizy' ),
__( 'Settings', 'brizy' ),
'manage_options',
self::menu_slug(),
array( $this, 'render' )
);
}
/**
* @internal
*/
function actionRegisterSubMenuGetHelpLink() {
if ( class_exists( 'BrizyPro_Admin_WhiteLabel' ) && BrizyPro_Admin_WhiteLabel::_init()->getEnabled() ) {
return;
}
if ( !class_exists( 'BrizyPro_Main' ) ) {
return;
}
global $submenu;
$submenu[self::menu_slug()][] = array( '<span id="get-help"></span>'.__( 'Get Help', 'brizy' ) , 'manage_options', __bt('support-url',apply_filters('brizy_support_url', Brizy_Config::SUPPORT_URL)) );
}
/**
* @internal
*/
public function actionRegisterSubMenuGoProPage() {
global $submenu;
if ( class_exists( 'BrizyPro_Main' ) ) {
return;
}
$submenu[self::menu_slug()][] = array( '<span style="display:flex;color:#00b9eb;" id="go-pro">
<svg height="20" width="20">
<path d="M13,7 L12,7 L12,4.73333333 C12,2.6744 10.206,1 8,1 C5.794,1 4,2.6744 4,4.73333333 L4,7 L3,7 C2.448,7 2,7.41813333 2,7.93333333 L2,14.0666667 C2,14.5818667 2.448,15 3,15 L13,15 C13.552,15 14,14.5818667 14,14.0666667 L14,7.93333333 C14,7.41813333 13.552,7 13,7 Z M10,5 L12,5 L12,7 L10,7 L6,7 L6,5 C6,3.897 6.897,3 8,3 C9.103,3 10,3.897 10,5 Z" fill="#00b9eb" fill-rule="nonzero"/>
</svg>'.__( 'Go Pro', 'brizy' )."</span>" , 'manage_options', apply_filters('brizy_upgrade_to_pro_url', Brizy_Config::UPGRADE_TO_PRO_URL) );
}
private function get_selected_tab() {
return ( ! empty( $_REQUEST['tab'] ) ) ? esc_attr( $_REQUEST['tab'] ) : null;
}
private function get_tabs() {
$selected_tab = $this->get_selected_tab();
$tabs = [
[
'id' => 'general',
'label' => __( 'General', 'brizy' ),
'is_selected' => is_null( $selected_tab ) || $selected_tab == 'general',
'href' => menu_page_url( self::menu_slug(), false ) . '&tab=general'
],
[
'id' => 'roles',
'label' => __( 'Role Manager', 'brizy' ),
'is_selected' => $selected_tab == 'roles',
'href' => menu_page_url( self::menu_slug(), false ) . '&tab=roles'
],
[
'id' => 'maintenance',
'label' => __( 'Maintenance Mode', 'brizy' ),
'is_selected' => $selected_tab == 'maintenance',
'href' => menu_page_url( self::menu_slug(), false ) . '&tab=maintenance'
]
];
return apply_filters( 'brizy_settings_tabs', $tabs, $selected_tab );
}
private function get_tab_content( $tab ) {
switch ( $tab ) {
default:
case 'general':
return $this->get_general_tab();
break;
case 'roles':
return $this->get_roles_tab();
break;
case 'maintenance':
return $this->get_maintenance_tab();
break;
}
}
private function get_general_tab() {
$list_post_types = $this->list_post_types();
$prepared_types = array_map( array( $this, 'is_selected' ), $list_post_types );
$svgEnabled = Brizy_Editor_Storage_Common::instance()->get( 'svg-upload', false );
$jsonEnabled = Brizy_Editor_Storage_Common::instance()->get( 'json-upload', false );
return Brizy_Admin_View::render(
'settings/general',
[
'types' => $prepared_types,
'svgUploadEnabled' => $svgEnabled,
'jsonUploadEnabled' => $jsonEnabled
]
);
}
private function get_roles_tab() {
return Brizy_Admin_View::render(
'settings/roles',
array( 'roles' => array_map( array( $this, 'is_role_selected' ), $this->list_wp_roles() ), )
);
}
private function get_maintenance_tab() {
$args = Brizy_MaintenanceMode::get_settings();
$args['pages'] = wp_list_pluck( get_pages(), 'post_title', 'ID' );
$args['available_roles'] = $this->list_wp_roles();
return Brizy_Admin_View::render( 'settings/maintenance', $args );
}
public function settings_submit() {
$screen = get_current_screen();
if ( $this->screenName != $screen->id ) {
return;
}
switch ( $_POST['tab'] ) {
case 'general':
$this->general_settings_submit();
break;
case 'roles':
$this->roles_settings_submit();
break;
case 'maintenance':
$this->maintenance_settings_submit();
break;
}
}
public function general_settings_submit() {
$error_count = 0;
$allowed_post_types = array_map( array( $this, 'to_type' ), $this->post_types() );
$post_types = isset( $_POST['post-types'] ) ? (array) $_POST['post-types'] : array();
$array_diff = array_diff( $post_types, $allowed_post_types );
$svgEnabled = isset( $_POST['svg-upload-enabled'] ) ? (bool) $_POST['svg-upload-enabled'] : false;
$jsonEnabled = isset( $_POST['json-upload-enabled'] ) ? (bool) $_POST['json-upload-enabled'] : false;
if ( count( $array_diff ) > 0 ) {
//error
Brizy_Admin_Flash::instance()->add_error( 'Invalid post type selected' );
$error_count ++;
}
Brizy_Editor_Storage_Common::instance()->set( 'svg-upload', $svgEnabled );
Brizy_Editor_Storage_Common::instance()->set( 'json-upload', $jsonEnabled );
if ( $error_count == 0 ) {
$this->selected_post_types = $post_types;
Brizy_Editor_Storage_Common::instance()->set( 'post-types', $post_types );
}
}
public function maintenance_settings_submit() {
Brizy_Editor_Storage_Common::instance()->set( 'maintenance', $_POST['brizy-maintenance'] );
}
/**
* Return the list of allowed capabilities Ids
* @return array
*/
public function get_capabilities() {
$capabilities = $this->get_capability_options();
$caps = array();
foreach ( $capabilities as $capability ) {
$caps[] = $capability['capability'];
}
return $caps;
}
/**
* Return the list of capabilities including the label
*
* @return mixed|void
*/
public function get_capability_options() {
return apply_filters( 'brizy_settings_capability_options', array(
array( 'capability' => '', 'label' => __( 'No Access' ) ),
array(
'capability' => Brizy_Admin_Capabilities::CAP_EDIT_WHOLE_PAGE,
'label' => __( 'Full Access', 'brizy' )
)
) );
}
public function roles_settings_submit() {
$allowed_roles = array_map( array( $this, 'role_to_id' ), $this->list_wp_roles() );
$allowed_capabilities = $this->get_capabilities();
$roles = isset( $_POST['role-capability'] ) ? (array) $_POST['role-capability'] : array();
if ( count( $roles ) != 0 ) {
foreach ( $roles as $role_id => $capability ) {
if ( ! in_array( $role_id, $allowed_roles ) ) {
continue;
}
// validate capability
if ( $capability != "" && ! in_array( $capability, $allowed_capabilities ) ) {
continue;
}
// remove all brizy capabilities from this role
foreach ( $allowed_capabilities as $cap ) {
wp_roles()->remove_cap( $role_id, $cap );
}
if ( $capability != "" ) {
wp_roles()->add_cap( $role_id, $capability );
}
}
}
}
/**
* @internal
*/
public function render() {
if ( is_network_admin() ) {
return;
}
try {
echo Brizy_Admin_View::render(
'settings/view',
array()
);
} catch ( Exception $e ) {
}
}
public function render_tabs() {
$tabs = $this->get_tabs();
foreach ( $tabs as $tab ) {
$is_active_class = $tab['is_selected'] ? 'nav-tab-active' : '';
?>
<a href="<?php echo $tab['href'] ?>"
class="nav-tab <?php echo $is_active_class ?>"><?php echo __( $tab['label'] ) ?></a>
<?php
}
}
public function render_tab_content() {
$tab = $this->get_selected_tab();
echo apply_filters( 'brizy_settings_render_tab', $this->get_tab_content( $tab ), $tab );
}
/**
* @internal
**/
public function action_validate_form_submit() {
if ( count( $_POST ) == 0 ) {
return;
}
if ( ! isset( $_POST['tab'] ) ) {
return;
}
if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'] ) ) {
return;
}
do_action( 'brizy_settings_submit' );
if ( ! Brizy_Admin_Flash::instance()->has_notice_type( Brizy_Admin_Flash::ERROR ) ) {
Brizy_Admin_Flash::instance()->add_success( 'Settings saved.' );
}
$tab = $this->get_selected_tab();
wp_redirect( menu_page_url( $this->menu_slug(), false ) . ( $tab ? '&tab=' . $tab : '' ) );
exit;
}
protected function list_post_types() {
$types = $this->post_types();
return array_map( array( $this, 'post_type_to_choice' ), $types );
}
static public function get_role_list() {
$roles = wp_roles()->roles;
unset( $roles['administrator'] );
foreach ( $roles as $key => $role ) {
$roles[ $key ]['id'] = $key;
}
$roles = apply_filters( 'brizy_settings_roles', $roles );
return $roles;
}
/**
* @return array
*/
public function list_wp_roles() {
return $this->role_list;
}
/**
* @return array
*/
protected function post_types() {
$types = get_post_types( array( 'public' => true ), 'objects' );
$types = array_filter(
$types,
array( $this, 'filter_types' )
);
return apply_filters( 'brizy_settings_post_types', $types );
}
private function post_type_to_choice( WP_Post_Type $type ) {
return array(
'type' => $type->name,
'name' => $type->labels->name,
);
}
private function to_type( WP_Post_Type $type ) {
return $type->name;
}
private function role_to_id( $value ) {
return $value['id'];
}
private function filter_types( WP_Post_Type $type ) {
return ! in_array( $type->name, array( 'attachment', 'elementor_library', Brizy_Admin_Stories_Main::CP_STORY ) );
}
private function is_selected( $type ) {
$type['selected'] = in_array( $type['type'], $this->selected_post_types );
return $type;
}
private function is_role_selected( $role ) {
$role['selected'] = ! isset( $role['capabilities'][ Brizy_Admin_Capabilities::CAP_EDIT_WHOLE_PAGE ] );
return $role;
}
public function role_capability_select_row( $role ) {
?>
<tr class="user-display-name-wrap">
<th><label for="display_name"><?php echo $role['name'] ?></label></th>
<td>
<select name="role-capability[<?php echo $role['id'] ?>]">
<?php
foreach ( $this->capability_options as $option ) {
?>
<option value="<?php echo $option['capability'] ?>"
<?php echo isset( $role['capabilities'][ $option['capability'] ] ) ? 'selected' : '' ?>>
<?php echo $option['label'] ?>
</option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
public function post_type_row( $type ) {
?>
<label>
<input type="checkbox"
name="post-types[]"
value="<?php echo $type['type']; ?>"
<?php echo $type['selected'] ? 'checked' : ''; ?>
>
<?php echo $type['name']; ?>
</label>
<?php
}
}

View File

@@ -0,0 +1,656 @@
.brizy-editor-enabled #insert-media-button,
.brizy-editor-enabled #wp-content-editor-tools .wp-editor-tabs,
.brizy-editor-enabled #wp-content-editor-container .quicktags-toolbar,
.brizy-editor-enabled #wp-content-editor-container .wp-editor-area,
.brizy-editor-enabled .editor-block-list__layout,
.brizy-editor-enabled .block-editor-block-list__layout,
.brizy-editor-enabled .block-editor-writing-flow__click-redirect,
.brizy-editor-enabled .edit-post-text-editor__body .editor-post-text-editor {
display: none;
}
#brizy-admin-enable,
#brizy-admin-disable {
float: left;
}
#brizy-admin-disable,
.brizy-editor-enabled #brizy-admin-enable {
display: none;
}
.brizy-editor-enabled #brizy-admin-disable {
display: block;
}
.brizy-editor {
padding: 10% 0;
display: none;
background: #fff;
align-items: center;
justify-content: center;
}
.brizy-editor-enabled .brizy-editor {
display: flex;
}
.brizy-button--arrow {
max-height: 14px;
margin-right: 11px;
}
.brizy-buttons {
margin-top:auto;
margin-bottom:auto;
text-align:center;
}
.brizy-buttons .button {
height: 33px;
min-height: 32px !important;
line-height: 1 !important;
display: inline-flex;
align-items: center;
}
.brizy-buttons .button::before {
background-color: white;
content: "\00a0";
width: 20px;
height: 20px;
margin-right: 10px;
}
.is-classic-editor {
margin: 20px 20px 20px 0;
text-align: left;
}
.brizy-buttons-gutenberg {
margin-bottom: 50px;
height: 300px;
width: 100%;
}
.brizy-buttons-gutenberg a {
height: 100%;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
border: 1px solid #dedede;
background-color: #f9f9f9;
text-decoration: none;
position: relative;
}
.brizy-buttons-gutenberg .button {
min-height: 46px !important;
padding-left: 35px !important;
padding-right: 35px !important;
}
.brizy-buttons-gutenberg a:hover {
background-color: #fff
}
.brizy-button {
padding: 0px 12px 0px;
border-style: solid;
border-width: 1px;
border-bottom: 0;
border-radius: 3px;
background-color: #d62c64;
text-shadow: none;
font-size: 13px;
font-family: "Open Sans", sans-serif;
color: #fff !important;
line-height: 1;
display: inline-flex;
align-items: center;
text-decoration: none;
transition: all 200ms linear;
height: 33px;
}
.brizy-go-editor-back-arrow {
padding-bottom: 5px;
font-size: 18px;
}
.brizy-button--default {
font-size: 15px;
color: #444;
border-color: #e5e5e5;
background-color: #fff;
box-shadow: 0px 2px 0px 0px #e3e3e3;
}
.brizy-button--primary {
color: #555 !important;
border-color: #ccc !important;
background-color: #f7f7f7 !important;
box-shadow: 0 1px 0 #ccc !important;
-webkit-box-shadow: 0 1px 0 #ccc!important;
}
a.brizy-button--primary:hover {
background-color: #e9e9e9 !important;
}
.brizy-button--default:hover,
.brizy-button--default:focus,
.brizy-button--default:active {
color: #444;
border-color: #e5e5e5;
background-color: #fff;
box-shadow: 0px 2px 0px 0px #e3e3e3;
}
/**
* Style Brizy Templates
*/
.brizy-template-rules .error {
color: red;
}
.brizy-template-rules .rules-container {
position: relative;
}
.brizy-template-rules .rules-container .lock-screen {
position: absolute;
top:0px;
left:0px;
bottom:0px;
right: 0px;
background: white;
opacity: 0.3;
text-align: center;
font-size: 3em;
padding-top: 1em;
}
.brizy-template-rules input[type="text"],
.brizy-template-rules select {
vertical-align: middle;
height: 28px;
line-height: 28px;
background-color: #fff;
border: 1px solid #aaa;
border-radius: 4px;
box-sizing: border-box;
cursor: pointer;
user-select: none;
-webkit-user-select: none;
box-shadow: none;
}
.brizy-rule-select,
.brizy-rule-select ~ .select2-container {
margin-right: 5px;
}
.brizy-template-rules .rule:not(:first-of-type) {
margin-top: 10px;
}
.brizy-template-rules .rule {
position: relative;
}
.brizy-template-rules .rule .rule-fields {
position: relative;
}
.brizy-template-rules .rule .overlay {
position: absolute;
top: -10px;
bottom: -10px;
left: 0px;
right: 0px;
}
.brizy-delete-rule {
border: 0;
padding: 0;
font-size: 13px;
text-decoration: underline;
cursor: pointer;
background: none;
color: #a00;
}
#template-rules .inside {
padding-bottom: 20px;
}
.brizy-rule-select > select {
padding-left: 8px;
padding-right: 20px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1;
appearance: none;
}
.brizy-rule-select > select:disabled {
color: #444;
background-color: #eee;
border: 1px solid #aaa;
}
.brizy-rule-select--options {
min-width: 175px;
}
.brizy-rule-select {
position: relative;
}
.brizy-template-rules .select2-selection__arrow {
color: #32373c;
border-color: #7e8993;
box-shadow: none;
border-radius: 3px;
padding: 0 5px 0 0;
-webkit-appearance: none;
background: #fff url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20width%3D%2220%22%20height%3D%2220%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M5%206l5%205%205-5%202%201-7%207-7-7%202-1z%22%20fill%3D%22%23555%22%2F%3E%3C%2Fsvg%3E') no-repeat left 5px top 55%;
background-size: 16px 16px;
cursor: pointer;
vertical-align: middle;
}
.brizy-template-rules .brizy-template-type label {
margin-right: 20px;
}
.brizy-template-rules .select2-selection__arrow b {
display: none;
}
.brizy-rule-new-condition .brizy-rule-select2::after {
content: none;
}
.brizy-rule-list-item {
}
.brizy-featured-image {
}
.brizy-featured-image .wrapper {
position: relative;
}
.brizy-featured-image .focal-point {
position: absolute;
z-index: 10;
width: 14px;
height: 14px;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #2eb0d8;
border: 2px solid #fff;
border-radius: 18px;
cursor: pointer;
}
.brizy-featured-image .deleteImage {
position: absolute;
right: -4px;
top: -4px;
z-index: 11;
font-size: 16px;
width: 16px;
height: 16px;
background-color: #2d323b;
border-radius: 50%;
color: #fff;
cursor: pointer;
}
.brizy-featured-image .deleteImage svg {
display: inline-block;
width: 1em;
height: 1em;
position: relative;
color: #efefef;
fill: #efefef;
stroke: none;
}
#brizy_dashboard .brizy-overview__feed {
font-size: 14px;
font-weight: 500;
}
#brizy_dashboard .e-brizy__feed .e-overview__post-link {
padding-bottom: 5px;
}
#brizy_dashboard .brizy-overview__recently-edited .brizy-overview__heading, #brizy_dashboard .brizy-overview__feed .brizy-overview__heading {
font-weight: 700;
border-bottom: 1px solid #eee;
margin: 0 -12px;
padding: 6px 12px;
}
#brizy_dashboard .brizy-overview__badge {
background: #39b54a;
color: #fff;
font-size: .75em;
padding: 3px 6px;
-webkit-border-radius: 3px;
border-radius: 3px;
text-transform: uppercase
}
.brizy-dashboard-widget-footer {
margin-top: 0;
margin-bottom: 0;
padding: 12px 12px 12px 0;
border-top: 1px solid #eee;
}
.brizy-dashboard-widget-footer a {
margin: 0 10px;
display: inline-block;
text-decoration: none;
}
.brizy-dashboard-widget-footer a:first-child {
margin-left: 0;
}
.brizy-dashboard-widget-footer a .dashicons {
font-size: 17px;
}
.brizy-dashboard-widget-footer__go-pro {
display: inline-flex;
fill: #0073aa;
}
.brizy-dashboard-widget-footer__go-pro:hover {
fill: #00a0d2;
}
.brizy-dashboard-widget-footer__go-pro svg {
vertical-align: bottom;
}
/* Maintenance Mode */
.brz-maintenance-table-access-links {
max-width: 1024px;
/*text-align: left;*/
}
.brz-maintenance-table-access-links th,
.brz-maintenance-table-access-links td {
border: 1px solid #ccd0d4;
}
.brz-maintenance-table-access-links th:first-child,
.brz-maintenance-table-access-links td:first-child {
width: 35px;
text-align: center;
}
.brz-maintenance-table-access-links th:not(:first-child) {
padding-left: 10px;
}
.brz-maintenance-delete-links {
padding-left: 10px !important;
}
.brz-maintenance-add-link {
margin-top: 15px !important;
}
/* Admin notice give us a rating */
.brz-review-notice-container {
display: flex;
align-items: center;
padding-top: 10px;
}
.brz-review-notice-container .dashicons {
font-size: 1.4em;
padding-left: 10px;
}
.brz-review-notice-container a {
padding-left: 5px;
text-decoration: none;
}
.brz-review-notice-container .dashicons:first-child {
padding-left: 0;
}
.brz-notice-image {
max-width: 100px;
}
.brz-notice-content .brz-notice-heading {
padding-bottom: 5px;
}
.brz-notice-content {
margin-left: 15px;
}
.brz-notice-container {
padding-top: 10px;
padding-bottom: 10px;
display: flex;
justify-content: left;
align-items: center;
}
/* Admin deactivate plugin modal */
.brz-deactivate-modal {
border-radius: 3px;
animation: brz-feedback-modal-fadein .5s linear;
}
.brz-deactivate-overlay {
animation: brz-feedback-overlay-fadein .5s linear;
}
.brz-deactivate-feedback-dialog-logo {
width: 40px;
vertical-align: middle;
}
.brz-deactivate-modal .ui-dialog-titlebar {
display: none;
}
.brz-deactivate-modal .ui-dialog-content {
padding: 0;
}
.brz-deactivate-feedback-dialog-header {
padding: 18px 15px;
box-shadow: 0 0 8px rgba(0, 0, 0, .1);
text-align: left;
}
.brz-deactivate-feedback-dialog-header-title {
font-size: 15px;
text-transform: uppercase;
font-weight: 700;
padding-left: 5px;
color: #495157;
}
.brz-deactivate-feedback-dialog-form {
padding: 30px;
text-align: left;
}
.brz-deactivate-feedback-dialog-form-caption {
font-weight: 700;
font-size: 15px;
color: #495157;
line-height: 1.4;
margin-bottom: 30px;
}
.brz-deactivate-feedback-dialog-input {
float: left;
margin: 0 15px 0 0;
box-shadow: none;
}
.brz-deactivate-feedback-dialog-label {
display: block;
font-size: 13px;
color: #6d7882;
}
#brz-deactivate-feedback-dialog .brz-deactivate-feedback-dialog-input {
float: left;
margin: 0 15px 0 0;
box-shadow: none;
}
.brz-deactivate-feedback-dialog-input-wrapper {
line-height: 1.3;
overflow: hidden;
margin-bottom: 15px;
}
.brz-deactivate-modal .ui-dialog-buttonpane {
border: none;
padding-bottom: 30px;
border-radius: 3px;
}
.brz-deactivate-modal .ui-dialog-buttonset {
float: none;
}
.brz-feedback-submit {
background-color: #05b3e6;
color: #fff;
width: 180px;
height: 38px;
border: none;
}
.brz-feedback-submit:hover,
.brz-feedback-submit:focus {
opacity: 0.9;
background-color: #05b3e6;
color: #fff !important;
}
.brz-feedback-submit:disabled:hover {
color: #a4afb7 !important;
}
.brz-feedback-skip {
font-size: 12px;
color: #a4afb7;
background: none;
float: right;
width: auto;
border: none;
box-shadow: none;
}
.brz-feedback-skip:hover,
.brz-feedback-skip:active,
.brz-feedback-skip:focus {
opacity: 0.8;
color: #a4afb7;
background: none;
box-shadow: none;
}
.brz-feedback-text {
margin: 10px 0 0 30px;
padding: 5px;
font-size: 13px;
-webkit-box-shadow: none;
box-shadow: none;
background-color: #fff;
width: 92%;
}
.brz-feedback-text-alert {
max-width: fit-content;
color: #b01b1b;
padding: 0;
}
@-webkit-keyframes brz-feedback-modal-fadein {
0% {
opacity: 0;
}
to {
opacity: 1;
}
}
@-webkit-keyframes brz-feedback-overlay-fadein {
0% {
opacity: 0;
}
to {
opacity: 0.7;
}
}
@-webkit-keyframes brz-rotation {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes brz-rotation {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.brz-loading:before {
display: inline-block;
content: "\f463";
font: 18px dashicons;
animation: brz-rotation 2s linear infinite;
margin-top: 10px;
}
.brz-leads-export-disable {
pointer-events: none;
cursor: default;
opacity: 0.5;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 564 B

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="16px" height="16px" viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Icons / Brizy / logo</title>
<g id="Icons-/-Brizy-/-logo" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<path d="M8.31363932,1.00097401 C14.6921658,1.04143425 14.9865593,2.3548823 15.0001467,7.26264889 L15.0001467,8.73850282 C14.9863402,13.7254269 14.6825962,15.0011517 8.00022831,15.0011517 C1.42392978,15.0011517 1.02536623,13.7656047 1.00121086,8.97318 L0.999847253,8.49821537 C0.999652451,8.33614065 0.999652451,8.17028679 0.999652451,8.00057586 L0.999676802,7.74889252 C0.999701152,7.66595585 0.999749852,7.58397371 0.999847253,7.50293635 L1.00121086,7.02797171 C1.02536623,2.235547 1.42392978,1 8.00022831,1 Z M4.3880998,8.44637849 L3.57881198,9.29081447 L8.09695816,11.9481732 L12.6151044,9.29081447 L11.8298616,8.46052061 L8.09695816,10.6253103 L4.3880998,8.44637849 Z M8.09695816,3.94761089 L3.57881198,6.65368016 L8.09695816,9.3597494 L12.6151044,6.65368016 L8.09695816,3.94761089 Z M8.09695816,5.24430492 L10.5506638,6.71811036 L8.09695816,8.19191581 L5.64325255,6.71811036 L8.09695816,5.24430492 Z" id="Combined-Shape" fill="#03080F" fill-rule="nonzero"></path>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 498 B

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="87px" height="74px" viewBox="0 0 87 74" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Brizy logo</title>
<g id="Brizy-logo" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Group" transform="translate(5.000000, 5.000000)">
<path d="M0,23.3212886 L38.4152832,3.55271368e-15 L76.8305664,23.3212886 L38.4152832,46.6425772 L0,23.3212886 Z M13.7901017,23.8765574 L38.4152832,38.8688143 L63.0404647,23.8765574 L38.4152832,8.88430041 L13.7901017,23.8765574 Z" id="Top-element" fill="#181C25" fill-rule="nonzero"></path>
<polygon id="Bottom-el" fill="#A7B2DD" points="0 40.1772962 6.88092406 36 38.4152832 55.1225586 70.1540838 36.124113 76.8305664 40.1772962 38.4152832 63.4985848"></polygon>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 881 B

View File

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<symbol id="circle" viewBox="0 0 16 16">
<g class="nc-icon-wrapper" fill="#111111">
<g class="nc-loop_circle-02-16" transform="rotate(46.097857151180506 8 8)">
<path opacity="0.4" fill="#111111"
d="M8,16c-4.4111328,0-8-3.5888672-8-8s3.5888672-8,8-8s8,3.5888672,8,8S12.4111328,16,8,16z M8,2C4.6914062,2,2,4.6914062,2,8s2.6914062,6,6,6s6-2.6914062,6-6S11.3085938,2,8,2z"></path>
<path data-color="color-2"
d="M16,8h-2c0-3.3085938-2.6914062-6-6-6V0C12.4111328,0,16,3.5888672,16,8z"></path>
</g>
</g>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 721 B

View File

@@ -0,0 +1,36 @@
jQuery(document).ready(function ($) {
var BrizyCloud = {
form: null,
pageUrl: null,
init: function (form) {
BrizyCloud.form = form;
BrizyCloud.pageUrl = form.attr('action');
form.find('select[name=brizy-cloud-use-container]').on('change', BrizyCloud.containerChange)
},
containerChange: function (e) {
var value = e.target.value;
$.ajax({
url: Brizy_Admin_Data.url,
data: {action: 'brizy-cloud-projects', container: value}
}).done(function (response) {
var select = BrizyCloud.form
.find('select[name=brizy-cloud-use-project]');
select
.find('option[value!=0]')
.remove();
for (var i = 0; i < response.data.length; i++) {
select.append('<option value="'+response.data[i].id+'">'+response.data[i].name+'</option>')
}
});
}
};
$(function () {
BrizyCloud.init($('#cloud-form'));
});
});

View File

@@ -0,0 +1,137 @@
jQuery(document).ready(function ($) {
if (wp.hooks && wp.hooks.addFilter)
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'brizy/featuredImage',
function (originalElement) {
return function (origianalProps) {
var isDragging = false;
var el = wp.element.createElement;
var x = Brizy_Admin_Data.page.focalPoint.x;
var y = Brizy_Admin_Data.page.focalPoint.y;
if (!origianalProps.media) {
return el(originalElement, origianalProps);
}
var clickAndMouseMoveHandler = function ( e ) {
if ( ! isDragging && e.type !== 'click' ) {
return;
}
var $this = $(e.target);
var imageW = $this.width();
var imageH = $this.height();
var $focalPointX = $('#_thumbnail_focal_point_x');
var $focalPointY = $('#_thumbnail_focal_point_y');
var $focalPointDiv = $('#_thumbnail_focal_point_div');
$focalPointDiv.on('mouseup', function () {
isDragging = false;
});
if ( window.getSelection ) {
window.getSelection().removeAllRanges();
} else if ( document.selection ) {
document.selection.empty();
}
// Calculate FocusPoint coordinates
var offsetX = e.pageX - $this.offset().left;
var offsetY = e.pageY - $this.offset().top;
// Calculate CSS Percentages
var percentageX = (offsetX / imageW) * 100;
var percentageY = (offsetY / imageH) * 100;
// Set positioning
$focalPointDiv.css({
left: percentageX.toFixed(0) + '% ',
top: percentageY.toFixed(0) + '%'
});
$focalPointX.val(percentageX.toFixed(0));
$focalPointY.val(percentageY.toFixed(0));
wp.data.dispatch('core/editor').editPost({
'brizy_attachment_focal_point': {
x: percentageX.toFixed(0),
y: percentageY.toFixed(0)
}
});
};
return el('div', {class: 'brizy-featured-image hide-if-no-js'}, [
el('input', {
id: '_thumbnail_focal_point_x',
name: '_thumbnail_focal_point_x',
type: 'hidden',
value: Brizy_Admin_Data.page.focalPoint.x
}),
el('input', {
id: '_thumbnail_focal_point_y',
name: '_thumbnail_focal_point_y',
type: 'hidden',
value: Brizy_Admin_Data.page.focalPoint.y
}),
el('div',
{
class: 'wrapper',
onMouseLeave: function () {
isDragging = false;
}
}, [
el('img', {
id: 'featured-image-el',
src: origianalProps.media.source_url,
width: "100%",
onClick: clickAndMouseMoveHandler,
onMouseMove: clickAndMouseMoveHandler,
onMouseDown: function () {
isDragging = true;
},
onMouseUp: function () {
isDragging = false;
}
}),
el('div', {
class: 'focal-point',
id: '_thumbnail_focal_point_div',
style: {left: x + "%", top: y + "%"},
onMouseDown: function () {
isDragging = true;
}
}),
el('div', {class: 'deleteImage'}, [
el('a', {
id: 'remove-post-thumbnail', href: "#", onClick: function (e) {
origianalProps.onRemoveImage(e);
Brizy_Admin_Data.page.focalPoint.x = 50;
Brizy_Admin_Data.page.focalPoint.y = 50;
wp.data.dispatch('core/editor').editPost({
'brizy_attachment_focal_point': {
x: 50,
y: 50
}
});
}
},
[
el('svg', {class: 'brz-icon-svg'}, [
el('use', {'xlinkHref': Brizy_Admin_Data.pluginUrl + '/editor/icons/icons.svg#nc-circle-remove'}),
]),
]),
]),
]),
]);
}
}
);
});

View File

@@ -0,0 +1,2 @@
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(e.hyperapp={})}(this,function(e){"use strict";e.h=function(e,n){for(var t=[],r=[],o=arguments.length;2<o--;)t.push(arguments[o]);for(;t.length;){var u=t.pop();if(u&&u.pop)for(o=u.length;o--;)t.push(u[o]);else null!=u&&!0!==u&&!1!==u&&r.push(u)}return"function"==typeof e?e(n||{},r):{nodeName:e,attributes:n||{},children:r,key:n&&n.key}},e.app=function(e,n,t,r){var o,u=[].map,l=r&&r.children[0]||null,i=l&&function n(e){return{nodeName:e.nodeName.toLowerCase(),attributes:{},children:u.call(e.childNodes,function(e){return 3===e.nodeType?e.nodeValue:n(e)})}}(l),y=[],g=!0,f=b(e),a=function e(r,o,u){for(var n in u)"function"==typeof u[n]?function(e,t){u[e]=function(e){var n=t(e);return"function"==typeof n&&(n=n(v(r,f),u)),n&&n!==(o=v(r,f))&&!n.then&&s(f=d(r,b(o,n),f)),n}}(n,u[n]):e(r.concat(n),o[n]=b(o[n]),u[n]=b(u[n]));return u}([],f,b(n));return s(),a;function N(e){return"function"==typeof e?N(e(f,a)):null!=e?e:""}function c(){o=!o;var e=N(t);for(r&&!o&&(l=function e(n,t,r,o,u){if(o===r);else if(null==r||r.nodeName!==o.nodeName){var l=function e(n,t){var r="string"==typeof n||"number"==typeof n?document.createTextNode(n):(t=t||"svg"===n.nodeName)?document.createElementNS("http://www.w3.org/2000/svg",n.nodeName):document.createElement(n.nodeName),o=n.attributes;if(o){o.oncreate&&y.push(function(){o.oncreate(r)});for(var u=0;u<n.children.length;u++)r.appendChild(e(n.children[u]=N(n.children[u]),t));for(var l in o)w(r,l,o[l],null,t)}return r}(o,u);n.insertBefore(l,t),null!=r&&x(n,t,r),t=l}else if(null==r.nodeName)t.nodeValue=o;else{!function(e,n,t,r){for(var o in b(n,t))t[o]!==("value"===o||"checked"===o?e[o]:n[o])&&w(e,o,t[o],n[o],r);var u=g?t.oncreate:t.onupdate;u&&y.push(function(){u(e,n)})}(t,r.attributes,o.attributes,u=u||"svg"===o.nodeName);for(var i={},f={},a=[],c=r.children,s=o.children,d=0;d<c.length;d++){a[d]=t.childNodes[d];var v=k(c[d]);null!=v&&(i[v]=[a[d],c[d]])}for(var d=0,h=0;h<s.length;){var v=k(c[d]),p=k(s[h]=N(s[h]));if(f[v])d++;else if(null==p||p!==k(c[d+1]))if(null==p||g)null==v&&(e(t,a[d],c[d],s[h],u),h++),d++;else{var m=i[p]||[];v===p?(e(t,m[0],m[1],s[h],u),d++):m[0]?e(t,t.insertBefore(m[0],a[d]),m[1],s[h],u):e(t,a[d],null,s[h],u),f[p]=s[h],h++}else null==v&&x(t,a[d],c[d]),d++}for(;d<c.length;)null==k(c[d])&&x(t,a[d],c[d]),d++;for(var d in i)f[d]||x(t,i[d][0],i[d][1])}return t}(r,l,i,i=e)),g=!1;y.length;)y.pop()()}function s(){o||(o=!0,setTimeout(c))}function b(e,n){var t={};for(var r in e)t[r]=e[r];for(var r in n)t[r]=n[r];return t}function d(e,n,t){var r={};return e.length?(r[e[0]]=1<e.length?d(e.slice(1),n,t[e[0]]):n,b(t,r)):n}function v(e,n){for(var t=0;t<e.length;)n=n[e[t++]];return n}function k(e){return e?e.key:null}function h(e){return e.currentTarget.events[e.type](e)}function w(e,n,t,r,o){if("key"===n);else if("style"===n)for(var u in b(r,t)){var l=null==t||null==t[u]?"":t[u];"-"===u[0]?e[n].setProperty(u,l):e[n][u]=l}else"o"===n[0]&&"n"===n[1]?(n=n.slice(2),e.events?r||(r=e.events[n]):e.events={},(e.events[n]=t)?r||e.addEventListener(n,h):e.removeEventListener(n,h)):n in e&&"list"!==n&&"type"!==n&&"draggable"!==n&&"spellcheck"!==n&&"translate"!==n&&!o?e[n]=null==t?"":t:null!=t&&!1!==t&&e.setAttribute(n,t),null!=t&&!1!==t||e.removeAttribute(n)}function x(e,n,t){function r(){e.removeChild(function e(n,t){var r=t.attributes;if(r){for(var o=0;o<t.children.length;o++)e(n.childNodes[o],t.children[o]);r.ondestroy&&r.ondestroy(n)}return n}(n,t))}var o=t.attributes&&t.attributes.onremove;o?o(n,r):r()}}});
//# sourceMappingURL=hyperapp.js.map

Some files were not shown because too many files have changed in this diff Show More