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,157 @@
<?php
class Brizy_Editor_Accounts_AbstractAccountManager {
/**
* @var Brizy_Editor_Project
*/
private $project;
/**
* @var Brizy_Editor_Accounts_Account[]
*/
private $accounts;
/**
* Brizy_Editor_Accounts_AbstractAccountManager constructor.
*
* @param $class
* @param Brizy_Editor_Project $project
*/
public function __construct( $class, Brizy_Editor_Project $project ) {
$this->project = $project;
try {
$this->loadAccounts( $class, $project );
} catch ( Exception $exception ) {
$this->accounts = array();
}
}
public function getAllAccounts() {
return $this->accounts;
}
/**
* @param $service
* @param $accountId
*
* @return Brizy_Editor_Accounts_Account[]|null
*/
public function getAccounts( $service ) {
if ( isset( $this->accounts[ $service ] ) ) {
return array_values( $this->accounts[ $service ] );
}
return array();
}
/**
* @param $service
* @param $accountId
*
* @return Brizy_Editor_Accounts_Account|null
*/
public function getAccount( $service, $accountId ) {
return $this->accounts[ $service ][ $accountId ];
}
/**
* @param $service
* @param Brizy_Editor_Accounts_Account $anAccount
*
* @return bool
*/
public function hasAccount( $service, Brizy_Editor_Accounts_Account $anAccount ) {
foreach ( $this->getAccounts( $service ) as $account ) {
if ( $anAccount->isEqual( $account ) ) {
return true;
}
}
return false;
}
/**
* @param $service
* @param Brizy_Editor_Accounts_Account $account
*/
public function addAccount( $service, Brizy_Editor_Accounts_Account $account ) {
if ( $this->hasAccount( $service, $account ) ) {
return;
}
$this->accounts[ $service ][ $account->getId() ] = $account;
$this->updateStorage();
}
/**
* @param $service
* @param Brizy_Editor_Accounts_Account $account
*/
public function deleteAccount( $service, Brizy_Editor_Accounts_Account $account ) {
unset( $this->accounts[ $service ][ $account->getId() ] );
$this->updateStorage();
}
/**
* @param $service
* @param $accountId
*/
public function deleteAccountById( $service, $accountId ) {
unset( $this->accounts[ $service ][ $accountId ] );
$this->updateStorage();
}
/**
*
*/
private function updateStorage() {
$data = array();
foreach ( $this->accounts as $service => $accounts ) {
foreach ( $accounts as $account ) {
$data[ $service ][] = $account->convertToOptionValue();
}
}
$this->project->setAccounts( $data );
$this->project->saveStorage();
}
/**
* @param $class
* @param Brizy_Editor_Project $project
*
* @throws Brizy_Editor_Exceptions_NotFound
*/
private function loadAccounts( $class, Brizy_Editor_Project $project ) {
//$this->project->setMetaValue( 'accounts', [] );
$meta_value = $project->getMetaValue( 'accounts' );
if ( is_array( $meta_value ) ) {
foreach ( $meta_value as $service => $accounts ) {
foreach ( $accounts as $account ) {
$account1 = Brizy_Editor_Accounts_Account::createFromSerializedData( $account );
if ( $this->hasAccount( $service, $account1 ) ) {
continue;
}
$this->accounts[ $service ][ $account1->getId() ] = $account1;
}
}
}
}
}

View File

@@ -0,0 +1,178 @@
<?php
abstract class Brizy_Editor_Accounts_AbstractAccount extends Brizy_Admin_Serializable {
const INTEGRATIONS_GROUP = 'form-integration';
const RECAPTCHA_GROUP = 'recaptcha';
const SOCIAL_GROUP = 'social';
use Brizy_Editor_Forms_DynamicPropsAware;
/**
* This will group the accounts
* ex: form-integration,
* recaptcha
* other implementations
*
*
* @return string
*/
abstract public function getGroup();
/**
* This will return the service name for this account:
* ex: facebook, twitter, linkedin....
*
* @return mixed
*/
abstract public function getService();
/**
* Brizy_Editor_Accounts_Account constructor.
*
* @param null $data
*/
public function __construct( $data = null ) {
if ( is_array( $data ) ) {
foreach ( $data as $key => $val ) {
$this->set( $key, $val );
}
} else {
$this->data = array();
}
if ( ! isset( $data['id'] ) ) {
$this->set( 'id', md5( time() . rand( 0, 10000 ) ) );
}
$this->set( 'group', $this->getGroup() );
}
/**
* @param self $account
*
* @return bool
*/
public function isEqual( self $account ) {
$aData = $account->convertToOptionValue();
foreach ( $this->data as $key => $val ) {
if ( $key == 'id' ) {
continue;
}
if ( ! isset( $aData[ $key ] ) || $aData[ $key ] != $val ) {
return false;
}
}
return true;
}
/**
* @return array|null
*/
public function convertToAuthData() {
$data = $this->data;
unset( $data['id'] );
unset( $data['group'] );
unset( $data['service'] );
return $data;
}
/**
* @param string[] $data
*
* @return Brizy_Editor_Accounts_AbstractAccount
*/
public function setData( $data ) {
$this->data = $data;
return $this;
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->jsonSerialize() );
}
/**
* @param $serialized
*/
public function unserialize( $serialized ) {
$this->data = unserialize( $serialized );
}
/**
* @return array|mixed|null
*/
public function jsonSerialize() {
return $this->data;
}
/**
* @return array|null
*/
public function convertToOptionValue() {
return $this->data;
}
/**
* @param $data
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
static public function createFromSerializedData( $data ) {
if ( isset( $data['group'] ) )
switch ( $data['group'] ) {
default:
case self::INTEGRATIONS_GROUP:
return new Brizy_Editor_Accounts_Account( $data );
case self::SOCIAL_GROUP:
return new Brizy_Editor_Accounts_SocialAccount( $data );
case self::RECAPTCHA_GROUP:
return new Brizy_Editor_Accounts_RecaptchaAccount( $data );
}
throw new Exception( 'Invalid account group.' );
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception`
*/
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
return self::createFromSerializedData( get_object_vars( $json_obj ) );
}
throw new Exception( 'Invalid json provided.' );
}
/**
* Some accounts may need advanced validation
*
* Ex: a request to an external api may be needed
*
* @return bool
*/
public function validate() {
return true;
}
}

View File

@@ -0,0 +1,53 @@
<?php
class Brizy_Editor_Accounts_Account extends Brizy_Editor_Accounts_AbstractAccount {
/**
* @return mixed
*/
public function getGroup() {
return Brizy_Editor_Accounts_AbstractAccount::INTEGRATIONS_GROUP;
}
/**
* @return mixed
*/
public function getService() {
return $this->data['service'];
}
/**
* @param $data
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
static public function createFromSerializedData( $data ) {
$data['group'] = Brizy_Editor_Accounts_AbstractAccount::INTEGRATIONS_GROUP;
return Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( $data );
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
return Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( get_object_vars( $json_obj ) );
}
throw new Exception( 'Invalid json provided.' );
}
}

View File

@@ -0,0 +1,156 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 2/7/19
* Time: 10:13 AM
*/
class Brizy_Editor_Accounts_Api extends Brizy_Admin_AbstractApi {
const nonce = 'brizy-api';
const BRIZY_GET_ACCOUNT = '_get_account';
const BRIZY_GET_ACCOUNTS = '_get_accounts';
const BRIZY_ADD_ACCOUNT = '_add_account';
const BRIZY_UPDATE_ACCOUNT = '_update_account';
const BRIZY_DELETE_ACCOUNT = '_delete_account';
/**
* @var Brizy_Editor_Accounts_ServiceAccountManager
*/
private $manager;
/**
* Brizy_Admin_Rules_Api constructor.
*
* @param Brizy_Editor_Accounts_ServiceAccountManager $manager
*/
public function __construct( $manager ) {
$this->manager = $manager;
parent::__construct();
}
/**
* @return Brizy_Editor_Accounts_Api
* @throws Exception
*/
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self( new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() ) );
}
return $instance;
}
/***
* @return null
*/
protected function getRequestNonce() {
return $this->param( 'hash' );
}
/**
* Register all api actions
*/
protected function initializeApiActions() {
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
add_action( $pref . self::BRIZY_GET_ACCOUNT, array( $this, 'actionGetAccount' ) );
add_action( $pref . self::BRIZY_GET_ACCOUNTS, array( $this, 'actionGetAccounts' ) );
add_action( $pref . self::BRIZY_ADD_ACCOUNT, array( $this, 'actionAddAccount' ) );
add_action( $pref . self::BRIZY_UPDATE_ACCOUNT, array( $this, 'actionUpdateAccount' ) );
add_action( $pref . self::BRIZY_DELETE_ACCOUNT, array( $this, 'actionDeleteAccount' ) );
}
public function actionGetAccount() {
$this->verifyNonce( self::nonce );
if ( ! $this->param( 'id' ) ) {
$this->error( 400, 'Invalid account id' );
}
try {
$manager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() );
$account = $manager->getAccount( $this->param( 'id' ) );
if ( ! $account ) {
$this->error( 404, 'Account not found' );
}
$this->success( $account );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( $e->getMessage(), array( $e ) );
$this->error( 500, $e->getMessage() );
}
}
public function actionGetAccounts() {
$this->verifyNonce( self::nonce );
$filter = array();
if ( $this->param( 'group' ) ) {
$filter['group'] = $this->param( 'group' );
}
if ( $this->param( 'service' ) ) {
$filter['service'] = $this->param( 'service' );
}
try {
$manager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() );
$accounts = $manager->getFilteredAccounts( $filter );
$this->success( $accounts );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( $e->getMessage(), array( $e ) );
$this->error( 500, $e->getMessage() );
}
}
public function actionAddAccount() {
$this->verifyNonce( self::nonce );
try {
$manager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() );
$instance = Brizy_Editor_Accounts_AbstractAccount::createFromJson( json_decode( file_get_contents( 'php://input' ) ) );
$instance->validate();
$manager->addAccount( $instance );
$this->success( $instance );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( $e->getMessage(), array( $e ) );
$this->error( 500, $e->getMessage() );
}
}
public function actionUpdateAccount() {
$this->verifyNonce( self::nonce );
try {
$manager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() );
$instance = Brizy_Editor_Accounts_AbstractAccount::createFromJson( json_decode( file_get_contents( 'php://input' ) ) );
$manager->updateAccount( $instance );
$this->success( $instance );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( $e->getMessage(), array( $e ) );
$this->error( 500, $e->getMessage() );
}
}
public function actionDeleteAccount() {
$this->verifyNonce( self::nonce );
try {
if ( ! $this->param( 'id' ) ) {
$this->error( 400, 'Invalid account id' );
}
$manager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() );
$manager->deleteAccountById( $this->param( 'id' ) );
$this->success( null );
} catch ( Exception $e ) {
Brizy_Logger::instance()->critical( $e->getMessage(), array( $e ) );
$this->error( 500, $e->getMessage() );
}
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 11/26/18
* Time: 5:00 PM
*/
class Brizy_Editor_Accounts_RecaptchaAccount extends Brizy_Editor_Accounts_AbstractAccount {
const SERVICE_NAME = 'recaptcha';
/**
* @return mixed
*/
public function getGroup() {
return Brizy_Editor_Accounts_AbstractAccount::RECAPTCHA_GROUP;
}
/**
* @return mixed
*/
public function getService() {
return self::SERVICE_NAME;
}
/**
* @param $data
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
static public function createFromSerializedData( $data ) {
$data['group'] = Brizy_Editor_Accounts_AbstractAccount::RECAPTCHA_GROUP;
$data['service'] = self::SERVICE_NAME;
return Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( $data );
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
$json_obj->group = Brizy_Editor_Accounts_AbstractAccount::RECAPTCHA_GROUP;
$json_obj->service = self::SERVICE_NAME;
return Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( get_object_vars( $json_obj ) );
}
throw new Exception( 'Invalid json provided.' );
}
public function getSiteKey() {
return $this->get( 'sitekey' );
}
/**
* @throws Exception
*/
public function validate() {
if ( ! isset( $_REQUEST['secretkey'] ) ) {
throw new Exception( 'Invalid secret provided' );
}
if ( ! isset( $_REQUEST['response'] ) ) {
throw new Exception( 'Invalid response provided' );
}
$http = new WP_Http();
$response = $http->post( 'https://www.google.com/recaptcha/api/siteverify', array(
'body' => array(
'secret' => $_REQUEST['secretkey'],
'response' => $_REQUEST['response']
)
) );
$body = wp_remote_retrieve_body( $response );
$responseJsonObject = json_decode( $body );
if ( ! is_object( $responseJsonObject ) || ! $responseJsonObject->success ) {
throw new Exception( "Unable to validate account" );
}
return true;
}
}

View File

@@ -0,0 +1,194 @@
<?php
class Brizy_Editor_Accounts_ServiceAccountManager {
/**
* @var Brizy_Editor_Project
*/
private $project;
/**
* @var Brizy_Editor_Accounts_Account[]
*/
private $accounts;
/**
* Brizy_Editor_Forms_Manager constructor.
*
* @param Brizy_Editor_Project $project
*/
public function __construct( Brizy_Editor_Project $project ) {
$this->accounts = array();
$this->project = $project;
try {
$this->loadAccounts( $project );
} catch ( Exception $exception ) {
$this->accounts = array();
}
}
public function getAllAccounts() {
return $this->accounts;
}
public function getFilteredAccounts( $filter ) {
$accounts = array();
foreach ( $this->getAllAccounts() as $account ) {
if ( isset( $filter['service'] ) && $filter['service'] != $account->getService() ) {
continue;
}
if ( isset( $filter['group'] ) && $filter['group'] != $account->getGroup() ) {
continue;
}
$accounts[] = $account;
}
return $accounts;
}
/**
* @param $group
*
* @return array
*/
public function getAccountsByGroup( $group ) {
return $this->getFilteredAccounts( array( 'group' => $group ) );
}
/**
* @param $service
*
* @return array
*/
public function getAccountsByService( $service ) {
return $this->getFilteredAccounts( array( 'service' => $service ) );
}
/**
* @param $accountId
*
* @return Brizy_Editor_Accounts_Account|mixed
*/
public function getAccount( $accountId ) {
foreach ( $this->accounts as $key => $account ) {
if ( $account->getId() == $accountId ) {
return $account;
}
}
}
/**
* @param Brizy_Editor_Accounts_AbstractAccount $anAccount
*
* @return bool
*/
public function hasAccount( Brizy_Editor_Accounts_AbstractAccount $anAccount ) {
foreach ( $this->getAllAccounts() as $account ) {
if ( $anAccount->isEqual( $account ) ) {
return true;
}
}
return false;
}
/**
* @param Brizy_Editor_Accounts_AbstractAccount $account
*/
public function addAccount( Brizy_Editor_Accounts_AbstractAccount $account ) {
if ( $this->hasAccount( $account ) ) {
return;
}
$this->accounts[] = $account;
$this->updateStorage();
}
/**
* @param Brizy_Editor_Accounts_AbstractAccount $anAccount
*/
public function updateAccount( Brizy_Editor_Accounts_AbstractAccount $anAccount ) {
foreach ( $this->getAllAccounts() as $index => $account ) {
if ( $account->getId() == $anAccount->getId() ) {
$this->accounts[ $index ] = $anAccount;
break;
}
}
$this->updateStorage();
}
/**
* @param Brizy_Editor_Accounts_AbstractAccount $account
*/
public function deleteAccount( Brizy_Editor_Accounts_AbstractAccount $account ) {
$this->deleteAccountById( $account->getId() );
}
/**
* @param $accountId
*/
public function deleteAccountById( $accountId ) {
foreach ( $this->getAllAccounts() as $key => $account ) {
if ( $account->getId() == $accountId ) {
unset( $this->accounts[ $key ] );
break;
}
}
$this->accounts = array_values( $this->accounts );
$this->updateStorage();
}
/**
*
*/
private function updateStorage() {
$data = array();
foreach ( $this->getAllAccounts() as $account ) {
$data[] = $account->convertToOptionValue();
}
$this->project->setAccounts( $data );
$this->project->saveStorage();
}
/**
* @param Brizy_Editor_Project $project
*
* @throws Brizy_Editor_Exceptions_NotFound
*/
private function loadAccounts( Brizy_Editor_Project $project ) {
$meta_value = $project->getMetaValue( 'accounts' );
if ( is_array( $meta_value ) ) {
foreach ( $meta_value as $account ) {
try {
$anAccount = Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( $account );
if ( $this->hasAccount( $anAccount ) ) {
continue;
}
$this->accounts[] = $anAccount;
} catch ( Exception $e ) {
continue;
}
}
}
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 11/26/18
* Time: 5:00 PM
*/
class Brizy_Editor_Accounts_SocialAccount extends Brizy_Editor_Accounts_Account {
/**
* @return mixed
*/
public function getGroup() {
return Brizy_Editor_Accounts_AbstractAccount::SOCIAL_GROUP;
}
/**
* @param $data
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
static public function createFromSerializedData( $data ) {
$data['group'] = Brizy_Editor_Accounts_AbstractAccount::SOCIAL_GROUP;
return Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( $data );
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Accounts_AbstractAccount
* @throws Exception
*/
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
$json_obj->group = Brizy_Editor_Accounts_AbstractAccount::SOCIAL_GROUP;
return Brizy_Editor_Accounts_AbstractAccount::createFromSerializedData( get_object_vars( $json_obj ) );
}
throw new Exception( 'Invalid json provided.' );
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,102 @@
<?php
class Brizy_Editor_API_AccessToken extends Brizy_Admin_Serializable {
/**
* @var string $token
*/
private $token;
/**
* @var string $token
*/
private $refresh_token;
/**
* @var int $token
*/
private $expires;
/**
* Brizy_API_Access_Token constructor.
*
* @param string $token
* @param int $expires
*/
public function __construct( $token, $expires ) {
$this->token = $token;
$this->expires = (int) $expires;
}
public function convertToOptionValue() {
return array(
'token' => $this->token,
'refresh_token' => $this->refresh_token,
'expires' => $this->expires
);
}
static public function createFromSerializedData( $data ) {
$instance = new self( $data['token'], $data['expires'] );
$instance->refresh_token = $data['refresh_token'];
return $instance;
}
public function access_token() {
return $this->token;
}
public function get_expires() {
return $this->expires;
}
public function expired() {
return time() >= $this->get_expires();
}
/**
* @return string
*/
public function get_refresh_token() {
return $this->refresh_token;
}
/**
* @param $refresh_token
*
* @return $this
*/
public function set_refresh_token( $refresh_token ) {
$this->refresh_token = $refresh_token;
return $this;
}
public function export() {
return array(
'access_token' => $this->access_token(),
'expires' => $this->get_expires(),
);
}
public function serialize() {
return serialize( array(
'token' => $this->token,
'refresh_token' => $this->refresh_token,
'expires' => $this->expires,
) );
}
public function unserialize( $data ) {
$vars = unserialize( $data );
foreach ( $vars as $prop => $value ) {
$this->$prop = $value;
}
}
}

View File

@@ -0,0 +1,90 @@
<?php
class Brizy_Editor_API_Auth extends Brizy_Editor_Http_Client {
/**
* @var string
*/
private $gateway_url;
/**
* @var string
*/
private $client_id;
/**
* @var string
*/
private $secret;
public function __construct( $gateway_url, $client_id, $secret ) {
parent::__construct();
$this->gateway_url = $gateway_url;
$this->client_id = $client_id;
$this->secret = $secret;
}
public function auth_url() {
return $this->gateway_url . '/oauth/token';
}
public function refresh_url() {
return $this->gateway_url . '/oauth/refresh';
}
/**
* @param $email
*
* @return Brizy_Editor_API_AccessToken
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function getToken( $email ) {
$token = get_option( $this->get_meta_id(), null );
if ( $token instanceof Brizy_Editor_API_AccessToken) {
if ( ! $token->expired() ) {
return $token;
} else {
$this->clearTokenCache();
}
}
$response = $this->post( $this->auth_url(),
array(
'body' => array(
'client_id' => $this->client_id,
'client_secret' => $this->secret,
'email' => $email,
'grant_type' => 'https://visual.dev/api/extended_client_credentials'
),
'sslverify' => false
)
)->get_response_body();
$brizy_editor_API_access_token = new Brizy_Editor_API_AccessToken( $response['access_token'], $response['expires_in'] + time() - 20 );
if ( isset( $response['refresh_token'] ) ) {
$brizy_editor_API_access_token->set_refresh_token( $response['refresh_token'] );
}
add_option( $this->get_meta_id(), $brizy_editor_API_access_token );
return $brizy_editor_API_access_token;
}
public function clearTokenCache() {
delete_option( $this->get_meta_id() );
}
private function get_meta_id() {
return "brizy_" . md5( $this->client_id );
}
}

View File

@@ -0,0 +1,363 @@
<?php
class Brizy_Editor_API_Client extends Brizy_Editor_Http_Client
{
/**
* @var Brizy_Editor_API_AccessToken
*/
private $access_token;
/**
* Brizy_Editor_API_Client constructor.
*
* @param $token
*/
public function __construct($token)
{
parent::__construct();
$this->access_token = $token;
}
public function getUser()
{
return $this->post('users/me', array())->get_response_body();
}
/**
* @param null $clone_from_id
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function create_project($clone_from_id = null)
{
$project = new Brizy_Editor_API_Project(array());
$save_data = $project->getSaveData();
if ($clone_from_id) {
$save_data['resource_id_clonable'] = $clone_from_id;
}
return $this->post('projects', array('body' => $save_data))->get_response_body();
}
/**
* @param $page_ids
* @param $project_target
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function clone_pages( $page_ids, $project_target ) {
//
// return $this->post( 'pages/clones', array(
// 'body' => array(
// 'project' => $project_target,
// 'pages' => $page_ids
// )
// ) )->get_response_body();
// }
/**
* @param Brizy_Editor_API_Project $project
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function get_project(Brizy_Editor_API_Project $project)
{
return $this->get("projects/{$project->get_id()}")->get_response_body();
}
/**
* @param Brizy_Editor_API_Project $project
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function update_project(Brizy_Editor_API_Project $project)
{
return $this->put(
"projects/{$project->get_id()}",
array('body' => $project->getSaveData('PUT'))
)->get_response_body();
}
/**
* @param $id
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function delete_project($id)
{
return $this->delete("projects/$id")->get_response_body();
}
/**
* @param $project_id
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function get_pages( $project_id ) {
// return $this->get( "projects/$project_id/pages?=signature=" . Brizy_Editor_Signature::get() )->get_response_body();
// }
/**
* @param $project_id
* @param $page_id
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function get_page( $project_id, $page_id ) {
// return $this->get( "projects/$project_id/pages/$page_id" )->get_response_body();
// }
/**
* @param $project_id
* @param Brizy_Editor_API_Page $page
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function create_page( $project_id, Brizy_Editor_API_Page $page ) {
// return $this->post( "projects/$project_id/pages", array( 'body' => $page->getSaveData() ) )->get_response_body();
// }
/**
* @param $project_id
* @param $page_id
* @param Brizy_Editor_API_Page $page
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function update_page( $project_id, $page_id, Brizy_Editor_API_Page $page ) {
// return $this->put( "projects/$project_id/pages/$page_id", array( 'body' => $page->getSaveData( 'PUT' ) ) )->get_response_body();
// }
/**
* @param Brizy_Editor_Project $project
* @param $page_data
* @param $config
* @param $compiler_url
*
* @return array
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Exceptions_NotFound
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
* @throws Twig_Error_Loader
* @throws Twig_Error_Runtime
* @throws Twig_Error_Syntax
*/
public function compile_page(Brizy_Editor_Project $project, $page_data, $config, $compiler_url)
{
$blockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL);
$body = apply_filters(
'brizy_compiler_params',
array(
'page_id' => (int)$config['wp']['page'],
'free_version' => BRIZY_EDITOR_VERSION,
'free_url' => Brizy_Config::getCompilerDownloadUrl(),
'config_json' => json_encode($config),
'pages_json' => json_encode(
array(
array(
'id' => (int)$config['wp']['page'],
'data' => $page_data,
'is_index' => true,
),
)
),
'project_json' => json_encode($project->createResponse()),
'global_blocks_json' => json_encode(
$blockManager->createResponseForEntities($blockManager->getEntities([]))
),
)
);
$page = parent::request($compiler_url, array('body' => $body), 'POST')->get_response_body();
$template_context = array(
'editorData' => array(
'urls' => array(
'assets' => $config['urls']['assets'],
'apiEndpoint' => set_url_scheme(admin_url('admin-ajax.php')),
),
'api' => array(
'getTimestamp' => Brizy_Editor_API::AJAX_TIMESTAMP,
),
'serverTimestamp' => time(),
),
'page' => $page,
);
$blocks = $page['blocks'];
return [
'pageHtml' => Brizy_TwigEngine::instance(Brizy_Editor_UrlBuilder::editor_build_path('editor/views/'))
->render('static.html.twig', $template_context),
'pageScripts' => [
'free' => $blocks['freeScripts'],
'pro' => (isset($blocks['proScripts']) ? $blocks['proScripts'] : []),
],
'pageStyles' => [
'free' => $blocks['freeStyles'],
'pro' => (isset($blocks['proStyles']) ? $blocks['proStyles'] : []),
],
];
}
/**
* @param $project_id
* @param $page_id
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function delete_page( $project_id, $page_id ) {
// return $this->delete( "projects/$project_id/pages/$page_id" )->get_response_body();
// }
/**
* @param $project_id
* @param $base64
*
* @return array|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function add_media($project_id, $base64)
{
return $this->post(
"projects/$project_id/media",
array(
'timeout' => 30,
'body' => array('attachment' => $base64),
)
)->get_response_body();
}
/**
* @return array
*/
protected function get_headers()
{
return array(//'Authorization' => 'Bearer ' . $this->access_token->access_token()
);
}
/**
* @param $suffix
*
* @return string
*/
protected function url($suffix)
{
$implode = rtrim(implode("/", array(Brizy_Config::GATEWAY_URI, 'v1', $suffix)), "/");
return $implode;
}
/**
* @param $url
* @param array $options
* @param string $method
*
* @return Brizy_Editor_Http_Response
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function request($url, $options = array(), $method = 'GET')
{
return parent::request(
$this->url($url),
$options,
$method
);
}
/**
* @param $options
*
* @return array
*/
protected function prepare_options($options)
{
$options = parent::prepare_options($options);
$options['headers'] = array_merge($options['headers'], $this->get_headers());
return $options;
}
protected function get_project_json(Brizy_Editor_Project $project)
{
return json_encode(
array(
'id' => $project->getId(),
'data' => $project->getDataAsJson(),
)
);
}
}

View File

@@ -0,0 +1,4 @@
<?php
class Brizy_Editor_API_Exceptions_Exception extends Exception {
}

View File

@@ -0,0 +1,141 @@
<?php
/**
*
* @deprecated
*
* Class Brizy_Editor_API_Page
*/
class Brizy_Editor_API_Page extends Brizy_Admin_Serializable {
/**
* @var array
*/
private $data;
/**
* @param array $data
*
* @return Brizy_Editor_API_Page
*/
public static function get( $data = array() ) {
return new self( $data );
}
public function convertToOptionValue() {
return array(
'data' => $this->data
);
}
static public function createFromSerializedData( $data ) {
$page = new self( $data['data'] );
return $page;
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->data );
}
/**
* @param $data
*/
public function unserialize( $data ) {
$this->data = unserialize( $data );
}
/**
* Brizy_Editor_API_Page constructor.
*
* @param array $data
*/
public function __construct( $data = array() ) {
$default = array( 'title' => 'Default title', 'data' => '{}' );
$this->data = array_merge( $default, $data );
}
public function get_id() {
return isset( $this->data['id'] ) ? $this->data['id'] : '';
}
public function set_id( $id ) {
$this->data['id'] = $id;
return $this;
}
public function get_title() {
return isset( $this->data['title'] ) ? $this->data['title'] : '';
}
public function set_title( $title ) {
$this->data['title'] = $title;
return $this;
}
// public function get_status() {
// return isset( $this->data['status'] ) ? $this->data['status'] : '';
// }
//
// public function set_status( $status ) {
// //$this->data['status'] = $status;
//
// return $this;
// }
public function get_content() {
return isset( $this->data['data'] ) ? $this->data['data'] : '';
}
public function set_content( $content ) {
$this->data['data'] = stripslashes( $content );
return $this;
}
public function get_language() {
return isset( $this->data['language'] ) ? $this->data['language'] : null;
}
public function get_type() {
return isset( $this->data['type'] ) ? $this->data['type'] : null;
}
public function get_url() {
return isset( $this->data['url'] ) ? $this->data['url'] : '';
}
public function get_description() {
return isset( $this->data['description'] ) ? $this->data['description'] : '';
}
public function set_description( $data ) {
$data['description'] = $data;
return $this;
}
public function is_index() {
return isset( $this->data['is_index'] ) ? (bool) $this->data['is_index'] : true;
}
public function set_is_index( $is_index ) {
$this->data['is_index'] = $is_index;
return $this;
}
public function getSaveData() {
$data = $this->data;
return array_diff_key( $data, array( 'id' => 0, 'cloned_from' => null ) );
}
}

View File

@@ -0,0 +1,208 @@
<?php
class Brizy_Editor_API_Platform extends Brizy_Editor_Http_Client {
/**
* @var string
*/
private $client_id;
/**
* @var string
*/
private $secret;
/**
* @var string
*/
private $email;
private function sign_up_url() {
return Brizy_Config::GATEWAY_URI . '/v1/users';
}
private function auth_url() {
return Brizy_Config::GATEWAY_URI . '/oauth/token';
}
/**
* Brizy_Editor_API_Platform constructor.
*/
public function __construct() {
parent::__construct();
$credentials = self::getCredentials();
$this->client_id = $credentials->client_id;
$this->secret = $credentials->client_secret;
$this->email = $credentials->email;
}
/**
* @return Brizy_Editor_API_AccessToken
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// private function getToken() {
//
// Brizy_Logger::instance()->notice( 'Getting token to create the user' );
//
// $body = array(
// 'client_id' => $this->client_id,
// 'client_secret' => $this->secret,
// 'email' => $this->email,
// 'grant_type' => 'https://visual.dev/api/limited_client_credentials'
// );
//
// $response = $this->post( $this->auth_url(), array(
// 'body' => $body
// ) );
//
// $response_array = $response->get_response_body();
//
// $brizy_editor_API_access_token = new Brizy_Editor_API_AccessToken(
// $response_array['access_token'],
// time() + $response_array['expires_in']
// );
//
//
// if ( isset( $response_array['refresh_token'] ) ) {
// $brizy_editor_API_access_token->set_refresh_token( $response_array['refresh_token'] );
// }
//
// return $brizy_editor_API_access_token;
// }
/**
* @return array|mixed|null|object
* @throws Exception
*/
static public function getCredentials() {
return (object) array(
"client_id" => Brizy_Config::PLATFORM_CLIENT_ID,
"client_secret" => Brizy_Config::PLATFORM_CLIENT_SECRET,
"email" => Brizy_Config::PLATFORM_EMAIL
);
}
/**
* @return string
*/
// protected function random_email() {
// $uniqid = 'brizy-' . md5( uniqid( '', true ) );
// return $uniqid . '@brizy.io';
// }
/**
* @param null $clone_id
* @param bool $is_local
*
* @return array|bool|mixed|object
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
// public function createUser( $clone_id = null, $is_local = true ) {
//
// $email = $this->random_email();
//
// if ( $is_local ) {
//
// Brizy_Logger::instance()->notice( 'New user created' );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_local', true );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_id', uniqid( 'user', true ) );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_email', $email );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_signature', Brizy_Editor_Signature::get() );
//
// return Brizy_Editor_User::reload();
// }
//
// $token = $this->getToken();
//
// Brizy_Logger::instance()->notice( 'Create new user', array( 'clone_id' => $clone_id ) );
//
// $options = array(
// 'headers' => array(
// 'Authorization' => 'Bearer ' . $token->access_token()
// ),
// 'body' => array(
// 'email' => $email,
// 'signature' => Brizy_Editor_Signature::get()
// ),
// 'sslverify' => false
// );
//
// if ( $clone_id ) {
// $options['body']['resource_id_clonable'] = $clone_id;
// }
//
// $response = $this->post( $this->sign_up_url(), $options );
//
// $user = $response->get_response_body();
//
// if ( $response->is_ok() ) {
//
// Brizy_Logger::instance()->notice( 'New user created', array( $user ) );
// Brizy_Editor_Storage_Common::instance()->delete( 'platform_user_local' );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_id', $user['id'] );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_email', $email );
// Brizy_Editor_Storage_Common::instance()->set( 'platform_user_signature', Brizy_Editor_Signature::get() );
//
// $user = Brizy_Editor_User::reload();
//
// // try to create the local project on platform
// try {
// $local_project = Brizy_Editor_Project::get();
//
// $api_project = $user->create_project( null, false );
// $api_project->set_globals( $local_project->get_globals() );
//
// $local_project->updateProjectData( $api_project );
// $local_project->save();
//
// $user->update_project( $api_project );
//
// return $user;
// } catch ( Exception $e ) {
// Brizy_Logger::instance()->error( 'Unable to create the project for remote user', array( $response ) );
// }
// }
//
// Brizy_Logger::instance()->error( 'Failed to create user', array( $response ) );
//
// return null;
// }
public function isUserCreatedLocally() {
return Brizy_Editor_Storage_Common::instance()->get( 'platform_user_local', false ) === true;
}
/**
* @param $data
*
* @throws Exception
*/
public function notifyFormSubmit( $data ) {
$urlBuilder = new Brizy_Editor_UrlBuilder( Brizy_Editor_Project::get() );
$urls = $urlBuilder->application_form_notification_url();
$response = $this->post( $urls, $data );
if ( ! $response->is_ok() ) {
Brizy_Logger::instance()->error( 'Failed to notify the platform about a form submit', array( 'response' => $response ) );
}
}
}

View File

@@ -0,0 +1,116 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_API_Project extends Brizy_Admin_Serializable {
private $data;
public function __construct( $data ) {
$defaults = array( 'title' => '', 'globals' => array() );
$this->data = array_merge( $defaults, is_array( $data ) ? $data : array() );
}
public function serialize() {
return serialize( $this->data );
}
public function unserialize( $data ) {
$this->data = unserialize( $data );
}
public function convertToOptionValue() {
return array(
'data' => serialize( $this->data )
);
}
static public function createFromSerializedData( $data ) {
$api_project = new self( $data );
return $api_project;
}
public function get_data() {
return $this->data;
}
public function get_id() {
return $this->data['id'];
}
public function set_id( $id ) {
return $this->data['id'] = $id;
}
public function get_globals() {
if ( base64_encode( base64_decode( $this->data['globals'], true ) ) === $this->data['globals'] ) {
return json_decode( base64_decode( $this->data['globals'], true ) );
}
return json_decode( $this->data['globals'] );
}
public function get_globals_as_json() {
return $this->data['globals'];
}
public function set_globals( $globals ) {
return $this->data['globals'] = base64_encode( json_encode( $globals ) );
}
public function set_globals_as_json( $globals ) {
return $this->data['globals'] = base64_encode( $globals );
}
/**
* @return string
*/
public function get_template_slug() {
$data = $this->get_data();
return $data['template']['slug'];
}
/**
* @return string
*/
public function get_template_version() {
$data = $this->get_data();
return $data['version'];
}
/**
* @param $version
*
* @return $this
*/
public function set_template_version( $version ) {
$this->data['version'] = $version;
return $this;
}
public function set_meta_key( $key, $value ) {
if ( is_null( $key ) ) {
throw new InvalidArgumentException( 'Hte key parameter should not be null' );
}
$this->data['meta_data'][ $key ] = $value;
}
public function getSaveData( $method = 'POST' ) {
$data = array(
'globals' => $this->get_globals_as_json(),
);
if ( $method == 'POST' ) {
$data['signature'] = Brizy_Editor_Signature::get();
}
return $data;
}
}

View File

@@ -0,0 +1,29 @@
<?php
abstract class Brizy_Editor_Asset_AbstractStorage extends Brizy_Editor_Asset_StaticFile {
/**
* @var Brizy_Editor_UrlBuilder
*/
protected $url_builder;
/**
* Brizy_Editor_Asset_AbstractStorage constructor.
*
* @param $url_builder
*/
public function __construct( $url_builder ) {
$this->url_builder = $url_builder;
}
/**
* Get the asset and store it somewhere in uploads and return the new local url.
*
* @param $asset_url
*
* @return mixed
*/
abstract public function store( $asset_url );
}

View File

@@ -0,0 +1,61 @@
<?php
class Brizy_Editor_Asset_AssetProxyProcessor implements Brizy_Editor_Content_ProcessorInterface {
/**
* @var Brizy_Editor_Asset_Storage
*/
private $storage;
/**
* Brizy_Editor_Asset_HtmlAssetProcessor constructor.
*
* @param Brizy_Editor_Asset_AbstractStorage $storage
*/
public function __construct( $storage ) {
$this->storage = $storage;
}
/**
* @param string $content
* @param Brizy_Content_Context $context
*
* @return mixed|string
*/
public function process( $content, Brizy_Content_Context $context ) {
preg_match_all( '/"(.[^"]*(?:\?|&|&amp;)brizy=(.[^"]*))"/im', $content, $matches );
if ( ! isset( $matches[2] ) ) {
return $content;
}
foreach ( $matches[2] as $i => $url ) {
$url = urldecode($url);
$hash_matches = array();
preg_match( "/^.[^#]*(#.*)$/", $url, $hash_matches );
$url = preg_replace( "/^(.[^#]*)#.*$/", '$1', $url );
if ( $url ) {
// store and replace $url
$new_url = $this->storage->store( $url );
if ( $new_url == $url ) {
continue;
}
if ( isset( $hash_matches[1] ) && $hash_matches[1] != '' ) {
$new_url .= $hash_matches[1];
}
$content = str_replace( $matches[1][ $i ], $new_url, $content );
}
}
return $content;
}
}

View File

@@ -0,0 +1,28 @@
<?php
class Brizy_Editor_Asset_AssetProxyStorage extends Brizy_Editor_Asset_AbstractStorage {
/**
* Get the asset and store it somewhere in uploads and return the new local url.
*
* @param $asset_url
*
* @return mixed
*/
public function store( $asset_url ) {
//$asset_url = html_entity_decode( $asset_url );
$new_url = $this->url_builder->page_upload_url( "assets/icons/" . basename( $asset_url ) );
$new_path = $this->url_builder->page_upload_path( "assets/icons/" . basename( $asset_url ) );
$external_url = $this->url_builder->external_asset_url( $asset_url );
if ( $this->store_file( $external_url, $new_path ) ) {
$asset_url = $new_url;
}
return $asset_url;
}
}

View File

@@ -0,0 +1,28 @@
<?php
trait Brizy_Editor_Asset_AttachmentAware {
/**
* @param $media_name
*
* @return null|string
*/
private function getAttachmentByMediaName( $media_name ) {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare(
"SELECT
p.ID
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->postmeta} m ON ( p.ID = m.post_id )
WHERE
( m.meta_key = 'brizy_attachment_uid' AND m.meta_value = %s )
AND p.post_type = 'attachment'
AND p.post_status = 'inherit'
GROUP BY p.ID
ORDER BY p.post_date DESC",
$media_name
) );
}
}

View File

@@ -0,0 +1,96 @@
<?php
class Brizy_Editor_Asset_Cleaner {
const CLEAN_FILES_CRON_KEY = 'brizy-asset-clean-files';
const CLEAN_EMPTY_DIRS_CRON_KEY = 'brizy-asset-clean-dirs';
const FILE_LIFE_TIME = 2592000; // 30 days
public static function _init() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* Brizy_Admin_Cloud_Cron constructor.
*/
public function __construct() {
add_action( self::CLEAN_FILES_CRON_KEY, array( $this, 'clean_files' ) );
add_action( self::CLEAN_EMPTY_DIRS_CRON_KEY, array( $this, 'clean_empty_dirs' ) );
add_filter( 'cron_schedules', [ $this, 'cron_schedules' ] );
if ( ! wp_next_scheduled( self::CLEAN_FILES_CRON_KEY ) ) {
wp_schedule_event( time(), 'ten_minutes', self::CLEAN_FILES_CRON_KEY );
}
if ( ! wp_next_scheduled( self::CLEAN_EMPTY_DIRS_CRON_KEY ) ) {
wp_schedule_event( time(), 'daily', self::CLEAN_EMPTY_DIRS_CRON_KEY );
}
}
/**
* Remove images older than 30 days
*/
public function clean_files() {
$wp_filesystem = new WP_Filesystem_Direct( null );
$now = time();
foreach ( glob( $this->get_upload_dir() . '*/assets/images/{*/*.*,*/*/*.*}', GLOB_BRACE ) as $img ) {
if ( $now - filemtime( $img ) >= self::FILE_LIFE_TIME ) {
$wp_filesystem->delete( $img );
}
}
}
/**
* Remove empty folders
*/
public function clean_empty_dirs() {
$wp_filesystem = new WP_Filesystem_Direct( null );
foreach ( glob( $this->get_upload_dir() . '*/assets/images/*', GLOB_ONLYDIR ) as $dir ) {
$this->rm_empty_dir( $dir, $wp_filesystem );
}
}
private function rm_empty_dir( $path, $wp_filesystem ) {
$empty = true;
foreach ( glob( $path . "/*" ) as $file ) {
if ( is_dir( $file ) ) {
if ( ! $this->rm_empty_dir( $file, $wp_filesystem ) ) {
$empty = false;
}
} else {
$empty = false;
}
}
if ( $empty ) {
$wp_filesystem->delete( $path, false, 'd' );
}
return $empty;
}
public function cron_schedules( $schedules ) {
$schedules['ten_minutes'] = array(
'interval' => 600,
'display' => esc_html__( 'Every Ten Minutes', 'brizy' ),
);
return $schedules;
}
public function get_upload_dir() {
$urlBuilder = new Brizy_Editor_UrlBuilder( Brizy_Editor_Project::get() );
return $urlBuilder->upload_path( 'brizy/' );
}
}

View File

@@ -0,0 +1,245 @@
<?php
class Brizy_Editor_Asset_Crop_Cropper {
const BASIC_CROP_TYPE = 1;
const ADVANCED_CROP_TYPE = 2;
/**
* @var string[]
*/
private $services;
/**
* Brizy_Editor_Asset_Crop_Cropper constructor.
*/
public function __construct() {
$this->services = array(
//'Brizy_Editor_Asset_Crop_ExternalService',
'Brizy_Editor_Asset_Crop_WordpressService'
);
}
/**
* @param $source
* @param $target
* @param $callback
*
* @return bool
*/
private function serviceLoop( $source, $target, $callback ) {
foreach ( $this->services as $serviceClass ) {
try {
/**
* @var Brizy_Editor_Asset_Crop_ServiceInterface $service ;
*/
$service = new $serviceClass( $source, $target );
if ( $callback( $service ) ) {
return true;
}
} catch ( Exception $e ) {
continue;
}
}
return false;
}
/**
* @param $source
* @param $target
* @param $offsetX
* @param $offsetY
* @param $width
* @param $height
*
* @return bool
*/
private function serviceCrop( $source, $target, $offsetX, $offsetY, $width, $height ) {
return $this->serviceLoop( $source, $target, function ( Brizy_Editor_Asset_Crop_ServiceInterface $service ) use ( $offsetX, $offsetY, $width, $height ) {
$result = $service->crop( $offsetX, $offsetY, $width, $height );
if ( $result ) {
$result = $service->saveTargetImage();
}
return $result;
} );
}
/**
* @param $source
* @param $target
* @param $width
* @param $height
*
* @return bool
*/
private function serviceResize( $source, $target, $width, $height ) {
return $this->serviceLoop( $source, $target, function ( Brizy_Editor_Asset_Crop_ServiceInterface $service ) use ( $width, $height ) {
$result = $service->resize( $width, $height );
if ( $result ) {
$result = $service->saveTargetImage();
}
return $result;
} );
}
/**
* @param $source
* @param $target
* @param $filterOptions
*
* @return bool
*/
private function internalCrop( $source, $target, $filterOptions ) {
if ( $filterOptions['format'] == "gif" ) {
// do not resize
return false;
} else {
list( $imgWidth, $imgHeight ) = $filterOptions['originalSize'];
if ( $filterOptions['is_advanced'] === false ) {
list( $requestedImgWidth, $requestedImgHeight ) = array_values( $filterOptions['requestedData'] );
if ( $requestedImgWidth > $imgWidth && ( $requestedImgHeight == "any" || $requestedImgHeight == "*" ) ) {
return false;
}
return $this->serviceResize( $source, $target, $requestedImgWidth, $requestedImgHeight );
}
list( $requestedImgWidth, $requestedImgHeight, $requestedOffsetX, $requestedOffsetY, $containerWidth, $containerHeight ) = array_values( $filterOptions['requestedData'] );
if ( ( $containerWidth > $imgWidth || $containerHeight > $imgHeight ) || $requestedImgWidth > $imgWidth && $requestedImgHeight > $imgHeight ) {
$newOffsetX = $imgWidth * $requestedOffsetX / $requestedImgWidth;
$newOffsetY = $imgHeight * $requestedOffsetY / $requestedImgHeight;
$newImgWidth = $imgWidth * $containerWidth / $requestedImgWidth;
$newImgHeight = $imgHeight * $containerHeight / $requestedImgHeight;
return $this->serviceCrop( $source, $target, $newOffsetX, $newOffsetY, $newImgWidth, $newImgHeight );
} else {
return $this->serviceLoop( $source, $target, function ( Brizy_Editor_Asset_Crop_ServiceInterface $service ) use ( $source, $target, $requestedImgWidth, $requestedImgHeight, $requestedOffsetX, $requestedOffsetY, $containerWidth, $containerHeight ) {
$result = $service->resize( $requestedImgWidth, null );
$imageSizeAfterResize = $service->getSize();
$blackStripOnX = ( $containerWidth + $requestedOffsetX ) - $requestedImgWidth;
$blackStripOnY = ( $containerHeight + $requestedOffsetY ) - $requestedImgHeight;
$requestedImgWidth = min( $imageSizeAfterResize['width'], $requestedImgWidth );
$requestedImgHeight = min( $imageSizeAfterResize['height'], $requestedImgHeight );
// calculated the crop over boundary values
$containerWidthStripDelta = $blackStripOnX > 0 ? $blackStripOnX : 0;
$containerHeightStripDelta = $blackStripOnY > 0 ? $blackStripOnY : 0;
// make sure the requested crop offset and size does now go over image boundaries
$requestedOffsetX = ( $blackStripOnX ) > 0 ? ( $requestedOffsetX - $containerWidthStripDelta ) : $requestedOffsetX;
$requestedOffsetY = ( $blackStripOnY ) > 0 ? ( $requestedOffsetY - $containerHeightStripDelta ) : $requestedOffsetY;
// avoid the case when the image height or with is less that 1px (GD problem)
$containerWidth = $containerWidth > $requestedImgWidth ? $requestedImgWidth : $containerWidth;
$containerHeight = $containerHeight > $requestedImgHeight ? $requestedImgHeight : $containerHeight;
if ( $result && $service->crop( $requestedOffsetX, $requestedOffsetY, $containerWidth, $containerHeight ) ) {
$result = $service->saveTargetImage();
if ( ! $result ) {
@unlink( $target );
}
return $result;
}
return false;
} );
}
}
}
/**
* @param $source
* @param $target
* @param $filter
*
* @return bool
* @throws Exception
*/
public function crop( $source, $target, $filter, $originalSizes ) {
try {
wp_raise_memory_limit( 'image' );
return $this->internalCrop( $source, $target, $this->getFilterOptions( $source, $filter, $originalSizes ) );
} catch ( Exception $e ) {
Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] );
return false;
}
}
/**
* @param $source
* @param $filter
*
* @return array
* @throws Exception
*/
public function getFilterOptions( $source, $filter, $originalSizes ) {
parse_str( strtolower( $filter ), $output );
$configuration = array();
$configuration['format'] = pathinfo( basename( $source ), PATHINFO_EXTENSION );
$configuration['originalSize'] = $originalSizes;
$cropType = $this->getCropType( $filter );
switch ( $cropType ) {
case self::BASIC_CROP_TYPE:
$configuration['requestedData']['imageWidth'] = (int) $output['iw'];
$configuration['requestedData']['imageHeight'] = (int) $output['ih'];
$configuration['is_advanced'] = false;
break;
case self::ADVANCED_CROP_TYPE:
$configuration['requestedData']['imageWidth'] = (int) $output['iw'];
$configuration['requestedData']['imageHeight'] = (int) $output['ih'];
$configuration['requestedData']['offsetX'] = (int) $output['ox'];
$configuration['requestedData']['offsetY'] = (int) $output['oy'];
$configuration['requestedData']['cropWidth'] = (int) $output['cw'];
$configuration['requestedData']['cropHeight'] = (int) $output['ch'];
$configuration['is_advanced'] = true;
break;
}
return $configuration;
}
/**
* @param $filter
*
* @return int|null
* @throws Exception
*/
private function getCropType( $filter ) {
$regExAdvanced = "/^iW=[0-9]{1,4}&iH=[0-9]{1,4}&oX=[0-9]{1,4}&oY=[0-9]{1,4}&cW=[0-9]{1,4}&cH=[0-9]{1,4}$/is";
$regExBasic = "/^iW=[0-9]{1,4}&iH=([0-9]{1,4}|any|\*{1})$/is";
if ( preg_match( $regExBasic, $filter ) ) {
$cropType = self::BASIC_CROP_TYPE;
} elseif ( preg_match( $regExAdvanced, $filter ) ) {
$cropType = self::ADVANCED_CROP_TYPE;
} else {
throw new Exception( "Invalid size format." );
}
return $cropType;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 4/4/19
* Time: 3:51 PM
*/
class Brizy_Editor_Asset_Crop_ExternalService implements Brizy_Editor_Asset_Crop_ServiceInterface {
/**
* @var string
*/
private $targetPath;
/**
* Brizy_Editor_Asset_Crop_WordpressService constructor.
*
* @param $sourcePath
* @param $targetPath
*
* @throws Exception
*/
public function __construct( $sourcePath, $targetPath ) {
if ( ! file_exists( $sourcePath ) ) {
throw new Exception( 'Unable to crop media. Source file not found.' );
}
$this->targetPath = $targetPath;
}
/**
* @param int $offsetX
* @param int $offsetY
* @param int $width
* @param int $height
*
* @throws Exception
*/
public function crop( $offsetX, $offsetY, $width, $height ) {
throw new Exception( 'Not implemented' );
}
/**
* @param int $width
* @param int $height
*
* @throws Exception
*/
public function resize( $width, $height ) {
throw new Exception( 'Not implemented' );
}
/**
* @throws Exception
*/
public function saveTargetImage() {
throw new Exception( 'Not implemented' );
}
public function getSize() {
throw new Exception( 'Not implemented' );
}
}

View File

@@ -0,0 +1,40 @@
<?php
interface Brizy_Editor_Asset_Crop_ServiceInterface {
/**
* Brizy_Editor_Asset_Crop_ServiceInterface constructor.
*
* @param string $sourcePath File paths
* @param string $targetPath File paths
*/
public function __construct( $sourcePath, $targetPath );
/**
* @param int $offsetX
* @param int $offsetY
* @param int $width
* @param int $height
*
* @return bool
*/
public function crop( $offsetX, $offsetY, $width, $height );
/**
* @param int $width
* @param int $height
*
* @return bool
*/
public function resize( $width, $height );
/**
* @return mixed
*/
public function getSize();
/**
* @return bool
*/
public function saveTargetImage();
}

View File

@@ -0,0 +1,105 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 4/4/19
* Time: 3:51 PM
*/
class Brizy_Editor_Asset_Crop_WordpressService implements Brizy_Editor_Asset_Crop_ServiceInterface {
/**
* @var WP_Image_Editor
*/
private $imageEditor;
/**
* @var string
*/
private $targetPath;
/**
* Brizy_Editor_Asset_Crop_WordpressService constructor.
*
* @param $sourcePath
* @param $targetPath
*
* @throws Exception
*/
public function __construct( $sourcePath, $targetPath ) {
if ( ! file_exists( $sourcePath ) ) {
throw new Exception( 'Unable to crop media. Source file not found.' );
}
$this->targetPath = $targetPath;
$this->imageEditor = wp_get_image_editor( $sourcePath );
if ( $this->imageEditor instanceof WP_Error ) {
Brizy_Logger::instance()->error( $this->imageEditor->get_error_message(), array( $this->imageEditor ) );
throw new Exception( "Unable to obtain the image editor" );
}
}
/**
* @param int $offsetX
* @param int $offsetY
* @param int $width
* @param int $height
*
* @return bool
*/
public function crop( $offsetX, $offsetY, $width, $height ) {
try {
$this->imageEditor->crop( $offsetX, $offsetY, $width, $height );
} catch ( Exception $e ) {
Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] );
return false;
}
return true;
}
public function getSize() {
try {
return $this->imageEditor->get_size();
} catch ( Exception $e ) {
Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] );
}
}
/**
* @param int $width
* @param int $height
*
* @return bool
*/
public function resize( $width, $height ) {
try {
$this->imageEditor->resize( $width, $height );
} catch ( Exception $e ) {
Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] );
return false;
}
return true;
}
/**
* @throws Exception
*/
public function saveTargetImage() {
$result = $this->imageEditor->save( $this->targetPath );
if ( $result instanceof WP_Error ) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,34 @@
<?php
class Brizy_Editor_Asset_CssAssetProcessor implements Brizy_Editor_Content_ProcessorInterface {
/**
* @var Brizy_Editor_Asset_Storage
*/
private $storage;
/**
* Brizy_Editor_Asset_HtmlAssetProcessor constructor.
*
* @param Brizy_Editor_Asset_Storage $storage
*/
public function __construct( Brizy_Editor_Asset_Storage $storage ) {
$this->storage = $storage;
}
/**
* Find and cache all assets and replace the urls with new local ones.
*
* The css assets must be ignored as we have a special processor this.
*
* @param $content
*
* @param Brizy_Content_Context $context
*
* @return string
*/
public function process( $content, Brizy_Content_Context $context ) {
return $content;
}
}

View File

@@ -0,0 +1,21 @@
<?php
class Brizy_Editor_Asset_DomainProcessor implements Brizy_Editor_Content_ProcessorInterface {
/**
* @param string $content
* @param Brizy_Content_Context $context
*
* @return mixed|null|string|string[]
*/
public function process( $content, Brizy_Content_Context $context ) {
$url = home_url();
$content = Brizy_SiteUrlReplacer::restoreSiteUrl( $content, $url );
return $content;
}
}

View File

@@ -0,0 +1,113 @@
<?php
class Brizy_Editor_Asset_MediaAssetProcessor implements Brizy_Editor_Content_ProcessorInterface {
/**
* @var Brizy_Editor_Asset_Storage
*/
private $storage;
/**
* Brizy_Editor_Asset_HtmlAssetProcessor constructor.
*
* @param Brizy_Editor_Asset_AbstractStorage $storage
*/
public function __construct( $storage ) {
$this->storage = $storage;
}
/**
* Find and cache all assets and replace the urls with new local ones.
*
* @param string $content
* @param Brizy_Content_Context $context
*
* @return mixed|string
*/
public function process( $content, Brizy_Content_Context $context ) {
return $this->process_external_asset_urls( $content, $context );
}
/**
* @param string $content
* @param Brizy_Content_Context $context
*
* @return string
*/
public function process_external_asset_urls( $content, Brizy_Content_Context $context ) {
$site_url = str_replace( array( 'http://', 'https://' ), '', home_url() );
$site_url = str_replace( array( '/', '.' ), array( '\/', '\.' ), $site_url );
$project = $context->getProject();
$uidKey = Brizy_Editor::prefix( Brizy_Public_CropProxy::ENDPOINT );
$postIdKey = Brizy_Editor::prefix( Brizy_Public_CropProxy::ENDPOINT_POST );
$sizeKey = Brizy_Editor::prefix( Brizy_Public_CropProxy::ENDPOINT_FILTER );
preg_match_all( '/(http|https):\/\/' . $site_url . '\/?(\?' . $uidKey . '=(.[^"\',\s)]*))/im', $content, $matches );
if ( empty( $matches[0] ) ) {
return $content;
}
$uids = [];
foreach ( $matches[0] as $url ) {
try {
$args = $this->getQueryArgs( $url );
$uid = $args[ $uidKey ];
if ( ! is_numeric( $uid ) && ! in_array( $uid, $uids ) ) {
$uids[] = $uid;
}
} catch ( Exception $e ) {
continue;
}
}
$mediaCache = new Brizy_Editor_CropCacheMedia( $project );
$mediaCache->cacheImgs( $uids );
foreach ( $matches[0] as $url ) {
try {
$args = $this->getQueryArgs( $url );
$postId = null;
if ( ! empty( $args[ $postIdKey ] ) && $postId = $args[ $postIdKey ] ) {
$postId = wp_is_post_revision( $postId ) ? wp_get_post_parent_id( $postId ) : $postId;
}
$croppedUrl = $mediaCache->tryOptimizedPath( $args[ $uidKey ], $args[ $sizeKey ], $postId );
$content = str_replace( $url, $croppedUrl, $content );
} catch ( Exception $e ) {
continue;
}
}
return $content;
}
/**
* @throws Exception
*/
private function getQueryArgs( $url ) {
$endpoint = Brizy_Editor::prefix( Brizy_Public_CropProxy::ENDPOINT );
$parsedUrl = parse_url( html_entity_decode( $url ) );
if ( empty( $parsedUrl['query'] ) ) {
throw new Exception( 'The query does not exists.' );
}
parse_str( $parsedUrl['query'], $args );
if ( empty( $args[ $endpoint ] ) ) {
throw new Exception( 'Invalid query.' );
}
return $args;
}
}

View File

@@ -0,0 +1,38 @@
<?php
class Brizy_Editor_Asset_MediaProxyStorage extends Brizy_Editor_Asset_AbstractStorage {
/**
* Get the asset and store it somewhere in uploads and return the new local url.
*
* @param $asset_url
*
* @return mixed
*/
public function store( $asset_url ) {
$asset_url = html_entity_decode( $asset_url );
$sufix_url = $this->getAssetPart( $asset_url, $this->config['urls']['image'] );
$new_url = $this->url_builder->page_upload_url( "assets/images/".$sufix_url );
$new_path = $this->url_builder->page_upload_path( "assets/images/".$sufix_url );
$external_url = $this->url_builder->external_media_url( $sufix_url );
if ( $this->store_file( $external_url, $new_path ) ) {
$asset_url = $new_url;
}
return $asset_url;
}
/**
* @param $url
* @param $prefix
*
* @return mixed
*/
public function getAssetPart( $url, $prefix ) {
return str_replace( $prefix, '', $url );
}
}

View File

@@ -0,0 +1,30 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Asset_Media {
private $url;
private $path;
public function __construct( $url, $path ) {
$this->path = $path;
$this->url = $url;
}
public function get_path() {
return $this->path;
}
public function get_url() {
return $this->url;
}
public function get_name() {
return basename( $this->get_path() );
}
public function get_type() {
return pathinfo( $this->get_path(), PATHINFO_EXTENSION );
}
}

View File

@@ -0,0 +1,249 @@
<?php
trait Brizy_Editor_Asset_StaticFileTrait
{
public static function get_asset_content($asset_source)
{
$http = new WP_Http();
$wp_response = null;
if (is_string($asset_source)) {
$wp_response = $http->request($asset_source, array('timeout' => 30));
} else {
foreach ($asset_source as $url) {
$wp_response = $http->request($url, array('timeout' => 30));
if (is_wp_error($wp_response)) {
Brizy_Logger::instance()->error('Unable to get media content', array('exception' => $wp_response));
continue;
}
break;
}
}
$code = wp_remote_retrieve_response_code($wp_response);
if (is_wp_error($wp_response) || !($code >= 200 && $code < 300)) {
Brizy_Logger::instance()->error('Unable to get media content', array('exception' => $wp_response));
return false;
}
$content = wp_remote_retrieve_body($wp_response);
return $content;
}
/**
* @param $asset_source
* @param $asset_path
*
* @return bool
*/
protected function store_file($asset_source, $asset_path)
{
if (file_exists($asset_path)) {
return true;
}
try {
// check destination dir
$dir_path = dirname($asset_path);
if (!file_exists($dir_path)) {
if (!file_exists($dir_path) && !mkdir($dir_path, 0755, true) && !is_dir($dir_path)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir_path));
}
}
$content = self::get_asset_content($asset_source);
if ($content !== false) {
file_put_contents($asset_path, $content);
} else {
return false;
}
} catch (Exception $e) {
// clean up
if ($asset_path) {
@unlink($asset_path);
}
return false;
}
return true;
}
protected function create_attachment($madia_name, $absolute_asset_path, $relative_asset_path, $post_id = null, $uid = null)
{
return self::createMediaAttachment($absolute_asset_path, $relative_asset_path, $post_id, $uid);
}
public static function createMediaAttachment($absolute_asset_path, $relative_asset_path, $post_id = null, $uid = null)
{
$filetype = wp_check_filetype($absolute_asset_path);
$upload_path = wp_upload_dir();
$attachment = array(
'guid' => $upload_path['baseurl'] . "/" . $relative_asset_path,
'post_mime_type' => $filetype['type'],
'post_title' => basename($absolute_asset_path),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($attachment, $relative_asset_path, $post_id);
if (is_wp_error($attachment_id) || $attachment_id === 0) {
return false;
}
update_post_meta($attachment_id, 'brizy_attachment_uid', $uid ? $uid : md5($attachment_id . time()));
if (!function_exists('wp_generate_attachment_metadata')) {
include_once ABSPATH . "/wp-admin/includes/image.php";
}
$attach_data = wp_generate_attachment_metadata($attachment_id, $absolute_asset_path);
wp_update_attachment_metadata($attachment_id, $attach_data);
return $attachment_id;
}
/**
* @param $filename
* @param array $headers
*/
public function send_file($filename, $headers = array())
{
if (file_exists($filename)) {
$defaultHeaders = array(
'Content-Type' => self::get_mime($filename, 1),
'Cache-Control' => 'max-age=600'
);
$content = file_get_contents($filename);
// send headers
$headers = array_merge($defaultHeaders, $headers);
foreach ($headers as $key => $val) {
if (is_array($val)) {
$val = implode(', ', $val);
}
header("{$key}: {$val}");
}
// send file content
echo $content;
exit;
} else {
global $wp_query;
$wp_query->set_404();
return;
}
}
/**
* @param $filename
* @param int $mode
*
* @return mixed|string
*/
public static function get_mime($filename, $mode = 0)
{
// mode 0 = full check
// mode 1 = extension check only
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'webp' => 'image/webp',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'docx' => 'application/msword',
'xlsx' => 'application/vnd.ms-excel',
'pptx' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$array = explode('.', $filename);
$str = end($array);
$ext = strtolower($str);
if (function_exists('mime_content_type') && $mode == 0) {
$mimetype = mime_content_type($filename);
return $mimetype;
} elseif (function_exists('finfo_open') && $mode == 0) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
} elseif (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
} else {
return 'application/octet-stream';
}
}
}

View File

@@ -0,0 +1,6 @@
<?php
abstract class Brizy_Editor_Asset_StaticFile {
use Brizy_Editor_Asset_StaticFileTrait;
}

View File

@@ -0,0 +1,95 @@
<?php
class Brizy_Editor_Asset_Storage extends Brizy_Editor_Asset_AbstractStorage {
private $config;
/**
* Brizy_Editor_Asset_Storage constructor.
*
* @param $url_builder
* @param $config
*/
public function __construct( $url_builder, $config ) {
parent::__construct( $url_builder );
$this->config = $config;
}
/**
* Get the asset and store it somewhere in uploads and return the new local url.
*
* @param $asset_url
*
* @return mixed
*/
public function store( $asset_url ) {
$asset_url = html_entity_decode( $asset_url );
if ( $this->isEditorUrl( $asset_url ) ) {
$sufix_url = $this->getAssetPart( $asset_url, $this->config['urls']['assets'] );
$new_path = $this->url_builder->editor_asset_path( $sufix_url );
$new_url = $this->url_builder->upload_url( $new_path );
if ( $this->store_file( $asset_url, $new_path ) ) {
$asset_url = $new_url;
}
}
if ( $this->isStaticUrl( $asset_url ) ) {
$sufix_url = $this->getAssetPart( $asset_url, $this->config['urls']['static'] );
$new_path = $this->url_builder->page_upload_path( $sufix_url );
$new_url = $this->url_builder->page_upload_url( $sufix_url );
if ( $this->store_file( $asset_url, $new_path ) ) {
$asset_url = $new_url;
}
}
if ( $this->isMediaUrl( $asset_url ) ) {
$sufix_url = $this->getAssetPart( $asset_url, $this->config['urls']['image'] );
$new_path = $this->url_builder->media_asset_path( $sufix_url );
$new_url = $this->url_builder->media_asset_url( $sufix_url );
if ( $this->store_file( $asset_url, $new_path ) ) {
$asset_url = $new_url;
}
}
return $asset_url;
}
/**
* @param $url
*
* @return bool
*/
public function isStaticUrl( $url ) {
return strpos( $url, $this->config['urls']['static'] ) === 0;
}
public function getAssetPart( $url, $prefix ) {
return str_replace( $prefix, '', $url );
}
/**
* @param $url
*
* @return bool
*/
public function isEditorUrl( $url ) {
return strpos( $url, $this->config['urls']['assets'] ) === 0;
}
/**
* @param $url
*
* @return bool
*/
public function isMediaUrl( $url ) {
return strpos( $url, $this->config['urls']['image'] ) === 0;
}
}

View File

@@ -0,0 +1,94 @@
<?php
class Brizy_Editor_Asset_SvgAssetProcessor implements Brizy_Editor_Content_ProcessorInterface {
/**
* Find and cache all assets and replace the urls with new local ones.
*
* @param string $content
* @param Brizy_Content_Context $context
*
* @return mixed|string
*/
public function process( $content, Brizy_Content_Context $context ) {
$content = $this->process_external_asset_urls( $content, $context );
return $content;
}
/**
* @param string $content
* @param Brizy_Content_Context $context
*
* @return mixed
*/
public function process_external_asset_urls( $content, Brizy_Content_Context $context ) {
$site_url = str_replace( array( 'http://', 'https://' ), '', home_url() );
$site_url = str_replace( array( '/', '.' ), array( '\/', '\.' ), $site_url );
//preg_match_all( '/' . $site_url . '\/?(\?' . Brizy_Public_CropProxy::ENDPOINT . '=(.[^"\',\s)]*))/im', $content, $matches );
$brizy_attachment = Brizy_Editor::prefix('_attachment');
preg_match_all( '/(http|https):\/\/' . $site_url . '\/?(\?'.$brizy_attachment.'=(.[^"\',\s)]*))/im', $content, $matches );
if ( ! isset( $matches[0] ) || count( $matches[0] ) == 0 ) {
return $content;
}
foreach ( $matches[0] as $i => $url ) {
$parsed_url = parse_url( html_entity_decode( $matches[0][ $i ] ) );
if ( ! isset( $parsed_url['query'] ) ) {
continue;
}
parse_str( $parsed_url['query'], $params );
if ( ! isset( $params[$brizy_attachment] ) ) {
continue;
}
$media_path = $this->get_attachment_file_by_uid( $params[$brizy_attachment] );
if ( ! $media_path ) {
return $content;
}
$content = str_replace( $matches[0][ $i ], $media_path, $content );
}
return $content;
}
private function get_attachment_file_by_uid( $attachmentUId ) {
if ( ! is_numeric( $attachmentUId ) ) {
global $wpdb;
$posts_table = $wpdb->posts;
$meta_table = $wpdb->postmeta;
$attachment = $wpdb->get_var( $wpdb->prepare(
"SELECT
{$posts_table}.ID
FROM {$posts_table}
INNER JOIN {$meta_table} ON ( {$posts_table}.ID = {$meta_table}.post_id )
WHERE
{$meta_table}.meta_key = 'brizy_attachment_uid'
AND {$meta_table}.meta_value = %s
AND {$posts_table}.post_type = 'attachment'
GROUP BY {$posts_table}.ID
ORDER BY {$posts_table}.post_date DESC",
$attachmentUId
) );
if ( ! $attachment ) {
return;
}
}
return wp_get_attachment_url( (int)$attachment );
}
}

View File

@@ -0,0 +1,141 @@
<?php
trait Brizy_Editor_AutoSaveAware {
/**
* @param WP_Post $post
* @param $callaback
*
* @return bool|WP_Error
*/
public function auto_save_post( \WP_Post $post, $callaback ) {
try {
$user_id = get_current_user_id();
$postParentId = $post->post_parent;
$old_autosave = $this->getLastAutosave( $postParentId?$postParentId:$post->ID, $user_id );
$post_data = get_object_vars( $post );
$post_data['post_content'] .= "\n<!-- " . time() . "-->";
$autosavePost = null;
if ( $old_autosave ) {
$autosavePost = self::get( $old_autosave );
}
if ( $old_autosave ) {
$new_autosave = _wp_post_revision_data( $post_data, true );
$new_autosave['ID'] = $old_autosave;
$new_autosave['post_author'] = $user_id;
// If the new autosave has the same content as the post, delete the autosave.
$autosave_is_different = false;
foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
if ( normalize_whitespace( $new_autosave[ $field ] ) != normalize_whitespace( $post->$field ) ) {
$autosave_is_different = true;
break;
}
}
if ( ! $autosave_is_different ) {
wp_delete_post_revision( $old_autosave );
return new WP_Error( 'rest_autosave_no_changes', __( 'There is nothing to save. The autosave and the post content are the same.' ), array( 'status' => 400 ) );
}
/**
* This filter is documented in wp-admin/post.php.
*/
do_action( 'wp_creating_autosave', $new_autosave );
// wp_update_post expects escaped array.
wp_update_post( wp_slash( $new_autosave ) );
} else {
// Create the new autosave as a special post revision.
$revId = _wp_put_post_revision( $post_data, true );
$autosavePost = self::get( $revId );
}
$callaback( $autosavePost );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->exception( $exception );
return false;
}
}
/**
* @param $postId
* @param $userId
*
* @return int|void|null
* @throws Exception
*/
public static function getAutoSavePost( $postId, $userId ) {
$postParentId = wp_get_post_parent_id( $postId );
$autosave = wp_get_post_autosave( $postParentId ?$postParentId:$postId, $userId );
if ( ! $autosave ) {
return;
}
$post = get_post( $postId );
$postDate = new DateTime( $post->post_modified );
$autosaveDate = new DateTime( $autosave->post_modified );
if ( $postDate > $autosaveDate ) {
return null;
}
return $autosave->ID;
}
/**
* @param int $postParentId
*/
private function deleteOldAutoSaves( $postParentId ) {
global $wpdb;
$user_id = get_current_user_id();
$wpdb->query( $wpdb->prepare( "
DELETE p, pm FROM {$wpdb->posts} p
INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.id
WHERE p.post_author = %d and
p.post_parent = %d and
p.post_type = 'revision' and
p.post_name LIKE %s", $user_id, $postParentId, "{$postParentId}-autosave%" ) );
}
/**
* @param int $postParentId
* @param int $user_id
*
* @return int
*/
protected function getLastAutosave( $postParentId, $user_id ) {
global $wpdb;
$postParentId = (int) $postParentId;
$user_id = (int) $user_id;
$query = sprintf( "SELECT ID FROM {$wpdb->posts} WHERE post_parent = %d AND post_type= 'revision' AND post_status= 'inherit'AND post_name LIKE '%d-autosave%%'", $postParentId, $postParentId );
if ( is_integer( $user_id ) ) {
$query .= " AND post_author={$user_id}";
}
$query .= " ORDER BY post_date DESC";
return (int) $wpdb->get_var( $query );
}
/**
* @return mixed
*/
abstract protected function populateAutoSavedData( $autosave );
}

View File

@@ -0,0 +1,130 @@
<?php
class Brizy_Editor_BlockPosition extends Brizy_Admin_Serializable {
/**
* @var string
*/
protected $align;
/**
* @var int
*/
protected $top;
/**
* @var int
*/
protected $bottom;
/**
* Brizy_Editor_BlockPosition constructor.
*
* @param null $top
* @param null $bottom
* @param null $align
*/
public function __construct( $top = null, $bottom = null, $align = null ) {
$this->align = $align;
$this->top = $top;
$this->bottom = $bottom;
}
/**
* @return string
*/
public function getAlign() {
return $this->align;
}
/**
* @param string $align
*
* @return Brizy_Editor_BlockPosition
*/
public function setAlign( $align ) {
$this->align = $align;
return $this;
}
/**
* @return int
*/
public function getTop() {
return $this->top;
}
/**
* @param int $top
*
* @return Brizy_Editor_BlockPosition
*/
public function setTop( $top ) {
$this->top = (int) $top;
return $this;
}
/**
* @return int
*/
public function getBottom() {
return $this->bottom;
}
/**
* @param int $bottom
*
* @return Brizy_Editor_BlockPosition
*/
public function setBottom( $bottom ) {
$this->bottom = (int) $bottom;
return $this;
}
/**
* @return string
*/
public function serialize() {
$get_object_vars = array(
'align' => $this->getAlign(),
'top' => $this->getTop(),
'bottom' => $this->getBottom()
);
return serialize( $get_object_vars );
}
public function jsonSerialize() {
$get_object_vars = array(
'top' => $this->getTop(),
'bottom' => $this->getBottom(),
'align' => $this->getAlign()
);
return $get_object_vars;
}
public function convertToOptionValue() {
$get_object_vars = array(
'align' => $this->getAlign(),
'top' => $this->getTop(),
'bottom' => $this->getBottom()
);
return $get_object_vars;
}
static public function createFromSerializedData( $data ) {
$instance = new self(
isset( $data['top'] ) ? $data['top'] : null,
isset( $data['bottom'] ) ? $data['bottom'] : null,
isset( $data['align'] ) ? $data['align'] : null
);
return $instance;
}
}

View File

@@ -0,0 +1,98 @@
<?php
use Brizy\Utils\UUId;
class Brizy_Editor_BlockScreenshotApi extends Brizy_Admin_AbstractApi {
const nonce = 'brizy-api';
const AJAX_CREATE_BLOCK_SCREENSHOT = '_create_block_screenshot';
const AJAX_UPDATE_BLOCK_SCREENSHOT = '_update_block_screenshot';
/**
* @var Brizy_Editor_Post
*/
private $post;
/**
* @var array
*/
private $blockTypes;
/**
* Brizy_Editor_BlockScreenshotApi constructor.
*
* @param $post
*
* @throws Exception
*/
public function __construct( $post ) {
$this->post = $post;
$this->blockTypes = array(
Brizy_Editor_Screenshot_Manager::BLOCK_TYPE_NORMAL,
Brizy_Editor_Screenshot_Manager::BLOCK_TYPE_GLOBAL,
Brizy_Editor_Screenshot_Manager::BLOCK_TYPE_SAVED,
Brizy_Editor_Screenshot_Manager::BLOCK_TYPE_LAYOUT
);
parent::__construct();
}
protected function getRequestNonce() {
return $this->param( 'hash' );
}
protected function initializeApiActions() {
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
$pref_nopriv = 'wp_ajax_nopriv_' . Brizy_Editor::prefix();
add_action( $pref . self::AJAX_CREATE_BLOCK_SCREENSHOT, array( $this, 'saveBlockScreenShot' ) );
add_action( $pref . self::AJAX_UPDATE_BLOCK_SCREENSHOT, array( $this, 'saveBlockScreenShot' ) );
add_action( $pref_nopriv . self::AJAX_CREATE_BLOCK_SCREENSHOT, array( $this, 'saveBlockScreenShot' ) );
add_action( $pref_nopriv . self::AJAX_UPDATE_BLOCK_SCREENSHOT, array( $this, 'saveBlockScreenShot' ) );
}
public function saveBlockScreenShot() {
$this->verifyNonce( self::nonce );
session_write_close();
if ( empty( $_REQUEST['block_type'] ) || ! in_array( $_REQUEST['block_type'], $this->blockTypes ) || empty( $_REQUEST['ibsf'] ) ) {
$this->error( 400, __( 'Bad request', 'brizy' ) );
}
$brizyPost = isset( $_REQUEST['post'] ) ? $_REQUEST['post'] : null;
$base64 = $_REQUEST['ibsf'];
$imageContent = base64_decode( $base64 );
if ( isset( $_REQUEST['id'] ) ) {
if ( ! preg_match( "/.[-a-zA-Z0-9]+/", $_REQUEST['id'] ) ) {
$this->error( 400, __( 'Invalid uid string', 'brizy' ) );
}
$screenId = $_REQUEST['id'];
} else {
$screenId = UUId::uuid();
}
if ( false === $imageContent ) {
$this->error( 400, __( 'Invalid image content', 'brizy' ) );
}
$manager = new Brizy_Editor_Screenshot_Manager( new Brizy_Editor_UrlBuilder( $brizyPost ) );
try {
$result = $manager->saveScreenshot( $screenId, $_REQUEST['block_type'], $imageContent, $brizyPost );
} catch ( Exception $e ) {
$this->error( 400, $e->getMessage() );
}
if ( $result ) {
$screenPath = $manager->getScreenshot( $screenId, $brizyPost );
wp_send_json_success( array( 'id' => $screenId, 'file_name' => $screenPath ) );
}
}
}

View File

@@ -0,0 +1,421 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/18/19
* Time: 12:20 PM
*/
class Brizy_Editor_Block extends Brizy_Editor_Post {
use Brizy_Editor_AutoSaveAware, Brizy_Editor_Synchronizable;
const BRIZY_META = 'brizy-meta';
const BRIZY_MEDIA = 'brizy-media';
const BRIZY_POSITION = 'brizy-position';
/**
* @var Brizy_Editor_BlockPosition
*/
protected $position;
/**
* @var string
*/
protected $meta;
/**
* @var string
*/
protected $media;
/**
* @var Brizy_Admin_Rule[]
*/
protected $rules;
/**
* @var self;
*/
static protected $block_instance = null;
public static function cleanClassCache() {
self::$block_instance = array();
}
protected function canBeSynchronized() {
return $this->isSavedBlock();
}
/**
* @param $apost
* @param null $uid
*
* @return Brizy_Editor_Block|Brizy_Editor_Post|mixed
* @throws Exception
*/
public static function get( $apost, $uid = null ) {
$wp_post_id = $apost;
if ( $apost instanceof WP_Post ) {
$wp_post_id = $apost->ID;
}
if ( isset( self::$block_instance[ $wp_post_id ] ) ) {
return self::$block_instance[ $wp_post_id ];
}
return self::$block_instance[ $wp_post_id ] = new self( $wp_post_id, $uid );
}
public function createResponse( $fields = array() ) {
if ( empty( $fields ) ) {
$fields = array(
'uid',
'id',
'meta',
'data',
'status',
'position',
'rules',
'dataVersion',
'synchronized',
'synchronizable',
'isCloudEntity'
);
}
$global = array();
if ( in_array( 'uid', $fields ) ) {
$global['uid'] = $this->getUid();
}
if ( in_array( 'status', $fields ) ) {
$global['status'] = get_post_status( $this->getWpPostId() );
}
if ( in_array( 'dataVersion', $fields ) ) {
$global['dataVersion'] = $this->getCurrentDataVersion();
}
if ( in_array( 'data', $fields ) ) {
$global['data'] = $this->get_editor_data();
}
if ( in_array( 'meta', $fields ) ) {
$global['meta'] = $this->getMeta();
}
if ( $this->getWpPost()->post_type == Brizy_Admin_Blocks_Main::CP_SAVED ) {
if ( in_array( 'isCloudEntity', $fields ) ) {
$global['isCloudEntity'] = false;
}
if ( in_array( 'synchronized', $fields ) ) {
$global['synchronized'] = $this->isSynchronized( Brizy_Editor_Project::get()->getCloudAccountId() );
}
if ( in_array( 'synchronizable', $fields ) ) {
$global['synchronizable'] = $this->isSynchronizable( Brizy_Editor_Project::get()->getCloudAccountId() );
}
}
if ( $this->getWpPost()->post_type == Brizy_Admin_Blocks_Main::CP_GLOBAL ) {
if ( in_array( 'position', $fields ) && $this->getPosition() ) {
$global['position'] = $this->getPosition()->convertToOptionValue();
}
if ( in_array( 'rules', $fields ) ) {
$ruleManager = new Brizy_Admin_Rules_Manager();
$global['rules'] = $ruleManager->getRules( $this->getWpPostId() );
}
}
return $global;
}
/**
* Brizy_Editor_Block constructor.
*
* @param $wp_post_id
* @param null $uid
*
* @throws Brizy_Editor_Exceptions_NotFound
* @throws Brizy_Editor_Exceptions_UnsupportedPostType
*/
public function __construct( $wp_post_id, $uid = null ) {
if ( $uid ) {
$this->uid = $uid;
}
parent::__construct( $wp_post_id );
}
/**
* @return bool
*/
public function uses_editor() {
return true;
}
/**
* This should always return true
*
* @param $val
*
* @return $this
*/
public function set_uses_editor( $val ) {
parent::set_uses_editor(true);
return $this;
}
public function setPosition( $position ) {
$this->position = $position;
return $this;
}
/**
* @return object
*/
public function getPosition() {
return $this->position;
}
/**
* @return Brizy_Admin_Rule[]
*/
public function getRules() {
return $this->rules;
}
/**
* @param Brizy_Admin_Rule[] $rules
*
* @return Brizy_Editor_Block
*/
public function setRules( $rules ) {
$this->rules = $rules;
return $this;
}
public function isGlobalBlock() {
return $this->getWpPost() instanceof WP_Post && $this->getWpPost()->post_type == Brizy_Admin_Blocks_Main::CP_GLOBAL;
}
public function isSavedBlock() {
return $this->getWpPost() instanceof WP_Post && $this->getWpPost()->post_type == Brizy_Admin_Blocks_Main::CP_SAVED;
}
/**
* @return array
*/
public function getMeta() {
return $this->meta;
}
/**
* @param string $meta
*
* @return Brizy_Editor_Block
*/
public function setMeta( $meta ) {
$this->meta = $meta;
return $this;
}
public function getMedia() {
return $this->media;
}
/**
* @param string $media
*
* @return Brizy_Editor_Block
*/
public function setMedia( $media ) {
$this->media = $media;
return $this;
}
public function jsonSerialize() {
$data = get_object_vars( $this );
$data['editor_data'] = base64_decode( $data['editor_data'] );
$data['rules'] = [];
$ruleManager = new Brizy_Admin_Rules_Manager();
$rules = $ruleManager->getRules( $this->getWpPostId() );
foreach ( $rules as $rule ) {
$data['rules'][] = $rule->jsonSerialize();
}
$data['position'] = null;
if ( $this->getPosition() ) {
$data['position'] = $this->getPosition()->jsonSerialize();
}
$data['meta'] = $this->getMeta();
$data['media'] = $this->getMedia();
//$data['cloudId'] = $this->getCloudId();
//$data['cloudAccountId'] = $this->getCloudAccountId();
unset( $data['wp_post'] );
return $data;
}
public function loadInstanceData() {
parent::loadInstanceData();
$storage = $this->getStorage();
$storage_post = $storage->get( self::BRIZY_POST, false );
$this->position = null;
$ruleManager = new Brizy_Admin_Rules_Manager();
$this->setRules( $ruleManager->getRules( $this->getWpPostId() ) );
// load synchronisation data
$this->loadSynchronizationData();
// back compatibility with old sync data
if ( isset( $storage_post['cloudId'] ) && isset( $storage_post['cloudAccountId'] ) ) {
$this->setSynchronized( $storage_post['cloudAccountId'], $storage_post['cloudId'] );
}
$this->setPosition( Brizy_Editor_BlockPosition::createFromSerializedData( get_metadata( 'post', $this->getWpPostId(), self::BRIZY_POSITION, true ) ) );
$this->meta = get_metadata( 'post', $this->getWpPostId(), self::BRIZY_META, true );
$this->media = get_metadata( 'post', $this->getWpPostId(), self::BRIZY_MEDIA, true );
}
public function convertToOptionValue() {
$data = parent::convertToOptionValue();
$ruleManager = new Brizy_Admin_Rules_Manager();
$data['position'] = null;
$data['rules'] = [];
if ( $this->getPosition() ) {
$data['position'] = $this->getPosition()->convertToOptionValue();
}
$rules = $ruleManager->getRules( $this->getWpPostId() );
foreach ( $rules as $rule ) {
$data['rules'][] = $rule->convertToOptionValue();
}
//$data['cloudId'] = $this->getCloudId();
//$data['cloudAccountId'] = $this->getCloudAccountId();
$data['media'] = $this->getMedia();
if ( $this->isSavedBlock() ) {
$data['synchronized'] = $this->isSynchronized( Brizy_Editor_Project::get()->getCloudAccountId() );
$data['synchronizable'] = $this->isSynchronizable( Brizy_Editor_Project::get()->getCloudAccountId() );
}
return $data;
}
/**
* @param $autosave
*
* @return Brizy_Editor_Block
*/
protected function populateAutoSavedData( $autosave ) {
/**
* @var Brizy_Editor_Block $autosave ;
*/
$autosave = parent::populateAutoSavedData( $autosave );
//$autosave->setPosition( $this->getPosition() );
//$autosave->setRules( $this->getRules() );
return $autosave;
}
/**
* @param $type
* @param array $arags
*
* @return array
* @throws Exception
*/
public static function getBlocksByType( $type, $arags = 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();
}
return $blocks;
}
public function save( $autosave = 0 ) {
parent::save( $autosave );
if ( $autosave !== 1 ) {
$this->savePost( true );
do_action( 'brizy_global_data_updated' );
}
}
/**
* This will take all values from entity and save them to database
*/
public function saveStorage() {
parent::saveStorage();
// save position
if ( $this->position instanceof Brizy_Editor_BlockPosition ) {
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_POSITION, $this->position->convertToOptionValue() );
}
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_META, $this->meta );
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_MEDIA, $this->media );
}
/**
* @return $this|Brizy_Editor_Block
* @throws Brizy_Editor_Exceptions_DataVersionMismatch
*/
protected function saveDataVersion()
{
// cyheck data version except for global blocks
// issue: #14271
if(Brizy_Admin_Blocks_Main::CP_GLOBAL !== $this->getWpPost()->post_type) {
parent::saveDataVersion();
}
return $this;
}
}

View File

@@ -0,0 +1,84 @@
<?php if (!defined('ABSPATH')) {
die('Direct access forbidden.');
}
class Brizy_Editor_CompiledHtml
{
/**
* @var Brizy_Editor_Helper_Dom
*/
private $dom;
/**
* Brizy_Editor_CompiledHtml constructor.
*
* @param $content
*/
public function __construct($content)
{
$this->dom = new Brizy_Editor_Helper_Dom($content);
}
/**
* @return string
* @deprecated Use getBody()
*/
public function get_body()
{
return $this->getBody();
}
/**
* @return string
*/
public function getBody()
{
$body_tag = $this->dom->get_body();
return $body_tag->get_content();
}
/**
* @param bool $include_parent_tag
*
* @return string
* @deprecated Use getHead)
*/
public function get_head($include_parent_tag = false)
{
return $this->getHead($include_parent_tag);
}
/**
* @param false $include_parent_tag
* @return string
*/
public function getHead($include_parent_tag = false)
{
$head_tag = $this->dom->get_head();
return $head_tag->get_content();
}
/**
* Extract the page content.. excluding headers and footers generated by Brizy
*
* This function will only remove headers added by Brizy.. if you want to remove some specific parts of the
* content please use the `brizy_exclude_from_page_content` filter to add selectors that will be removed.
*/
public function getPageContent()
{
$dom = pQuery::parseStr($this->getBody());
$dom->remove('section.brz-section__header');
$dom->remove('footer.brz-footer');
$excludeSelectors = apply_filters('brizy_exclude_from_page_content', []);
foreach ($excludeSelectors as $selector)
{
$dom->remove($selector);
}
return $dom->html();
}
}

View File

@@ -0,0 +1,11 @@
<?php
class Brizy_Editor_Constants {
/**
* @deprecated
*/
const USES_BRIZY = 'brizy-use-brizy';
const BRIZY_ENABLED = 'brizy_enabled';
}

View File

@@ -0,0 +1,11 @@
<?php
interface Brizy_Editor_Content_ProcessorInterface {
/**
* @param string $content
* @param Brizy_Content_Context $context
*
* @return mixed
*/
public function process( $content, Brizy_Content_Context $context );
}

View File

@@ -0,0 +1,277 @@
<?php
class Brizy_Editor_CropCacheMedia extends Brizy_Editor_Asset_StaticFile {
use Brizy_Editor_Asset_AttachmentAware;
/**
* @var Brizy_Editor_UrlBuilder
*/
private $url_builder;
private static $imgs = [];
/**
* Brizy_Editor_CropCacheMedia constructor.
*
* @param Brizy_Editor_Project $project
*/
public function __construct( $project ) {
$this->url_builder = new Brizy_Editor_UrlBuilder( $project );
}
/**
* @param $madia_name
* @param bool $ignore_wp_media
*
* @return false|string
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function download_original_image( $madia_name, $ignore_wp_media = true ) {
// Check if user is querying API
if ( ! $madia_name ) {
Brizy_Logger::instance()->error( 'Empty media file provided' );
throw new InvalidArgumentException( "Invalid media file" );
}
if ( $ignore_wp_media && strpos( $madia_name, "wp-" ) === 0 ) {
Brizy_Logger::instance()->error( 'Invalid try to download wordpress file from application server' );
throw new InvalidArgumentException( "Invalid media file" );
}
$external_asset_url = $this->url_builder->external_media_url( "iW=5000&iH=any/" . $madia_name );
if ( ! ( $attachmentId = $this->getAttachmentByMediaName( $madia_name ) ) ) {
// /var/www/html/wp-content/uploads/2021/09/mediaName.png
$original_asset_path = $this->url_builder->wp_upload_path( $madia_name );
// 2021/09/mediaName.png
$original_asset_path_relative = $this->url_builder->wp_upload_relative_path( $madia_name );
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', [
'source' => $external_asset_url,
'destination' => $original_asset_path
] );
throw new Exception( 'Unable to cache media' );
}
}
$attachmentId = $this->create_attachment( $madia_name, $original_asset_path, $original_asset_path_relative, null, $madia_name );
}
if ( $attachmentId === 0 || is_wp_error( $attachmentId ) ) {
Brizy_Logger::instance()->error( 'Unable to attach media file', [ 'media' => $external_asset_url ] );
throw new Exception( 'Unable to attach media' );
}
return get_attached_file( $attachmentId );
}
/**
* @param $original
* @param $size
*
* @return string|null
* @throws Exception
*/
public function crop_media( $uid, $size ) {
if ( ! $size ) {
throw new InvalidArgumentException( "Invalid crop filter" );
}
if ( array_key_exists( $size, Brizy_Editor::get_all_image_sizes() ) ) {
return $this->getImgUrlByWpSize( $uid, $size, true );
}
$resizedImgPath = $this->getResizedMediaPath( $uid, $size );
if ( file_exists( $resizedImgPath ) ) {
return $resizedImgPath;
}
$cropPath = $this->url_builder->brizy_upload_path( 'imgs/' );
if ( ! wp_mkdir_p( $cropPath ) ) {
throw new RuntimeException( sprintf( 'Directory "%s" was not created', $cropPath ) );
}
$cropper = new Brizy_Editor_Asset_Crop_Cropper();
$originalPath = $this->getOriginalPath( $uid );
if ( ! $cropper->crop( $originalPath, $resizedImgPath, $size, $this->getOrignalImgSizes( $uid ) ) ) {
return $originalPath;
}
return $resizedImgPath;
}
/**
* @throws Exception
*/
public function tryOptimizedPath( $uid, $size, $postId ) {
$originalPath = $this->getOriginalPath( $uid );
$urlBuilder = new Brizy_Editor_UrlBuilder( Brizy_Editor_Project::get(), $postId );
$resized_image_path = $this->buildPath( $urlBuilder->page_upload_path( "/assets/images/" . $size ), $this->basename( $originalPath ) );
$optimizedPath = $this->buildPath( dirname( $resized_image_path ), 'optimized', $this->basename( $resized_image_path ) );
if ( file_exists( $optimizedPath ) ) {
return str_replace( $this->url_builder->upload_path(), $this->url_builder->upload_url(), $optimizedPath );
}
if ( array_key_exists( $size, Brizy_Editor::get_all_image_sizes() ) ) {
return $this->getImgUrlByWpSize( $uid, $size );
}
$cropper = new Brizy_Editor_Asset_Crop_Cropper();
$options = $cropper->getFilterOptions( $originalPath, $size, $this->getOrignalImgSizes( $uid ) );
if (
$options['is_advanced'] === false
&&
$options['requestedData']['imageWidth'] > $options['originalSize'][0]
&&
in_array( $options['requestedData']['imageHeight'], [ 'any', '*', '0' ] )
) {
return $this->getImgUrlByWpSize( $uid, 'original' );
}
$croppedPath = $this->getResizedMediaPath( $uid, $size );
if ( ! file_exists( $croppedPath ) ) {
throw new Exception( 'The image was not cropped yet.' );
}
return str_replace( $this->url_builder->upload_path(), $this->url_builder->upload_url(), $croppedPath );
}
/**
* @param $uid
* @param $size
*
* @return string
* @throws Exception
*/
public function getResizedMediaPath( $uid, $size ) {
$originalPath = $this->getOriginalPath( $uid );
$pathinfo = pathinfo( $originalPath );
$size = strtolower( $size );
$size = str_replace( [ 'iw=', 'ih=', 'ox=', 'oy=', 'cw=', 'ch=' ], '', $size );
$size = str_replace( '&', 'x', $size );
$name = $pathinfo['filename'] . '-' . $size . 'x' . filemtime( $originalPath ) . '.' . $pathinfo['extension'];
return $this->buildPath( $this->url_builder->brizy_upload_path( 'imgs' ), $name );
}
/**
* @throws Exception
*/
public function getOriginalPath( $hash ) {
$id = $this->getAttachmentId( $hash );
$file = get_attached_file( $id );
if ( ! $file ) {
throw new Exception( sprintf( 'File by id "%s" is not found.', $id ) );
}
if ( ! file_exists( $file ) ) {
throw new Exception( sprintf( 'The file "%s" does not exist.', $file ) );
}
return $file;
}
/**
* @throws Exception
*/
private function getAttachmentId( $uid ) {
if ( is_numeric( $uid ) ) {
return $uid;
}
if ( isset( self::$imgs[ $uid ] ) ) {
return self::$imgs[ $uid ]->ID;
}
$img = get_posts( [
'meta_key' => 'brizy_attachment_uid',
'meta_value' => $uid,
'post_type' => 'attachment',
'fields' => 'ids',
'posts_per_page' => 10
] );
if ( empty( $img[0] ) ) {
throw new Exception( sprintf( 'There is no image with the uid "%s"', $uid ) );
}
return $img[0];
}
/**
* @throws Exception
*/
private function getOrignalImgSizes( $uid ) {
$sizes = wp_get_attachment_image_src( $this->getAttachmentId( $uid ), 'full' );
return [ $sizes[1], $sizes[2] ];
}
public function cacheImgs( $uids ) {
global $wpdb;
if ( ! $uids ) {
return;
}
$sql = "SELECT m.meta_value, p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} m ON ( p.ID = m.post_id ) WHERE m.meta_key = 'brizy_attachment_uid' AND m.meta_value IN (" . implode( ', ', array_fill( 0, count( $uids ), '%s' ) ) . ") AND p.post_type = 'attachment' ORDER BY p.post_date DESC";
$imgs = $wpdb->get_results( $wpdb->prepare( $sql, $uids ), OBJECT_K );
if ( ! $imgs ) {
return;
}
self::$imgs = array_merge( self::$imgs, $imgs );
}
/**
* @throws Exception
*/
private function getImgUrlByWpSize( $uid, $size, $path = false ) {
$size = $size == 'original' ? 'full' : $size;
$imgUrl = wp_get_attachment_image_url( $this->getAttachmentId( $uid ), $size );
if ( ! $imgUrl ) {
$imgUrl = str_replace( $this->url_builder->upload_path(), $this->url_builder->upload_url(), $this->getOriginalPath( $uid ) );
}
if ( $path ) {
return str_replace( $this->url_builder->upload_url(), $this->url_builder->upload_path(), $imgUrl );
}
return $imgUrl;
}
public function basename( $originalPath ) {
return preg_replace( '/^.+[\\\\\\/]/', '', $originalPath );
}
public function buildPath( ...$parts ) {
return implode( DIRECTORY_SEPARATOR, $parts );
}
}

View File

@@ -0,0 +1,5 @@
<?php
interface Brizy_Editor_Data_ProjectMergeStrategyInterface {
public function merge( $projectData1, $projectData2 );
}

View File

@@ -0,0 +1,32 @@
<?php
class Brizy_Editor_Data_ProjectMergeStrategy {
/**
* @param $version
*
* @return Brizy_Editor_Data_ProjectMergeStrategyInterface
*/
static public function getMergerInstance( $version ) {
if ( version_compare( $version, '1.0.81' ) <= 0 ) {
return new Brizy_Editor_Data_ProjectMerge81();
}
return new Brizy_Editor_Data_ProjectMerge82();
}
/**
* This code needs to be updated if the project data will change.
*
* @param $version
*
* @return bool
*/
static public function checkVersionCompatibility( $version ) {
if ( version_compare( $version, '1.0.81' ) > 0 && version_compare( $version, BRIZY_VERSION ) <= 0 ) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,45 @@
<?php
class Brizy_Editor_Data_ProjectMerge81 implements Brizy_Editor_Data_ProjectMergeStrategyInterface {
/**
* @param $projectData1
* @param $projectData2
*
* @return mixed
*/
public function merge( $projectData1, $projectData2 ) {
// MERGE STYLES
// 1. merge extra fonts
$projectData1->extraFonts = array_unique(
array_merge(
(array) ( isset( $projectData1->extraFonts ) ? $projectData1->extraFonts : array() ),
(array) ( isset( $projectData2->extraFonts ) ? $projectData2->extraFonts : array() )
)
);
// 2. merge extra fonts styles
if ( ! isset( $projectData1->styles ) ) {
$projectData1->styles = (object) array( '_extraFontStyles' => array() );
}
$projectData1->styles->_extraFontStyles = array_merge(
(array) ( isset( $projectData1->styles->_extraFontStyles ) ? $projectData1->styles->_extraFontStyles : array() ),
(array) ( isset( $projectData2->styles->_extraFontStyles ) ? $projectData2->styles->_extraFontStyles : array() )
);
$projectData1->styles->default = $projectData2->styles->default;
if ( $projectData2->styles && isset( $projectData2->styles->_selected ) ) {
$selected = $projectData2->styles->_selected;
$projectData1->styles->_selected = $selected;
if ( $selected ) {
$projectData1->styles->$selected = $projectData2->styles->$selected;
}
}
return $projectData1;
}
}

View File

@@ -0,0 +1,91 @@
<?php
class Brizy_Editor_Data_ProjectMerge82 implements Brizy_Editor_Data_ProjectMergeStrategyInterface {
private function mergeFonts( $fonts, $newFonts, $key = "family" ) {
$result = $fonts;
foreach ( $newFonts->data as $newFont ) {
$exist = false;
foreach ( $fonts->data as $font ) {
if ( $font->$key === $newFont->$key ) {
$exist = true;
}
}
if ( ! $exist ) {
$result->data[] = $newFont;
}
}
return $result;
}
public function merge( $projectData1, $projectData2 ) {
$result = $projectData1;
// selected Kit
$result->selectedKit = $projectData2->selectedKit;
// selected Style
$result->selectedStyle = $projectData2->selectedStyle;
if ( ! isset( $result->styles ) ) {
$result->styles = array();
}
// merge styles
foreach ( $projectData2->styles as $i => $style ) {
foreach ( $result->styles as $j => $resultStyle ) {
if ( $style->id === $resultStyle->id ) {
$result->styles[ $j ] = $style;
} else {
$result->styles[] = $style;
}
}
}
// extraFontStyles
$result->extraFontStyles = array_merge(
(array) ( $result->extraFontStyles ),
(array) ( $projectData2->extraFontStyles )
);
// font
$result->font = $projectData2->font;
// fonts
// fonts -> config
$result->fonts->config = $this->mergeFonts( $result->fonts->config, $projectData2->fonts->config );
// fonts -> blocks
if ( isset( $projectData2->fonts->blocks ) ) {
if ( ! isset( $result->fonts->blocks ) ) {
$result->fonts->blocks = $projectData2->fonts->blocks;
} else {
$result->fonts->blocks = $this->mergeFonts( $projectData2->fonts->blocks, $projectData2->fonts->blocks );
}
}
// fonts -> google
if ( isset( $projectData2->fonts->google ) ) {
if ( ! isset( $result->fonts->google ) ) {
$result->fonts->google = $projectData2->fonts->google;
} else {
$result->fonts->google = $this->mergeFonts( $projectData2->fonts->google, $projectData2->fonts->google );
}
}
// fonts -> upload
if ( isset( $projectData2->fonts->upload ) ) {
if ( ! isset( $result->fonts->upload ) ) {
$result->fonts->uploud = $projectData2->fonts->upload;
} else {
$result->fonts->upload = $this->mergeFonts( $projectData2->fonts->upload, $projectData2->fonts->upload, "id" );
}
}
return $result;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,369 @@
<?php
abstract class Brizy_Editor_Entity extends Brizy_Admin_Serializable
{
const BRIZY_DATA_VERSION_KEY = 'brizy_data_version';
/**
* @var string
*/
protected $uid;
/**
* @var int
*/
protected $wp_post_id;
/**
* @var WP_Post
*/
protected $wp_post = null;
/**
* @var int
*/
protected $dataVersion = null;
/**
* Brizy_Editor_Entity constructor.
*/
public function __construct($postId)
{
if ( ! is_numeric($postId)) {
throw new Exception('Invalid post id provided');
}
Brizy_Editor::checkIfPostTypeIsSupported($postId);
$this->setWpPostId($postId);
$this->loadInstanceData();
}
/**
* @return bool
*/
public function can_edit_posts() {
return current_user_can( 'edit_posts' );
}
/**
* @return bool
*/
static public function canEditPosts() {
return current_user_can( 'edit_posts' );
}
static public function get($postId,$uid=null)
{
$type = get_post_type($postId);
switch ($type) {
case Brizy_Admin_Blocks_Main::CP_GLOBAL:
case Brizy_Admin_Blocks_Main::CP_SAVED:
return Brizy_Editor_Block::get($postId,$uid);
default:
case 'page':
case 'post':
case Brizy_Admin_Popups_Main::CP_POPUP:
return Brizy_Editor_Post::get($postId,$uid);
}
}
/**
* @return bool
*/
public function uses_editor() {
return self::isBrizyEnabled($this->getWpPostId());
}
/**
* @return bool
*/
static public function isBrizyEnabled($post) {
if($post instanceof WP_Post)
$post = $post->ID;
return (bool)get_post_meta($post, Brizy_Editor_Constants::BRIZY_ENABLED, true);
}
/**
* @param $value
*
* @return $this
* @throws Brizy_Editor_Exceptions_AccessDenied
*/
public function set_uses_editor( $value ) {
self::setBrizyEnabled($this->getWpPostId(), $value);
return $this;
}
/**
* @return bool
*/
static public function setBrizyEnabled($post, $value) {
if ( ! self::canEditPosts() ) {
throw new Brizy_Editor_Exceptions_AccessDenied( 'Current user cannot edit page' );
}
if($post instanceof WP_Post)
$post = $post->ID;
update_post_meta($post, Brizy_Editor_Constants::BRIZY_ENABLED, (int)$value);
}
/**
* @return string
*/
static public function getEditUrl($post) {
if($post instanceof WP_Post)
$post = $post->ID;
return add_query_arg(
array( Brizy_Editor::prefix( '-edit' ) => '' ),
get_permalink( $post )
);
}
/**
* @param $postId
*
* @return Brizy_Editor_Block|Brizy_Editor_Post|mixed
* @throws Exception
*/
public function duplicateTo($postId)
{
// check post types
if (get_post_type($postId) !== $this->getWpPost()->post_type) {
throw new Exception('Cannot duplicate post. Invalid target post type');
}
if ( ! $this->uses_editor()) {
throw new Exception('The source post is not using Brizy.');
}
// copy current date the the new post
$newPost = self::get($postId);
if ($newPost->uses_editor()) {
throw new Exception('Target post is using Brizy.');
}
$newPost->set_needs_compile(true);
$newPost->set_uses_editor(true);
$newPost->setDataVersion(1);
$newPost->createUid();
return $newPost;
}
/**
* Will return the key on witch the object data will be saved in storage
*
* @return mixed
*/
abstract protected function getObjectKey();
/**
* Load all object data
*/
abstract protected function loadInstanceData();
/**
* @return mixed
*/
abstract public function createResponse($fields = array());
/**
* Save post data and and trigger post update
*
* @return mixed
*/
abstract public function savePost();
/**
* This will save ro create an autosave object the the data from entity
* Also before saving the data version will be checked
*
* @return $this
* @throws Exception
*/
public function save($autosave = 0)
{
// check entity versions before saving.
if ((int)$autosave === 0) {
$this->saveDataVersion();
}
$this->createUid();
return $this;
}
/**
* This will take all values from entity and save them to database
*/
public function saveStorage()
{
$value = $this->convertToOptionValue();
$this->getStorage()->set($this->getObjectKey(), $value);
}
/**
* @return Brizy_Editor_Post[]
* @throws Brizy_Editor_Exceptions_NotFound
* @throws Brizy_Editor_Exceptions_UnsupportedPostType
*/
public static function get_all_brizy_post_ids()
{
global $wpdb;
$posts = $wpdb->get_results(
$wpdb->prepare(
"SELECT p.ID FROM {$wpdb->postmeta} pm
JOIN {$wpdb->posts} p ON p.ID=pm.post_id and p.post_type <> 'revision' and p.post_type<>'attachment' and p.post_status='publish'
WHERE pm.meta_key = %s ",
Brizy_Editor_Storage_Post::META_KEY
), ARRAY_A
);
return array_column($posts,'ID');
}
/**
* @return int
*/
public function getWpPostId()
{
return $this->wp_post_id;
}
/**
* @param int $wp_post_id
*
* @return Brizy_Editor_Entity
*/
public function setWpPostId($wp_post_id)
{
$this->wp_post_id = $wp_post_id;
return $this;
}
/**
* Return the post parent id
*
* @return int
*/
public function getWpPostParentId()
{
return $this->getWpPost()->post_parent ?: $this->getWpPostId();
}
/**
* @return WP_Post
*/
public function getWpPost()
{
return $this->wp_post ?: ($this->wp_post = get_post($this->getWpPostId()));
}
/**
* @return $this
*/
protected function saveDataVersion()
{
$version = $this->getCurrentDataVersion();
if ($this->dataVersion !== $version + 1) {
Brizy_Logger::instance()->critical(
'Unable to save entity. The data version is wrong.',
[
'post_id' => $this->getWpPostId(),
'currentVersion' => $version,
'newVersion' => $this->dataVersion,
]
);
throw new Brizy_Editor_Exceptions_DataVersionMismatch('Unable to save entity. The data version is wrong.');
}
update_post_meta($this->getWpPostId(), self::BRIZY_DATA_VERSION_KEY, $this->dataVersion);
return $this;
}
/**
* @return int
*/
public function getCurrentDataVersion()
{
return (int)(get_post_meta($this->getWpPostId(), self::BRIZY_DATA_VERSION_KEY, true) ?: 0);
}
/**
* @param $dataVersion
*
* @return $this
*/
public function setDataVersion($dataVersion)
{
$this->dataVersion = (int)$dataVersion;
return $this;
}
/**
* @return string
*/
public function getUid()
{
return $this->uid;
}
/**
* Return an instance of Brizy_Editor_Storage_Abstract that will store the object data
*
* @return Brizy_Editor_Storage_Post
*/
protected function getStorage()
{
return Brizy_Editor_Storage_Post::instance($this->wp_post_id);
}
/**
* @return mixed|string
*/
protected function createUid()
{
$WPPost = $this->getWpPost();
$post_id = $WPPost->post_type != 'revision'?$this->getWpPostId():$WPPost->post_parent;
if ($uid = $this->getUid()) {
$uid = get_post_meta($post_id, 'brizy_post_uid', true);
if ( ! $uid) {
update_post_meta($post_id, 'brizy_post_uid', $this->getUid());
}
return $uid;
}
$uid = get_post_meta($post_id, 'brizy_post_uid', true);
if ( ! $uid) {
$uid = md5($post_id.time());
update_post_meta($post_id, 'brizy_post_uid', $uid);
}
return $this->uid = $uid;
}
}

View File

@@ -0,0 +1,7 @@
<?php
class Brizy_Editor_Exceptions_AccessDenied extends Brizy_Editor_Exceptions_Exception {
protected $code = 401;
protected $message = 'Unauthorised access';
}

View File

@@ -0,0 +1,4 @@
<?php
class Brizy_Editor_Exceptions_DataVersionMismatch extends Exception {
}

View File

@@ -0,0 +1,16 @@
<?php
class Brizy_Editor_Exceptions_Exception extends Exception implements Serializable {
protected $code = 500;
protected $message = 'Internal server error';
public function serialize() {
return serialize( [ 'code' => $this->getCode(), 'message' => $this->getMessage() ] );
}
public function unserialize( $serialized ) {
$data = $this->unserialize( $serialized );
$this->code = $data['code'];
$this->message = $data['message'];
}
}

View File

@@ -0,0 +1,5 @@
<?php
class Brizy_Editor_Exceptions_InvalidContent extends Brizy_Editor_Exceptions_Exception {
protected $message = 'Content is invalid';
}

View File

@@ -0,0 +1,5 @@
<?php
class Brizy_Editor_Exception_NotBrizyPage extends Brizy_Editor_Exceptions_NotFound {
protected $message = 'Invalid page';
}

View File

@@ -0,0 +1,12 @@
<?php
class Brizy_Editor_Exceptions_NotFound extends Brizy_Editor_Exceptions_Exception {
protected $code = 404;
protected $message = 'Not Found';
public function __construct( $message = "", $code = 0, Throwable $previous = null ) {
parent::__construct( $message, $code, $previous );
}
}

View File

@@ -0,0 +1,7 @@
<?php
class Brizy_Editor_Exceptions_ServiceUnavailable extends Brizy_Editor_Exceptions_Exception {
protected $code = 503;
protected $message = 'Service Unavailable';
}

View File

@@ -0,0 +1,6 @@
<?php
class Brizy_Editor_Exceptions_SignatureMismatch extends Brizy_Editor_Exceptions_Exception {
protected $code = 409;
protected $message = 'Signature mismatch';
}

View File

@@ -0,0 +1,3 @@
<?php
class Brizy_Editor_Exceptions_UnsupportedPostType extends Brizy_Editor_Exceptions_NotFound {}

View File

@@ -0,0 +1,208 @@
<?php
abstract class Brizy_Editor_Forms_AbstractIntegration extends Brizy_Admin_Serializable {
/**
* @var string
*/
protected $id;
/**
* @var bool
*/
protected $completed;
/**
* @var WP_Error
*/
protected $exception;
/**
* Brizy_Editor_Forms_AbstractIntegration constructor.
*
* @param $id
*/
public function __construct( $id ) {
$this->id = $id;
}
/**
* @param Brizy_Editor_Forms_Form $form
* @param $fields
*
* @return mixed
*/
abstract public function handleSubmit( Brizy_Editor_Forms_Form $form, $fields );
public function handleFailToSendMessage( WP_Error $error ) {
$this->exception = $error;
}
/**
* @return bool
*/
public function isCompleted() {
return $this->completed;
}
/**
* @param bool $completed
*
* @return Brizy_Editor_Forms_AbstractIntegration
*/
public function setCompleted( $completed ) {
$this->completed = $completed;
return $this;
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->jsonSerialize() );
}
/**
* @return array|mixed
*/
public function jsonSerialize() {
$get_object_vars = array(
'id' => $this->getId(),
'completed' => $this->isCompleted(),
);
return $get_object_vars;
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Forms_AbstractIntegration
* @throws Exception
*/
public static function createInstanceFromJson( $json_obj ) {
$instance = null;
if ( is_object( $json_obj ) ) {
switch ( $json_obj->id ) {
case 'wordpress':
$instance = Brizy_Editor_Forms_WordpressIntegration::createFromJson( $json_obj );
break;
case 'smtp':
if ( class_exists( 'Brizy_Editor_Forms_SmtpIntegration' ) ) {
$instance = Brizy_Editor_Forms_SmtpIntegration::createFromJson( $json_obj );
}
break;
case 'gmail_smtp':
if ( class_exists( 'Brizy_Editor_Forms_GmailSmtpIntegration' ) ) {
$instance = Brizy_Editor_Forms_GmailSmtpIntegration::createFromJson( $json_obj );
}
break;
default:
if ( class_exists( 'Brizy_Editor_Forms_ServiceIntegration' ) ) {
$instance = Brizy_Editor_Forms_ServiceIntegration::createFromJson( $json_obj );
}
break;
}
if ( $instance ) {
$instance->setId( $json_obj->id );
if ( isset( $json_obj->completed ) ) {
$instance->setCompleted( $json_obj->completed );
}
}
add_action( 'wp_mail_failed', array( $instance, 'handleFailToSendMessage' ) );
}
return $instance;
}
/**
* @param $data
*
* @param null $instance
*
* @return Brizy_Editor_Forms_ServiceIntegration|Brizy_Editor_Forms_WordpressIntegration|void|null
*/
public static function createFromSerializedData( $data, $instance = null ) {
if ( $data instanceof Brizy_Editor_Forms_WordpressIntegration ||
$data instanceof Brizy_Editor_Forms_ServiceIntegration ) {
return $data;
}
if ( is_array( $data ) ) {
switch ( $data['id'] ) {
case 'wordpress':
$instance = Brizy_Editor_Forms_WordpressIntegration::createFromSerializedData( $data, $instance );
break;
case 'smtp':
if ( class_exists( 'Brizy_Editor_Forms_SmtpIntegration' ) ) {
$instance = Brizy_Editor_Forms_SmtpIntegration::createFromSerializedData( $data );
}
break;
case 'gmail_smtp':
if ( class_exists( 'Brizy_Editor_Forms_GmailSmtpIntegration' ) ) {
$instance = Brizy_Editor_Forms_GmailSmtpIntegration::createFromSerializedData( $data );
}
break;
default:
if ( class_exists( 'Brizy_Editor_Forms_ServiceIntegration' ) ) {
$instance = Brizy_Editor_Forms_ServiceIntegration::createFromSerializedData( $data );
}
break;
}
if ( $instance ) {
$instance->setId( $data['id'] );
$instance->setCompleted( $data['completed'] );
}
}
return $instance;
}
/**
* @return array|mixed
*/
public function convertToOptionValue() {
return $this->jsonSerialize();
}
/**
* @return string
*/
public function getId() {
return $this->id;
}
/**
* @param string $id
*
* @return Brizy_Editor_Forms_AbstractIntegration
*/
public function setId( $id ) {
$this->id = $id;
return $this;
}
/**
* @return WP_Error
*/
public function getException() {
return $this->exception;
}
public function __destruct() {
remove_action( 'wp_mail_failed', array( $this, 'handleFailToSendMessage' ) );
}
}

View File

@@ -0,0 +1,449 @@
<?php
/**
* @todo: Implement Brizy_Admin_AbstractApi here
*
* Class Brizy_Editor_Forms_Api
*/
class Brizy_Editor_Forms_Api {
const AJAX_GET_FORM = '_get_form';
const AJAX_CREATE_FORM = '_create_form';
const AJAX_UPDATE_FORM = '_update_form';
const AJAX_DELETE_FORM = '_delete_form';
const AJAX_SUBMIT_FORM = '_submit_form';
const AJAX_GET_INTEGRATION = '_get_integration';
const AJAX_CREATE_INTEGRATION = '_create_integration';
const AJAX_UPDATE_INTEGRATION = '_update_integration';
const AJAX_DELETE_INTEGRATION = '_delete_integration';
const AJAX_SET_RECAPTCHA_ACCOUNT = '_set_recaptcha_account';
const AJAX_GET_RECAPTCHA_ACCOUNT = '_get_recaptcha_account';
const AJAX_DELETE_RECAPTCHA_ACCOUNT = '_delete_recaptcha_account';
const AJAX_VALIDATE_RECAPTCHA_ACCOUNT = '_validate_recaptcha_account';
const AJAX_AUTHENTICATION_CALLBACK = '_authentication_callback';
/**
* @var Brizy_Editor_Post
*/
private $post;
/**
* @return Brizy_Editor_Post
*/
public function get_post() {
return $this->post;
}
/**
* Brizy_Editor_API constructor.
*
* @param Brizy_Editor_Post $post
*/
public function __construct( $post ) {
$this->post = $post;
$this->initialize();
}
private function initialize() {
$pref = 'wp_ajax_' . Brizy_Editor::prefix();
$pref_nopriv = 'wp_ajax_nopriv_' . Brizy_Editor::prefix();
if ( Brizy_Editor_User::is_user_allowed() ) {
add_action( $pref . self::AJAX_GET_FORM, array( $this, 'get_form' ) );
add_action( $pref . self::AJAX_CREATE_FORM, array( $this, 'create_form' ) );
add_action( $pref . self::AJAX_UPDATE_FORM, array( $this, 'update_form' ) );
add_action( $pref . self::AJAX_DELETE_FORM, array( $this, 'delete_form' ) );
add_action( $pref . self::AJAX_CREATE_INTEGRATION, array( $this, 'createIntegration' ) );
add_action( $pref . self::AJAX_GET_INTEGRATION, array( $this, 'getIntegration' ) );
add_action( $pref . self::AJAX_UPDATE_INTEGRATION, array( $this, 'updateIntegration' ) );
add_action( $pref . self::AJAX_DELETE_INTEGRATION, array( $this, 'deleteIntegration' ) );
}
add_filter( 'brizy_form_submit_data', array( $this, 'handleFileTypeFields' ), - 100, 2 );
add_action( $pref . self::AJAX_SUBMIT_FORM, array( $this, 'submit_form' ) );
add_action( $pref_nopriv . self::AJAX_SUBMIT_FORM, array( $this, 'submit_form' ) );
}
protected function error( $code, $message ) {
wp_send_json_error( array( 'code' => $code, 'message' => $message ), 200 );
}
protected function success( $data, $code = 200 ) {
wp_send_json_success( $data, $code );
}
private function authorize() {
if ( ! wp_verify_nonce( $_REQUEST['hash'], Brizy_Editor_API::nonce ) ) {
wp_send_json_error( array( 'code' => 400, 'message' => 'Bad request' ), 400 );
}
}
public function get_form() {
try {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$form = $manager->getForm( $_REQUEST['formId'] );
if ( $form ) {
$this->success( $form );
}
$this->error( 404, 'Form not found' );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), array( $exception ) );
$this->error( $exception->getCode(), $exception->getMessage() );
exit;
}
}
public function create_form() {
try {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$instance = Brizy_Editor_Forms_Form::createFromJson( json_decode( file_get_contents( 'php://input' ) ) );
$validation_result = $instance->validate();
if ( $validation_result === true ) {
$manager->addForm( $instance );
$this->success( $instance, 201 );
}
$this->error( 400, $validation_result );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), array( $exception ) );
$this->error( $exception->getCode(), $exception->getMessage() );
exit;
}
}
public function update_form() {
try {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$form_json = json_decode( file_get_contents( 'php://input' ) );
if ( ! $form_json ) {
$this->error( 400, 'Invalid json object provided' );
}
if ( ! isset( $_REQUEST['formId'] ) ) {
$this->error( 400, 'Invalid form id provided' );
}
$form = $manager->getForm( $_REQUEST['formId'] );
if ( ! $form ) {
$this->error( 404, 'Form not found' );
}
$instance = Brizy_Editor_Forms_Form::updateFromJson( $form, $form_json );
$validation_result = $instance->validate();
if ( $validation_result === true ) {
$manager->addForm( $instance );
$this->success( $instance, 200 );
}
$this->error( 400, $validation_result );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), array( $exception ) );
$this->error( $exception->getCode(), $exception->getMessage() );
exit;
}
}
public function delete_form() {
try {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$manager->deleteFormById( $_REQUEST['formId'] );
$this->success( array() );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), array( $exception ) );
$this->error( $exception->getCode(), $exception->getMessage() );
exit;
}
}
public function submit_form() {
try {
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
/**
* @var Brizy_Editor_Forms_Form $form ;
*/
$form = $manager->getForm( isset($_REQUEST['form_id'])?$_REQUEST['form_id']:null );
if ( ! $form ) {
$this->error( 404, "Form not found" );
}
$fields = json_decode( stripslashes( $_REQUEST['data'] ) );
if ( ! $fields ) {
$this->error( 400, "Invalid form data" );
}
// validtate recaptha response if exists
$accountManager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() );
$recaptchaAccounts = $accountManager->getAccountsByGroup( Brizy_Editor_Accounts_AbstractAccount::RECAPTCHA_GROUP );
if ( count( $recaptchaAccounts ) > 0 ) {
$recaptchaField = null;
foreach ( $fields as $field ) {
if ( $field->name == 'g-recaptcha-response' ) {
$recaptchaField = $field;
}
}
if ( ! $recaptchaField ) {
Brizy_Logger::instance()->error( "The submitted data is invalid." );
$this->error( 400, "The submitted data is invalid." );
}
$recaptchaAccount = $recaptchaAccounts[0];
$http = new WP_Http();
$array = array(
'secret' => $recaptchaAccount->getSecretKey(),
'response' => $recaptchaField->value
);
$response = $http->post( 'https://www.google.com/recaptcha/api/siteverify', array(
'body' => $array
)
);
$body = wp_remote_retrieve_body( $response );
$responseJsonObject = json_decode( $body );
if ( ! is_object( $responseJsonObject ) || ! $responseJsonObject->success ) {
$this->error( 400, "Unable to validation request" );
}
}
$form = apply_filters( 'brizy_form', $form );
$fields = apply_filters( 'brizy_form_submit_data', $fields, $form );
$result = null;
foreach ( $form->getIntegrations() as $integration ) {
if ( ! $integration->isCompleted() ) {
continue;
}
try {
$result = $integration->handleSubmit( $form, $fields );
} catch ( Exception $e ) {
Brizy_Logger::instance()->exception( $e );
$this->error( 500, 'Member was not created.' );
} finally {
if ( ! $result && $integration->getException() ) {
throw new Exception( $integration->getException()->get_error_message() );
}
}
}
$this->success( 200 );
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), array( $exception ) );
$this->error( 400, $exception->getMessage() );
exit;
}
}
public function handleFileTypeFields( $fields, $form ) {
foreach ( $fields as $field ) {
if ( $field->type == 'FileUpload' ) {
$uFile = $_FILES[ $field->name ];
foreach ( $_FILES[ $field->name ]['name'] as $index => $value ) {
$uFile = array(
'name' => $_FILES[ $field->name ]['name'][ $index ],
'type' => $_FILES[ $field->name ]['type'][ $index ],
'tmp_name' => $_FILES[ $field->name ]['tmp_name'][ $index ],
'error' => $_FILES[ $field->name ]['error'][ $index ],
'size' => $_FILES[ $field->name ]['size'][ $index ]
);
$uploadOverrides = array( 'test_form' => false );
$file = wp_handle_upload( $uFile, $uploadOverrides );
if ( ! $file || isset( $file['error'] ) ) {
Brizy_Logger::instance()->error( 'Failed to handle upload', $fields );
throw new Exception( 'Failed to handle upload' );
}
// create attachment
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $file['file'] ),
'post_mime_type' => $file['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file['file'] ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file['file'] );
if ( $attach_id instanceof WP_Error ) {
Brizy_Logger::instance()->critical( 'Failed to handle upload', array( $attach_id ) );
throw new Exception( 'Failed to handle upload' );
}
update_post_meta( $attach_id, 'brizy-form-upload', 1 );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
$field->value = $file['url'];
}
}
}
return $fields;
}
public function createIntegration() {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$form = $manager->getForm( $_REQUEST['formId'] );
if ( ! $form ) {
$this->error( 400, "Invalid form id" );
}
try {
$integration = Brizy_Editor_Forms_AbstractIntegration::createInstanceFromJson( json_decode( file_get_contents( 'php://input' ) ) );
if ( $form->getIntegration( $integration->getid() ) ) {
$this->error( 400, "This integration is already created" );
}
$integration = apply_filters( 'brizy_create_integration', $integration, $form );
$integration = apply_filters( 'brizy_prepare_integration', $integration, $form );
$integration = apply_filters( 'brizy_add_integration_accounts', $integration, $form );
if ( $form->addIntegration( $integration ) ) {
$manager->addForm( $form );
$this->success( $integration );
}
} catch ( Exception $exception ) {
Brizy_Logger::instance()->critical( $exception->getMessage(), array( $exception ) );
$this->error( 400, $exception->getMessage() );
}
$this->error( 500, "Unable to create integration" );
}
public function getIntegration() {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$form = $manager->getForm( $_REQUEST['formId'] );
if ( ! $form ) {
$this->error( 400, "Invalid form id" );
}
$integrationId = $_REQUEST['integration'];
if ( ! $integrationId ) {
$this->error( 400, "Invalid form integration" );
}
$integration = $form->getIntegration( $integrationId );
if ( $integration ) {
$integration = apply_filters( 'brizy_add_integration_accounts', $integration, $form );
$integration = apply_filters( 'brizy_prepare_integration', $integration, $form );
$this->success( $integration );
}
$this->error( 404, 'Integration not found' );
}
public function updateIntegration() {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$form = $manager->getForm( $_REQUEST['formId'] );
if ( ! $form ) {
$this->error( 400, "Invalid form id" );
}
$integration = Brizy_Editor_Forms_AbstractIntegration::createInstanceFromJson( json_decode( file_get_contents( 'php://input' ) ) );
$integration = apply_filters( 'brizy_update_integration', $integration, $form );
$integration = apply_filters( 'brizy_prepare_integration', $integration, $form );
//------------------
if ( $integration && $form->updateIntegration( $integration ) ) {
$manager->addForm( $form );
$this->success( $integration );
}
$this->error( 404, 'Integration not found' );
}
public function deleteIntegration() {
$this->authorize();
$manager = new Brizy_Editor_Forms_FormManager( Brizy_Editor_Project::get() );
$form = $manager->getForm( $_REQUEST['formId'] );
if ( ! $form ) {
$this->error( 400, "Invalid form id" );
}
$integrationId = $_REQUEST['integration'];
if ( ! $integrationId ) {
$this->error( 400, "Invalid form integration" );
}
$integrationId = apply_filters( 'brizy_update_integration', $integrationId, $form );
$deleted = false;
if ( $integrationId ) {
$deleted = $form->deleteIntegration( $integrationId );
}
if ( $deleted ) {
$manager->addForm( $form );
$this->success( null );
}
$this->error( 404, 'Integration not found' );
}
}

View File

@@ -0,0 +1,67 @@
<?php
trait Brizy_Editor_Forms_DynamicPropsAware {
/**
* @var string[]
*/
protected $data;
/**
* @param $name
* @param $arguments
*
* @return mixed|null
* @throws Exception
*/
public function __call( $name, $arguments ) {
$method = substr( $name, 0, 3 );
$key = substr( $name, 3 );
if ( empty( $key ) ) {
throw new Exception( 'Invalid key. You method must look like this: setKey();' );
}
switch ( $method ) {
case 'set':
return $this->set( strtolower( $key ), $arguments[0] );
break;
case 'get':
return $this->get( strtolower( $key ) );
break;
}
}
/**
* @param $name
*
* @return null|mixed
*/
protected function get( $name ) {
if ( is_null( $name ) ) {
return;
}
if ( isset( $this->data[ $name ] ) ) {
return $this->data[ $name ];
}
return null;
}
/**
* @param $key
* @param $value
*
* @return null|mixed
*/
protected function set( $key, $value ) {
if ( is_null( $value ) ) {
return null;
}
return $this->data[ $key ] = $value;
}
}

View File

@@ -0,0 +1,72 @@
<?php
class Brizy_Editor_Forms_Field extends Brizy_Admin_Serializable {
use Brizy_Editor_Forms_DynamicPropsAware;
/**
* Brizy_Editor_Forms_Field constructor.
*
* @param \BrizyForms\Model\Field|null $field
*/
public function __construct( \BrizyForms\Model\Field $field = null ) {
$this->data = array();
if ( $field ) {
$this->data = array( 'slug' => $field->getSlug(),
'name' => $field->getName(),
'required' => $field->getRequired()
);
}
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->jsonSerialize() );
}
public function unserialize( $serialized ) {
$this->data = unserialize( $serialized );
}
public function jsonSerialize() {
return $this->data;
}
public function convertToOptionValue() {
return $this->data;
}
static public function createFromSerializedData( $data ) {
$instance = new self();
foreach ( $data as $key => $val ) {
$instance->set( $key, $val );
}
return $instance;
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Forms_Field|void
* @throws Exception
*/
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
return self::createFromSerializedData( get_object_vars( $json_obj ) );
}
return new self();
}
}

View File

@@ -0,0 +1,63 @@
<?php
class Brizy_Editor_Forms_Folder extends Brizy_Admin_Serializable {
use Brizy_Editor_Forms_DynamicPropsAware;
/**
* Brizy_Editor_Forms_Folder constructor.
*
* @param \BrizyForms\Model\Folder|null $folder
*/
public function __construct( \BrizyForms\Model\Field $folder = null ) {
$this->data = array();
if ( $folder ) {
$this->data = array( 'id' => $folder->getId(), 'name' => $folder->getName() );
}
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->jsonSerialize() );
}
public function unserialize( $serialized ) {
$this->data = unserialize( $serialized );
}
public function jsonSerialize() {
return $this->data;
}
public function convertToOptionValue() {
return $this->data;
}
static public function createFromSerializedData( $data ) {
$instance = new self();
foreach ( $data as $key => $val ) {
$instance->set( $key, $val );
}
return $instance;
}
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
return self::createFromSerializedData( get_object_vars( $json_obj ) );
}
return new self();
}
}

View File

@@ -0,0 +1,105 @@
<?php
class Brizy_Editor_Forms_FormManager {
/**
* @var Brizy_Editor_Project
*/
private $project;
/**
* @var Brizy_Editor_Forms_Form[]
*/
private $forms;
/**
* Brizy_Editor_Forms_Manager constructor.
*
* @param Brizy_Editor_Project $project
*/
public function __construct( Brizy_Editor_Project $project ) {
$this->project = $project;
try {
$this->loadStorage();
} catch ( Exception $exception ) {
$this->forms = array();
}
}
/**
* @return array|Brizy_Editor_Forms_Form[]
*/
public function getAllForms() {
return $this->forms;
}
/**
* @param $form_id
*
* @return Brizy_Editor_Forms_Form
*/
public function getForm( $form_id ) {
if ( $form_id && isset($this->forms[ $form_id ])) {
return $this->forms[ $form_id ];
}
}
/**
* @param Brizy_Editor_Forms_Form $form
*/
public function addForm( $form ) {
$this->forms[ $form->getId() ] = $form;
$this->updateStorage();
}
/**
* @param Brizy_Editor_Forms_Form $form
*/
public function deleteForm( $form ) {
unset( $this->forms[ $form->getId() ] );
$this->updateStorage();
}
/**
* @param $formId
*/
public function deleteFormById( $formId ) {
unset( $this->forms[ $formId ] );
$this->updateStorage();
}
/**
* @throws Brizy_Editor_Exceptions_NotFound
*/
private function loadStorage() {
$data = $this->project->getMetaValue( 'forms' );
if ( ! $data ) {
$data = array();
}
foreach ( $data as $id => $form_data ) {
if ( $form_data instanceof Brizy_Editor_Forms_Form ) {
$this->forms[ $id ] = $form_data;
} elseif ( is_array( $form_data ) ) {
$this->forms[ $id ] = Brizy_Editor_Forms_Form::createFromSerializedData( $form_data );
}
}
}
private function updateStorage() {
$data = array();
foreach ( $this->forms as $id => $form ) {
$data[ $id ] = $form->convertToOptionValue();
}
$this->project->setMetaValue( 'forms', $data );
$this->project->saveStorage();
}
}

View File

@@ -0,0 +1,326 @@
<?php
class Brizy_Editor_Forms_Form extends Brizy_Admin_Serializable {
/**
* @var string
*/
protected $id;
/**
* @var Brizy_Editor_Forms_AbstractIntegration[]
*/
protected $integrations = array();
/**
* @var bool
*/
protected $hasEmailTemplate = false;
/**
* @var string
*/
protected $emailTemplate;
/**
* @return string
*/
public function serialize() {
return serialize( $this->convertToOptionValue() );
}
public function unserialize( $data ) {
$vars = unserialize( $data );
return self::createFromSerializedData( $vars );
}
/**
* @return array|mixed
*/
public function jsonSerialize() {
$get_object_vars = array(
'id' => $this->id,
'hasEmailTemplate' => $this->hasEmailTemplate(),
'emailTemplate' => $this->getEmailTemplate(),
'integrations' => array()
);
foreach ( $this->integrations as $integration ) {
$get_object_vars['integrations'][] = $integration->convertToOptionValue();
}
return $get_object_vars;
}
public function convertToOptionValue() {
$get_object_vars = array(
'id' => $this->id,
'hasEmailTemplate' => $this->hasEmailTemplate(),
'emailTemplate' => $this->getEmailTemplate(),
'integrations' => array()
);
foreach ( $this->integrations as $integration ) {
$get_object_vars['integrations'][] = $integration->convertToOptionValue();
}
return $get_object_vars;
}
static public function createFromSerializedData( $data ) {
$instance = new self();
$instance->id = $data['id'];
$instance->hasEmailTemplate = $data['hasEmailTemplate'];
$instance->emailTemplate = $data['emailTemplate'];
foreach ( $data['integrations'] as $integration ) {
$brizy_editor_forms_wordpress_integration = Brizy_Editor_Forms_AbstractIntegration::createFromSerializedData( $integration );
if ( $brizy_editor_forms_wordpress_integration ) {
$instance->integrations[] = $brizy_editor_forms_wordpress_integration;
}
}
return $instance;
}
/**
* @return string
*/
public function getId() {
return $this->id;
}
/**
* @param string $id
*
* @return Brizy_Editor_Forms_Form
*/
public function setId( $id ) {
$this->id = $id;
return $this;
}
/**
* @return Brizy_Editor_Forms_Form
* @throws Exception
*/
public static function createFromJson( $json_obj ) {
$formInstance = new self();
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
$formInstance->setId( $json_obj->id );
// add uncompleted wordpress integration
$current_user = wp_get_current_user();
$an_integration = new Brizy_Editor_Forms_WordpressIntegration();
$an_integration->setEmailTo( $current_user->user_email );
$formInstance->addIntegration( $an_integration );
if ( ! empty( $json_obj->integrations ) ) {
foreach ( (array) $json_obj->integrations as $integration ) {
if ( is_object( $integration ) ) {
$formInstance->addIntegration( Brizy_Editor_Forms_AbstractIntegration::createInstanceFromJson( $integration ) );
}
}
}
}
return $formInstance;
}
/**
* @param Brizy_Editor_Forms_Form $instance
* @param $json_obj
*
* @return Brizy_Editor_Forms_Form
* @throws Exception
*/
public static function updateFromJson( Brizy_Editor_Forms_Form $instance, $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
$instance->setHasEmailTemplate( $json_obj->hasEmailTemplate );
if ( $json_obj->hasEmailTemplate ) {
$instance->setEmailTemplate( $json_obj->emailTemplate );
} else {
$instance->setEmailTemplate( '' );
}
}
return $instance;
}
/**
* Target can be: create | update
*
* @param string $target
*
* @return array|bool
*/
public function validate( $target = 'create' ) {
$errors = array();
if ( ! $this->getId() ) {
$errors['id'] = 'Invalid form id';
}
if ( $this->hasEmailTemplate && $this->getEmailTemplate() == '' ) {
$errors['emailTemplate'] = 'Invalid email template content';
}
if ( count( $errors ) ) {
return $errors;
}
return true;
}
public function getIntegrations() {
return $this->integrations;
}
/**
* @param $id
*
* @return Brizy_Editor_Forms_AbstractIntegration|null
*/
public function getIntegration( $id ) {
foreach ( $this->integrations as $integration ) {
if ( $integration->getId() == $id ) {
return $integration;
}
}
return null;
}
public function addIntegration( Brizy_Editor_Forms_AbstractIntegration $anIntegration ) {
if ( ! $anIntegration ) {
return false;
}
if ( $this->getIntegration( $anIntegration->getId() ) ) {
return false;
}
$this->integrations[] = $anIntegration;
return true;
}
/**+
* @param $anIntegration
*
* @return bool
*/
public function updateIntegration( Brizy_Editor_Forms_AbstractIntegration $anIntegration ) {
if ( ! $anIntegration ) {
return false;
}
foreach ( $this->integrations as $k => $integration ) {
if ( $integration->getId() == $anIntegration->getId() ) {
$this->integrations[ $k ] = $anIntegration;
return true;
}
}
return false;
}
/**
* @param $id
*
* @return bool
*/
public function deleteIntegration( $id ) {
foreach ( $this->integrations as $k => $integration ) {
if ( $integration->getId() == $id ) {
unset( $this->integrations[ $k ] );
$this->integrations = array_values( $this->integrations );
return true;
}
}
return false;
}
/**
* @return bool
*/
public function hasEmailTemplate() {
return $this->hasEmailTemplate;
}
/**
* @param bool $hasEmailTemplate
*
* @return Brizy_Editor_Forms_Form
*/
public function setHasEmailTemplate( $hasEmailTemplate ) {
$this->hasEmailTemplate = $hasEmailTemplate;
return $this;
}
/**
* @return string
*/
public function getEmailTemplate() {
return $this->emailTemplate;
}
/**
* @param string $emailTemplate
*
* @return Brizy_Editor_Forms_Form
*/
public function setEmailTemplate( $emailTemplate ) {
$this->emailTemplate = $emailTemplate;
return $this;
}
/**
* @param $fields
*
* @return string
*/
public function getEmailTemplateContent( $fields ) {
$field_string = array();
foreach ( $fields as $field ) {
$field_string[] = "{$field->label}: " . esc_html( $field->value );
}
$content = implode( '<br>', $field_string );
return $content;
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 11/20/18
* Time: 4:48 PM
*/
class Brizy_Editor_Forms_GmailSmtpIntegration extends Brizy_Editor_Forms_SmtpIntegration {
/**
* Brizy_Editor_Forms_WordpressIntegration constructor.
*/
public function __construct() {
$this->id = 'gmail_smtp';
$this->host = 'smtp.gmail.com';
$this->port = 465;
$this->encryption = 'ssl';
$this->authentication = true;
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Forms_WordpressIntegration|null
*/
public static function createFromJson( $json_obj ) {
$instance = null;
if ( is_object( $json_obj ) ) {
$instance = new self();
self::populateInstanceDataFromJson( $instance, $json_obj );
if ( isset( $json_obj->emailTo ) ) {
$instance->setEmailTo( trim( $json_obj->emailTo ) );
}
if ( isset( $json_obj->subject ) ) {
$instance->setSubject( trim( $json_obj->subject ) );
}
if ( isset( $json_obj->username ) ) {
$instance->setUsername( trim( $json_obj->username ) );
}
if ( isset( $json_obj->password ) ) {
$instance->setPassword( trim( $json_obj->password ) );
}
}
return $instance;
}
public static function createFromSerializedData( $data, $instance = null ) {
if ( is_null( $instance ) ) {
$instance = new self();
}
$instance = parent::createFromSerializedData( $data, $instance );
return $instance;
}
}

View File

@@ -0,0 +1,63 @@
<?php
class Brizy_Editor_Forms_Group extends Brizy_Admin_Serializable {
use Brizy_Editor_Forms_DynamicPropsAware;
/**
* Brizy_Editor_Forms_Group constructor.
*
* @param \BrizyForms\Model\Group|null $group
*/
public function __construct( \BrizyForms\Model\Group $group = null ) {
$this->data = array();
if ( $group ) {
$this->data = array( 'id' => $group->getId(), 'name' => $group->getName() );
}
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->jsonSerialize() );
}
public function unserialize( $serialized ) {
$this->data = unserialize( $serialized );
}
public function jsonSerialize() {
return $this->data;
}
public function convertToOptionValue() {
return $this->data;
}
static public function createFromSerializedData( $data ) {
$instance = new self();
foreach ( $data as $key => $val ) {
$instance->set( $key, $val );
}
return $instance;
}
public static function createFromJson( $json_obj ) {
if ( ! isset( $json_obj ) ) {
throw new Exception( 'Bad Request', 400 );
}
if ( is_object( $json_obj ) ) {
return self::createFromSerializedData( get_object_vars( $json_obj ) );
}
return new self();
}
}

View File

@@ -0,0 +1,479 @@
<?php
//class BrizyPro_Forms_ServiceIntegration extends Brizy_Editor_Forms_AbstractIntegration {
class Brizy_Editor_Forms_ServiceIntegration extends Brizy_Editor_Forms_AbstractIntegration {
/**
* @var array
*/
protected $accounts = array();
/**
* @var array
*/
protected $fields = array();
/**
* @var array
*/
protected $lists = array();
/**
* @var array
*/
protected $listProperties = array();
/**
* @var array
*/
protected $folders = array();
/**
* @var
*/
protected $usedAccount;
/**
* @var
*/
protected $fieldsMap = '[]';
/**
* @var
*/
protected $usedList;
/**
* @var bool
*/
protected $hasConfirmation = false;
/**
* @var bool
*/
protected $confirmationNeeded = false;
/**
* @var string
*/
protected $usedFolder;
/**
* @param $fields
*
* @return bool|mixed
* @throws Exception
*/
public function handleSubmit( Brizy_Editor_Forms_Form $form, $fields ) {
$this->exception = null;
/**
* @var \BrizyForms\Service\Service $service ;
*/
$service = \BrizyForms\ServiceFactory::getInstance( $this->getId() );
if ( ! ( $service instanceof \BrizyForms\Service\Service ) ) {
$this->error( 400, "Invalid integration service" );
}
do_action( 'brizy_submit_form', $service, $fields, $this );
}
/**
* @return array|mixed
*/
public function jsonSerialize() {
$get_object_vars = parent::jsonSerialize();
if ( ! is_null( $this->getFields() ) ) {
$get_object_vars['fields'] = $this->getFields();
}
if ( ! is_null( $this->getLists() ) ) {
$get_object_vars['lists'] = $this->getLists();
}
if ( ! is_null( $this->getListProperties() ) ) {
$get_object_vars['listProperties'] = $this->getListProperties();
}
if ( ! is_null( $this->getFolders() ) ) {
$get_object_vars['folders'] = $this->getFolders();
}
if ( ! is_null( $this->getUsedAccount() ) ) {
$get_object_vars['usedAccount'] = $this->getUsedAccount();
}
if ( ! is_null( $this->getUsedList() ) ) {
$get_object_vars['usedList'] = $this->getUsedList();
}
if ( ! is_null( $this->getUsedFolder() ) ) {
$get_object_vars['usedFolder'] = $this->getUsedFolder();
}
if ( ! is_null( $this->getFieldsMap() ) ) {
$get_object_vars['fieldsMap'] = $this->getFieldsMap();
}
if ( ! is_null( $this->getAccounts() ) ) {
$get_object_vars['accounts'] = $this->getAccounts();
}
if ( ! is_null( $this->isConfirmationNeeded() ) ) {
$get_object_vars['confirmationNeeded'] = $this->isConfirmationNeeded();
}
if ( ! is_null( $this->hasConfirmation() ) ) {
$get_object_vars['hasConfirmation'] = $this->hasConfirmation();
}
return $get_object_vars;
}
/**
* @return string
*/
public function serialize() {
$value = $this->jsonSerialize();
unset( $value['accounts'] );
unset( $value['folders'] );
unset( $value['lists'] );
unset( $value['fields'] );
unset( $value['listProperties'] );
return serialize( $value );
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Forms_ServiceIntegration|null
* @throws Exception
*/
public static function createFromJson( $json_obj ) {
$instance = null;
if ( is_object( $json_obj ) ) {
$instance = new self( $json_obj->id );
if ( isset( $json_obj->fields ) ) {
foreach ( $json_obj->fields as $field ) {
$instance->addField( Brizy_Editor_Forms_Field::createFromJson( $field ) );
}
}
if ( isset( $json_obj->lists ) ) {
foreach ( $json_obj->lists as $list ) {
if ( ! $list instanceof Brizy_Editor_Forms_Group ) {
$instance->addList( Brizy_Editor_Forms_Group::createFromJson( $list ) );
} else {
$instance->addList( $list );
}
}
}
if ( isset( $json_obj->folders ) ) {
foreach ( $json_obj->folders as $folder ) {
if ( ! $folder instanceof Brizy_Editor_Forms_Folder ) {
$instance->addFolder( Brizy_Editor_Forms_Folder::createFromJson( $folder ) );
} else {
$instance->addFolder( $folder );
}
}
}
if ( isset( $json_obj->usedAccount ) ) {
$instance->setUsedAccount( $json_obj->usedAccount );
}
if ( isset( $json_obj->usedList ) ) {
$instance->setUsedList( $json_obj->usedList );
}
if ( isset( $json_obj->usedFolder ) ) {
$instance->setUsedFolder( $json_obj->usedFolder );
}
if ( isset( $json_obj->fieldsMap ) ) {
$instance->setFieldsMap( $json_obj->fieldsMap );
}
if ( isset( $json_obj->confirmationNeeded ) ) {
$instance->setConfirmationNeeded( $json_obj->confirmationNeeded );
}
if ( isset( $json_obj->hasConfirmation ) ) {
$instance->setHasConfirmation( $json_obj->hasConfirmation );
}
}
return $instance;
}
static public function createFromSerializedData( $data, $instance = null ) {
if ( is_null( $instance ) ) {
$instance = new self( $data['id'] );
}
if ( isset( $data['completed'] ) ) {
$instance->setCompleted( $data['completed'] );
}
if ( isset( $data['usedAccount'] ) ) {
$instance->setUsedAccount( $data['usedAccount'] );
}
if ( isset( $data['usedList'] ) ) {
$instance->setUsedList( $data['usedList'] );
}
if ( isset( $data['usedFolder'] ) ) {
$instance->setUsedFolder( $data['usedFolder'] );
}
if ( isset( $data['fieldsMap'] ) ) {
if ( is_array( $data['fieldsMap'] ) ) {
$instance->setFieldsMap( json_encode( $data['fieldsMap'] ) );
} elseif ( empty( $data['fieldsMap'] ) ) {
$instance->setFieldsMap( '[]' );
} else {
$instance->setFieldsMap( $data['fieldsMap'] );
}
}
if ( isset( $data['confirmationNeeded'] ) ) {
$instance->setConfirmationNeeded( $data['confirmationNeeded'] );
}
if ( isset( $data['hasConfirmation'] ) ) {
$instance->setHasConfirmation( $data['hasConfirmation'] );
}
return $instance;
}
/**
* @param Brizy_Editor_Forms_Group $list
*/
public function addList( Brizy_Editor_Forms_Group $list ) {
$this->lists[] = $list;
}
/**
* @param Brizy_Editor_Forms_Folder $folders
*/
public function addFolder( Brizy_Editor_Forms_Folder $folders ) {
$this->folders[] = $folders;
}
/**
* @param Brizy_Editor_Forms_Field $field
*/
public function addField( Brizy_Editor_Forms_Field $field ) {
$this->fields[] = $field;
}
/**
* @return array
*/
public function getFolders() {
return $this->folders;
}
/**
* @param array $folders
*
* @return Brizy_Editor_Forms_ServiceIntegration
*/
public function setFolders( $folders ) {
$this->folders = $folders;
return $this;
}
/**
* @return array
*/
public function getFields() {
return $this->fields;
}
/**
* @param array $fields
*
* @return self
*/
public function setFields( $fields ) {
$this->fields = $fields;
return $this;
}
/**
* @return array
*/
public function getLists() {
return $this->lists;
}
/**
* @param array $lists
*
* @return self
*/
public function setLists( $lists ) {
$this->lists = $lists;
return $this;
}
/**
* @return mixed
*/
public function getUsedAccount() {
return $this->usedAccount;
}
/**
* @param mixed $usedAccount
*
* @return self
*/
public function setUsedAccount( $usedAccount ) {
$this->usedAccount = $usedAccount;
return $this;
}
/**
* @return mixed
*/
public function getUsedListObject() {
$used_account = $this->getUsedList();
foreach ( (array) $this->lists as $list ) {
$var = $list->getId();
if ( $var == $used_account ) {
return $list;
}
}
return null;
}
/**
* @return mixed
*/
public function getUsedList() {
return $this->usedList;
}
/**
* @param mixed $usedList
*
* @return self
*/
public function setUsedList( $usedList ) {
$this->usedList = $usedList;
return $this;
}
/**
* @return mixed
*/
public function getFieldsMap() {
return $this->fieldsMap;
}
/**
* @param mixed $fieldsMap
*
* @return self
*/
public function setFieldsMap( $fieldsMap ) {
$this->fieldsMap = $fieldsMap;
return $this;
}
/**
* @return array
*/
public function getAccounts() {
return $this->accounts;
}
/**
* @param array $accounts
*
* @return Brizy_Editor_Forms_ServiceIntegration
*/
public function setAccounts( $accounts ) {
$this->accounts = $accounts;
return $this;
}
/**
* @return bool
*/
public function isConfirmationNeeded() {
return (bool) $this->confirmationNeeded;
}
/**
* @param bool $confirmationNeeded
*
* @return Brizy_Editor_Forms_ServiceIntegration
*/
public function setConfirmationNeeded( $confirmationNeeded ) {
$this->confirmationNeeded = (bool) $confirmationNeeded;
return $this;
}
/**
* @return bool
*/
public function HasConfirmation() {
return $this->hasConfirmation;
}
/**
* @param bool $hasConfirmation
*
* @return Brizy_Editor_Forms_ServiceIntegration
*/
public function setHasConfirmation( $hasConfirmation ) {
$this->hasConfirmation = $hasConfirmation;
return $this;
}
/**
* @return string
*/
public function getUsedFolder() {
return $this->usedFolder;
}
/**
* @param string $usedFolder
*
* @return Brizy_Editor_Forms_ServiceIntegration
*/
public function setUsedFolder( $usedFolder ) {
$this->usedFolder = $usedFolder;
return $this;
}
/**
* @return array
*/
public function getListProperties() {
return $this->listProperties;
}
/**
* @param array $listProperties
*
* @return Brizy_Editor_Forms_ServiceIntegration
*/
public function setListProperties( $listProperties ) {
$this->listProperties = $listProperties;
return $this;
}
}

View File

@@ -0,0 +1,278 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 11/20/18
* Time: 4:48 PM
*/
class Brizy_Editor_Forms_SmtpIntegration extends Brizy_Editor_Forms_WordpressIntegration {
/**
* @var string
*/
protected $host;
/**
* @var string
*/
protected $port;
/**
* @var string
*/
protected $authentication;
/**
* @var string
*/
protected $username;
/**
* @var string
*/
protected $password;
/**
* @var string
*/
protected $encryption = 'ssl';
/**
* Brizy_Editor_Forms_WordpressIntegration constructor.
*/
public function __construct() {
$this->id = 'smtp';
}
/**
* @param Brizy_Editor_Forms_Form $form
* @param $fields
*
* @return bool|mixed
* @throws Exception
*/
public function handleSubmit( Brizy_Editor_Forms_Form $form, $fields ) {
add_action( 'phpmailer_init', array( $this, 'decoratePhpMailer' ) );
add_action( 'wp_mail_failed', array( $this, 'handleFailToSendMessage' ) );
$result = parent::handleSubmit( $form, $fields );
}
public function decoratePhpMailer( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = $this->getHost();
$phpmailer->SMTPSecure = $this->getEncryption();
$phpmailer->SMTPAuth = $this->getAuthentication();
$phpmailer->Port = $this->getPort();
$phpmailer->Username = $this->getUsername();
$phpmailer->Password = $this->getPassword();
}
/**
* @return array|mixed
*/
public function jsonSerialize() {
$get_object_vars = parent::jsonSerialize();
$get_object_vars['emailTo'] = $this->getEmailTo();
$get_object_vars['subject'] = $this->getSubject();
$get_object_vars['host'] = $this->getHost();
$get_object_vars['authentication'] = $this->getAuthentication();
$get_object_vars['port'] = $this->getPort();
$get_object_vars['username'] = $this->getUsername();
$get_object_vars['password'] = $this->getPassword();
$get_object_vars['encryption'] = $this->getEncryption();
return $get_object_vars;
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Forms_WordpressIntegration|null
*/
public static function createFromJson( $json_obj ) {
$instance = null;
if ( is_object( $json_obj ) ) {
$instance = new self();
self::populateInstanceDataFromJson( $instance, $json_obj );
if ( isset( $json_obj->host ) ) {
$instance->setHost( trim( $json_obj->host ) );
}
if ( isset( $json_obj->port ) ) {
$instance->setPort( trim( $json_obj->port ) );
}
if ( isset( $json_obj->authentication ) ) {
$instance->setAuthentication( $json_obj->authentication );
}
if ( isset( $json_obj->username ) ) {
$instance->setUsername( trim( $json_obj->username ) );
}
if ( isset( $json_obj->password ) ) {
$instance->setPassword( trim( $json_obj->password ) );
}
if ( isset( $json_obj->encryption ) ) {
$instance->setEncryption( $json_obj->encryption );
}
}
return $instance;
}
static public function createFromSerializedData( $data, $instance = null ) {
if ( is_null( $instance ) ) {
$instance = new self();
}
$instance = parent::createFromSerializedData( $data, $instance );
if ( isset( $data['host'] ) ) {
$instance->setHost( $data['host'] );
}
if ( isset( $data['port'] ) ) {
$instance->setPort( $data['port'] );
}
if ( isset( $data['username'] ) ) {
$instance->setUsername( $data['username'] );
}
if ( isset( $data['password'] ) ) {
$instance->setPassword( $data['password'] );
}
if ( isset( $data['encryption'] ) ) {
$instance->setEncryption( $data['encryption'] );
}
if ( isset( $data['authentication'] ) ) {
$instance->setAuthentication( $data['authentication'] );
}
return $instance;
}
/**
* @return string
*/
public function getHost() {
return $this->host;
}
/**
* @param string $host
*
* @return Brizy_Editor_Forms_SmtpIntegration
*/
public function setHost( $host ) {
$this->host = $host;
return $this;
}
/**
* @return string
*/
public function getPort() {
return $this->port;
}
/**
* @param string $port
*
* @return Brizy_Editor_Forms_SmtpIntegration
*/
public function setPort( $port ) {
$this->port = $port;
return $this;
}
/**
* @return string
*/
public function getAuthentication() {
return $this->authentication;
}
/**
* @param string $authentication
*
* @return Brizy_Editor_Forms_SmtpIntegration
*/
public function setAuthentication( $authentication ) {
$this->authentication = (bool)$authentication;
return $this;
}
/**
* @return string
*/
public function getUsername() {
return $this->username;
}
/**
* @param string $username
*
* @return Brizy_Editor_Forms_SmtpIntegration
*/
public function setUsername( $username ) {
$this->username = $username;
return $this;
}
/**
* @return string
*/
public function getPassword() {
return $this->password;
}
/**
* @param string $password
*
* @return Brizy_Editor_Forms_SmtpIntegration
*/
public function setPassword( $password ) {
$this->password = $password;
return $this;
}
/**
* @return string
*/
public function getEncryption() {
return $this->encryption;
}
/**
* @param string $encryption
*
* @return Brizy_Editor_Forms_SmtpIntegration
*/
public function setEncryption( $encryption ) {
//this is a hack because we had bool values on this property
if ( is_bool( $encryption ) ) {
$this->encryption = $encryption ? 'ssl' : 'tls';
} else {
$this->encryption = $encryption;
}
return $this;
}
}

View File

@@ -0,0 +1,424 @@
<?php
class Brizy_Editor_Forms_WordpressIntegration extends Brizy_Editor_Forms_AbstractIntegration {
/**
* @var string
*/
protected $emailTo;
/**
* @var string
*/
protected $subject;
/**
* @var string
*/
protected $fromEmail;
/**
* @var string
*/
protected $fromName;
/**
* @var string
*/
protected $replayTo;
/**
* @var string
*/
protected $cc;
/**
* @var string
*/
protected $bcc;
/**
* @var string
*/
protected $metaData;
/**
* Brizy_Editor_Forms_WordpressIntegration constructor.
*/
public function __construct() {
parent::__construct( 'wordpress' );
}
/**
* @param Brizy_Editor_Forms_Form $form
* @param $fields
*
* @return bool|mixed
* @throws Exception
*/
public function handleSubmit( Brizy_Editor_Forms_Form $form, $fields ) {
$this->exception = null;
///$recipients = explode( ',', $this->getEmailTo() );
$headers = array();
$headers[] = 'Content-type: text/html; charset=UTF-8';
if ( $this->getCc() ) {
$headers[] = "Cc: {$this->getCc()}";
}
if ( $this->getBcc() ) {
$headers[] = "Bcc: {$this->getBcc()}";
}
if ( $this->getReplayTo() ) {
$headers[] = "Reply-To: {$this->getReplayTo()}";
}
if ( $this->getFromEmail() ) {
$fromName = '';
if ( $this->getFromName() ) {
$headers[] = "From: \"{$this->getFromName()}\" <{$this->getFromEmail()}>";
} else {
$headers[] = "From: {$this->getFromEmail()}";
}
}
// $field_string = array();
// foreach ( $fields as $field ) {
// $field_string[] = "{$field->label}: " . esc_html( $field->value );
// }
$email_body = $form->getEmailTemplateContent( $fields );
$headers = apply_filters( 'brizy_form_email_headers', $headers, $fields, $form );
$email_body = apply_filters( 'brizy_form_email_body', $email_body, $fields, $form );
$email_subject = apply_filters( 'brizy_form_email_subject', $this->getSubject(), $fields, $form );
$email_body = $this->insertMetaDataFields( $email_body );
if ( ! function_exists( 'wp_mail' ) ) {
throw new Exception( 'Please check your wordpress configuration.' );
}
return wp_mail(
$this->getEmailTo(),
$email_subject,
$email_body,
$headers
);
}
/**
* @return array|mixed
*/
public function jsonSerialize() {
$get_object_vars = parent::jsonSerialize();
$get_object_vars['emailTo'] = $this->getEmailTo();
$get_object_vars['subject'] = $this->getSubject();
$get_object_vars['fromEmail'] = $this->getFromEmail();
$get_object_vars['fromName'] = $this->getFromName();
$get_object_vars['replayTo'] = $this->getReplayTo();
$get_object_vars['cc'] = $this->getCc();
$get_object_vars['bcc'] = $this->getBcc();
$get_object_vars['metaData'] = $this->getMetaData();
return $get_object_vars;
}
static public function createFromSerializedData( $data, $instance = null ) {
if ( is_null( $instance ) ) {
$instance = new self();
}
if ( isset( $data['completed'] ) ) {
$instance->setCompleted( $data['completed'] );
}
if ( isset( $data['emailTo'] ) ) {
$instance->setEmailTo( $data['emailTo'] );
}
if ( isset( $data['subject'] ) ) {
$instance->setSubject( $data['subject'] );
}
if ( isset( $data['fromEmail'] ) ) {
$instance->setFromEmail( $data['fromEmail'] );
}
if ( isset( $data['fromName'] ) ) {
$instance->setFromName( $data['fromName'] );
}
if ( isset( $data['replayTo'] ) ) {
$instance->setReplayTo( $data['replayTo'] );
}
if ( isset( $data['cc'] ) ) {
$instance->setCc( $data['cc'] );
}
if ( isset( $data['bcc'] ) ) {
$instance->setBcc( $data['bcc'] );
}
if ( isset( $data['metaData'] ) ) {
$instance->setMetaData( $data['metaData'] );
}
return $instance;
}
/**
* @return string
*/
public function serialize() {
return serialize( $this->jsonSerialize() );
}
/**
* @return string
*/
public function getEmailTo() {
return $this->emailTo;
}
/**
* @param string $emailTo
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setEmailTo( $emailTo ) {
$this->emailTo = $emailTo;
return $this;
}
/**
* @return string
*/
public function getSubject() {
return $this->subject;
}
/**
* @param string $subject
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setSubject( $subject ) {
$this->subject = $subject;
return $this;
}
/**
* @return string
*/
public function getFromEmail() {
return $this->fromEmail;
}
/**
* @param string $fromEmail
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setFromEmail( $fromEmail ) {
$this->fromEmail = $fromEmail;
return $this;
}
/**
* @return string
*/
public function getFromName() {
return $this->fromName;
}
/**
* @param string $fromName
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setFromName( $fromName ) {
$this->fromName = $fromName;
return $this;
}
/**
* @return string
*/
public function getReplayTo() {
return $this->replayTo;
}
/**
* @param string $replayTo
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setReplayTo( $replayTo ) {
$this->replayTo = $replayTo;
return $this;
}
/**
* @return string
*/
public function getCc() {
return $this->cc;
}
/**
* @param string $cc
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setCc( $cc ) {
$this->cc = $cc;
return $this;
}
/**
* @return string
*/
public function getBcc() {
return $this->bcc;
}
/**
* @param string $bcc
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setBcc( $bcc ) {
$this->bcc = $bcc;
return $this;
}
/**
* @return string
*/
public function getMetaData() {
return $this->metaData;
}
/**
* @param string $metaData
*
* @return Brizy_Editor_Forms_WordpressIntegration
*/
public function setMetaData( $metaData ) {
$this->metaData = $metaData;
return $this;
}
/**
* @param $json_obj
*
* @return Brizy_Editor_Forms_WordpressIntegration|null
*/
public static function createFromJson( $json_obj ) {
$instance = null;
if ( is_object( $json_obj ) ) {
$instance = new self();
self::populateInstanceDataFromJson( $instance, $json_obj );
}
return $instance;
}
private function insertMetaDataFields( $emailBody ) {
$metaFields = explode( ',', $this->getMetaData() );
$tests = array();
foreach ( $metaFields as $meta ) {
switch ( $meta ) {
case 'time':
$tests[] = 'Time: ' . date( 'Y-m-d H:i:s' );
break;
case 'pageUrl':
$tests[] = 'Page Url: ' . $_SERVER['HTTP_REFERER'];
break;
case 'userAgent':
$tests[] = 'User Agent: ' . $_SERVER['HTTP_USER_AGENT'];
break;
case 'remoteIp':
$ip = $_SERVER['REMOTE_ADDR'];
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
$tests[] = 'Remote IP: ' . $ip;
break;
case 'credit':
$tests[] = 'Powered by : ' . __bt( 'brizy', 'Brizy' );
break;
}
}
$tests = implode( '<br>', $tests );
return $emailBody . "<br>-------------------------<br>" . $tests;
}
protected static function populateInstanceDataFromJson( $instance, $json_obj ) {
if ( is_object( $json_obj ) ) {
if ( isset( $json_obj->emailTo ) ) {
$instance->setEmailTo( trim( $json_obj->emailTo ) );
} else {
// set the default email
$current_user = wp_get_current_user();
$instance->setEmailTo( $current_user->user_email );;
}
if ( isset( $json_obj->subject ) ) {
$instance->setSubject( trim( $json_obj->subject ) );
}
if ( isset( $json_obj->fromEmail ) ) {
$instance->setFromEmail( trim( $json_obj->fromEmail ) );
}
if ( isset( $json_obj->fromName ) ) {
$instance->setFromName( trim( $json_obj->fromName ) );
}
if ( isset( $json_obj->replayTo ) ) {
$instance->setReplayTo( trim( $json_obj->replayTo ) );
}
if ( isset( $json_obj->cc ) ) {
$instance->setCc( trim( $json_obj->cc ) );
}
if ( isset( $json_obj->bcc ) ) {
$instance->setBcc( trim( $json_obj->bcc ) );
}
if ( isset( $json_obj->metaData ) ) {
$instance->setMetaData( trim( $json_obj->metaData ) );
}
}
return $instance;
}
}

View File

@@ -0,0 +1,129 @@
<?php
class Brizy_Editor_Helper_DomTag {
/**
* @var string
*/
private $html_tag;
/**
* Brizy_DOM_Tag constructor.
*
* @param string $tag
*/
public function __construct( $tag ) {
$this->html_tag = trim( $tag );
}
/**
* @return string
*/
public function get_tag() {
return $this->html_tag;
}
/**
* @param $name
*
* @return null
*/
public function get_attr( $name ) {
preg_match( "/$name\s*=\s*\"([^\"]*)\"/i", $this->get_tag(), $res );
if ( isset( $res[1] ) ) {
return $res[1];
}
return null;
}
/**
* @return array
*/
public function get_attrs() {
$res = array();
preg_match_all( "/(\S+)=(?:\"(.[^\"]*)\")/", $this->get_tag(), $res );
$l = count( $res[0] );
$attrs = array();
for ( $i = 0; $i < $l; $i ++ ) {
$attrs[ $res[1][ $i ] ] = $res[2][ $i ];
}
return $attrs;
}
/**
* @return string
*/
public function get_content() {
$res = preg_match( "/\/>$/i", $this->get_tag() );
if ( $res === 1 ) {
return '';
}
$html = $this->get_tag();
$start = strpos( $html, ">" )+1;
$end = strrpos( $html, "<" );
return substr($html,$start,$end-$start);
}
/**
* @param $pattern
*
* @return Brizy_Editor_Helper_DomTag[]
*/
public function get_tags( $pattern ) {
$tags = array();
preg_match_all( $pattern, $this->get_tag(), $matches );
foreach ( $matches[0] as $value ) {
$tags[] = new Brizy_Editor_Helper_DomTag( $value );
}
return $tags;
}
/**
* @return Brizy_Editor_Helper_DomTag[]
*/
public function get_links() {
return $this->get_tags( '/(<link[^>]+>)/is' );
}
/**
* @param $rel_value
*
* @return Brizy_Editor_Helper_DomTag[]
*/
public function get_links_by_rel( $rel_value ) {
return $this->get_tags( "/(<link\s+(?=[^>]*rel=\"{$rel_value}\").[^>]*>)/is" );
}
/**
* @return Brizy_Editor_Helper_DomTag[]
*/
public function get_scripts() {
return $this->get_tags( '/(<script(.*?)<\/script>)/is' );
}
/**
* @return Brizy_Editor_Helper_DomTag[]
*/
public function get_styles() {
return $this->get_tags( '/(<style(.*?)<\/style>)/is' );
}
}

View File

@@ -0,0 +1,62 @@
<?php
class Brizy_Editor_Helper_Dom extends Brizy_Editor_Helper_DomTag {
/**
* @return Brizy_Editor_Helper_DomTag
*/
public function get_head() {
$headPos = strpos( $this->get_html(), "<head" );
$headEndPos = strpos( $this->get_html(), "</head>" );
$headString = substr( $this->get_html(), $headPos, $headEndPos - $headPos + 7 );
return new Brizy_Editor_Helper_DomTag( $headString );
}
/**
* @return $this|Brizy_Editor_Helper_DomTag
*/
public function get_body() {
$bodyPos = strpos( $this->get_html(), "<body" );
$bodyEndPos = strpos( $this->get_html(), "</body>" );
$bodyString = substr( $this->get_html(), $bodyPos, $bodyEndPos - $bodyPos + 7 );
return new Brizy_Editor_Helper_DomTag( $bodyString );
}
/**
* Return the tag html
*
* @return string
*/
protected function get_html() {
return $this->get_tag();
}
/**
* @todo: Move this somewhere else..
*
* @param array $tags
* @param $attr
*
* @return array
*/
public function get_attributes( $tags, $attr ) {
$list = array();
foreach ( $tags as $tag ) {
$link = trim( $tag->get_attr( $attr ) );
if ( empty( $link ) ) {
continue;
}
$list[] = $link;
}
return $list;
}
}

View File

@@ -0,0 +1,30 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Helper_PostStatic {
private $html;
public function __construct( $html ) {
$this->html = $html;
}
public function save_path() {
static $path;
return $path ? $path : $path = $this->uploads_dir() . DIRECTORY_SEPARATOR . self::DIR;
}
private function uploads_dir() {
$upload_dir = Brizy_Admin_UploadDir::getUploadDir();
return $upload_dir['baseurl'];
}
private function dom() {
static $dom;
return $dom ? $dom : $dom = new Brizy_Editor_Helper_Dom( $this->html );
}
}

View File

@@ -0,0 +1,181 @@
<?php
class Brizy_Editor_Http_Client {
/**
* @var WP_Http
*/
private $http;
/**
* Brizy_Editor_Http_Client constructor.
*
* @param null $http
*/
public function __construct( $http = null ) {
if ( is_null( $http ) ) {
$this->http = new WP_Http();
} else {
$this->http = $http;
}
add_filter( 'http_request_args', array( $this, 'sendExpect' ) );
}
/**
* @param $r
*
* @return mixed
*/
public function sendExpect( $r ) {
$r['headers']['Expect'] = '';
return $r;
}
/**
* @param $url
* @param array $options
* @param string $method
*
* @return Brizy_Editor_Http_Response
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function request( $url, $options = array(), $method = 'GET' ) {
$options['method'] = $method;
$options['timeout'] = Brizy_Config::WP_HTTP_TIMEOUT;
$options = $this->prepare_options( $options );
$response = null;
if ( is_string( $url ) ) {
Brizy_Logger::instance()->notice( "{$method} request to {$url}", array( 'options' => $options ) );
$wp_response = $this->getHttp()->request( $url, $options );
if ( is_wp_error( $wp_response ) ) {
throw new Brizy_Editor_API_Exceptions_Exception( $wp_response->get_error_message() );
}
$response = new Brizy_Editor_Http_Response( $wp_response );
} else {
foreach ( $url as $aurl ) {
$wp_response = $this->getHttp()->request( $aurl, $options );
$response = new Brizy_Editor_Http_Response( $wp_response );
if ( is_wp_error( $wp_response ) || ! $response->is_ok() ) {
continue;
} else {
break;
}
}
}
if ( $response && $response->is_ok() ) {
return $response;
}
switch ( $response->get_status_code() ) {
case 400 :
throw new Brizy_Editor_Http_Exceptions_BadRequest( $response );
case 401 :
throw new Brizy_Editor_Http_Exceptions_ResponseUnauthorized( $response );
case 404 :
throw new Brizy_Editor_Http_Exceptions_ResponseNotFound( $response );
default :
throw new Brizy_Editor_Http_Exceptions_ResponseException( $response );
}
}
/**
* @param $url
* @param array $options
*
* @return Brizy_Editor_Http_Response
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function get( $url, $options = array() ) {
return $this->request( $url, $options, 'GET' );
}
/**
* @param $url
* @param $options
*
* @return Brizy_Editor_Http_Response
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function post( $url, $options ) {
return $this->request( $url, $options, 'POST' );
}
/**
* @param $route
* @param null $options
*
* @return Brizy_Editor_Http_Response
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function put( $route, $options = null ) {
return $this->request( $route, $options, 'PUT' );
}
/**
* @param $route
* @param null $options
*
* @return Brizy_Editor_Http_Response
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
*/
public function delete( $route, $options = null ) {
return $this->request( $route, $options, 'DELETE' );
}
/**
* @return WP_Http
*/
public function getHttp() {
return $this->http;
}
/**
* @param $options
*
* @return array
*/
protected function prepare_options( $options ) {
if ( ! is_array( $options ) ) {
$options = array();
}
if ( ! isset( $options['headers'] ) ) {
$options['headers'] = array();
}
return $options;
}
}

View File

@@ -0,0 +1,5 @@
<?php
class Brizy_Editor_Http_Exceptions_BadRequest extends Brizy_Editor_Http_Exceptions_ResponseException {
}

View File

@@ -0,0 +1,17 @@
<?php
class Brizy_Editor_Http_Exceptions_ResponseException extends Brizy_Editor_API_Exceptions_Exception {
/**
* @var Brizy_Editor_Http_Response
*/
private $response;
public function __construct( $response, $previous = null ) {
$this->response = $response;
parent::__construct( $response->get_message(), $response->get_status_code(), $previous );
}
public function getResponse() {
return $this->response;
}
}

View File

@@ -0,0 +1,5 @@
<?php
class Brizy_Editor_Http_Exceptions_ResponseNotFound extends Brizy_Editor_Http_Exceptions_ResponseException {
}

View File

@@ -0,0 +1,5 @@
<?php
class Brizy_Editor_Http_Exceptions_ResponseUnauthorized extends Brizy_Editor_Http_Exceptions_ResponseException {
}

View File

@@ -0,0 +1,45 @@
<?php
class Brizy_Editor_Http_Response {
private $response;
public function __construct( $wp_response ) {
$this->response = $wp_response;
}
/**
* @return int
*/
public function get_status_code() {
$code = wp_remote_retrieve_response_code( $this->response );
return $code ? $code : 500;
}
/**
* @return array|mixed|object
*/
public function get_response_body() {
return json_decode( wp_remote_retrieve_body( $this->response ), true );
}
/**
* @return string
*/
public function get_message() {
return (string) wp_remote_retrieve_response_message( $this->response );
}
public function get_headers() {
return wp_remote_retrieve_headers( $this->response );
}
public function get_header( $header ) {
return wp_remote_retrieve_header( $this->response, $header );
}
public function is_ok() {
return $this->get_status_code() >= 200 && $this->get_status_code() < 300;
}
}

View File

@@ -0,0 +1,250 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/18/19
* Time: 12:20 PM
*/
class Brizy_Editor_Layout extends Brizy_Editor_Post {
use Brizy_Editor_Synchronizable;
const BRIZY_LAYOUT_META = 'brizy-meta';
const BRIZY_LAYOUT_MEDIA = 'brizy-media';
/**
* @var string
*/
protected $meta = '';
/**
* @var string
*/
protected $media;
/**
* @var Brizy_Editor_Layout
*/
static protected $layout_instance = null;
/**
* @param $apost
* @param null $uid
*
* @return Brizy_Editor_Layout|Brizy_Editor_Post|mixed
* @throws Exception
*/
public static function get( $apost, $uid = null ) {
$wp_post_id = $apost;
if ( $apost instanceof WP_Post ) {
$wp_post_id = $apost->ID;
}
if ( isset( self::$layout_instance[ $wp_post_id ] ) ) {
return self::$layout_instance[ $wp_post_id ];
}
return self::$layout_instance[ $wp_post_id ] = new self( $wp_post_id, $uid );
}
protected function canBeSynchronized() {
return true;
}
public function createResponse( $fields = array() ) {
if ( empty( $fields ) ) {
$fields = array(
'id',
'uid',
'meta',
'data',
'status',
'dataVersion',
'synchronized',
'synchronizable',
'isCloudEntity'
);
}
$global = array();
if ( in_array( 'uid', $fields ) ) {
$global['uid'] = $this->getUid();
}
if ( in_array( 'status', $fields ) ) {
$global['status'] = get_post_status( $this->getWpPostId() );
}
if ( in_array( 'dataVersion', $fields ) ) {
$global['dataVersion'] = $this->getCurrentDataVersion();
}
if ( in_array( 'data', $fields ) ) {
$global['data'] = $this->get_editor_data();
}
if ( in_array( 'meta', $fields ) ) {
$global['meta'] = $this->getMeta();
}
if ( in_array( 'synchronized', $fields ) ) {
$global['synchronized'] = $this->isSynchronized( Brizy_Editor_Project::get()->getCloudAccountId() );
}
if ( in_array( 'synchronizable', $fields ) ) {
$global['synchronizable'] = $this->isSynchronizable( Brizy_Editor_Project::get()->getCloudAccountId() );
}
if ( in_array( 'isCloudEntity', $fields ) ) {
$global['isCloudEntity'] = false;
}
return $global;
}
/**
* Brizy_Editor_Layout constructor.
*
* @param $wp_post_id
* @param null $uid
*
* @throws Exception
*/
public function __construct( $wp_post_id, $uid = null ) {
if ( $uid ) {
$this->uid = $uid;
}
parent::__construct( $wp_post_id );
}
/**
* @return bool
*/
public function uses_editor() {
return true;
}
/**
* This should always return true
*
* @param $val
*
* @return $this
*/
public function set_uses_editor( $val ) {
parent::set_uses_editor(true);
return $this;
}
/**
* @return array
*/
public function getMeta() {
return $this->meta;
}
/**
* @param string $meta
*
* @return Brizy_Editor_Block
*/
public function setMeta( $meta ) {
$this->meta = $meta;
return $this;
}
public function getMedia() {
return $this->media;
}
/**
* @param string $media
*
* @return Brizy_Editor_Block
*/
public function setMedia( $media ) {
$this->media = $media;
return $this;
}
/**
* @return mixed
*/
public function get_template() {
return get_post_meta( $this->getWpPostId(), '_wp_page_template', true );
}
/**
* @param string $editor_version
*/
public function set_editor_version( $editor_version ) {
$this->editor_version = $editor_version;
update_metadata( 'post', $this->wp_post_id, self::BRIZY_POST_EDITOR_VERSION, $editor_version );
}
public function jsonSerialize() {
$data = get_object_vars( $this );
$data['editor_data'] = base64_decode( $data['editor_data'] );
$data['meta'] = $this->getMeta();
//$data['cloudId'] = $this->getCloudId();
//$data['cloudAccountId'] = $this->getCloudAccountId();
$data['media'] = $this->getMedia();
unset( $data['wp_post'] );
return $data;
}
public function loadInstanceData() {
parent::loadInstanceData();
$storage = $this->getStorage();
$storage_post = $storage->get( self::BRIZY_POST, false );
// load synchronisation data
$this->loadSynchronizationData();
// back compatibility with old sync data
if ( isset( $storage_post['cloudId'] ) && isset( $storage_post['cloudAccountId'] ) ) {
$this->setSynchronized( $storage_post['cloudAccountId'], $storage_post['cloudId'] );
}
$this->meta = get_metadata( 'post', $this->getWpPostId(), self::BRIZY_LAYOUT_META, true );
$this->media = get_metadata( 'post', $this->getWpPostId(), self::BRIZY_LAYOUT_MEDIA, true );
}
public function convertToOptionValue() {
$data = parent::convertToOptionValue();
$data['media'] = $this->getMedia();
//$data['cloudId'] = $this->getCloudId();
//$data['cloudAccountId'] = $this->getCloudAccountId();
$data['synchronized'] = $this->isSynchronized( Brizy_Editor_Project::get()->getCloudAccountId() );
$data['synchronizable'] = $this->isSynchronizable( Brizy_Editor_Project::get()->getCloudAccountId() );
return $data;
}
/**
* This will take all values from entity and save them to database
*/
public function saveStorage() {
parent::saveStorage();
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_LAYOUT_META, $this->meta );
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_LAYOUT_MEDIA, $this->media );
}
}

View File

@@ -0,0 +1,85 @@
<?php
class Brizy_Editor_Multipass {
private $signature_key;
private $encryption_key;
private $init_vector;
public function __construct($secret_key)
{
$key_material = hash("SHA256", $secret_key, true);
$this->encryption_key = substr($key_material, 0, 16);
$this->signature_key = substr($key_material, 16, 16);
$iv_material = hash("SHA256", $this->encryption_key, true);
$this->init_vector = substr($iv_material, 0, 16);
}
/**
* Converts and signs a PHP object or array into a JWT string.
*
* @param object|array $payload PHP object or array
*
* @return string A signed JWT
*
* @uses jsonEncode
* @uses urlsafeB64Encode
*/
public function encode($payload)
{
$segments = array();
$segments[] = $this->urlsafeB64Encode($this->encrypt(json_encode($payload), $this->encryption_key, $this->init_vector));
$signing_input = implode('.', $segments);
$signature = $this->sign($signing_input, $this->signature_key);
$segments[] = $this->urlsafeB64Encode($signature);
return implode('.', $segments);
}
/**
* Sign a string with a given key and algorithm.
*
* @param string $msg The message to sign
* @param string|resource $key The secret key
*
* @return string An encrypted message
*
*/
private function sign($msg, $key)
{
return hash_hmac('SHA256', $msg, $key, true);
}
/**
* Encode a string with URL-safe Base64.
*
* @param string $input The string you want encoded
*
* @return string The base64 encode of what you passed in
*/
private function urlsafeB64Encode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
/**
* Encrypt a string with AES-128-CBC
*
* @param string $json_payload The data
* @param string $encryption_key The secret encryption key
* @param string $init_vector A non-NULL Initialization Vector
*
* @return string An encrypted data
*/
private function encrypt($json_payload, $encryption_key, $init_vector)
{
return openssl_encrypt($json_payload, 'AES-128-CBC' , $encryption_key, OPENSSL_RAW_DATA, $init_vector);
}
}

View File

@@ -0,0 +1,267 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/18/19
* Time: 12:20 PM
*/
class Brizy_Editor_Popup extends Brizy_Editor_Post {
const BRIZY_META = 'brizy-meta';
const BRIZY_MEDIA = 'brizy-media';
const BRIZY_CLOUD_CONTAINER = 'brizy-cloud-container';
const BRIZY_CLOUD_UPDATE_META = 'brizy-cloud-update-required';
/**
* @var string
*/
protected $meta = '';
/**
* @var string
*/
protected $media;
/**
* @var array
*/
protected $cloudId;
/**
* @var Brizy_Editor_Popup
*/
static protected $popup_instance = null;
/**
* @param $apost
*
* @return Brizy_Editor_Popup
* @throws Brizy_Editor_Exceptions_NotFound
*/
public static function get( $apost, $uid = null ) {
$wp_post_id = $apost;
if ( $apost instanceof WP_Post ) {
$wp_post_id = $apost->ID;
}
if ( isset( self::$popup_instance[ $wp_post_id ] ) ) {
return self::$popup_instance[ $wp_post_id ];
}
return self::$popup_instance[ $wp_post_id ] = new self( $wp_post_id, $uid );
}
/**
* @return bool
* @todo rename this to isGlobal
*
*/
public function isGlobalPopup() {
return $this->getWpPost() instanceof WP_Post && $this->getWpPost()->post_type == Brizy_Admin_Popups_Main::CP_GLOBAL_POPUP;
}
public function isSavedPopup() {
return $this->getWpPost() instanceof WP_Post && $this->getWpPost()->post_type == Brizy_Admin_Popups_Main::CP_POPUP;
}
/**
* @return bool
*/
public function isCloudUpdateRequired() {
if ( $this->isGlobalPopup() ) {
return false;
}
return (bool) get_metadata( 'post', $this->wp_post_id, self::BRIZY_CLOUD_UPDATE_META, true );
}
/**
* @param bool $cloudUpdateRequired
*
* @return Brizy_Editor_Popup
*/
public function setCloudUpdateRequired( $cloudUpdateRequired ) {
if ( $this->isSavedPopup() ) {
update_metadata( 'post', $this->wp_post_id, self::BRIZY_CLOUD_UPDATE_META, (int) $cloudUpdateRequired );
}
return $this;
}
/**
* @param string $meta
*/
public function setContainer( $meta ) {
$this->meta = $meta;
update_metadata( 'post', $this->wp_post_id, self::BRIZY_CLOUD_CONTAINER, $meta );
}
public function getContainer() {
return get_metadata( 'post', $this->wp_post_id, self::BRIZY_CLOUD_CONTAINER, true );
}
/**
* @return array
*/
public function getMeta() {
return get_metadata( 'post', $this->wp_post_id, self::BRIZY_META, true );
}
/**
* @param string $meta
*
* @return Brizy_Editor_Popup
*/
public function setMeta( $meta ) {
$this->meta = $meta;
update_metadata( 'post', $this->wp_post_id, self::BRIZY_META, $meta );
}
public function getMedia() {
return get_metadata( 'post', $this->wp_post_id, self::BRIZY_MEDIA, true );
}
/**
* @param string $media
*
* @return Brizy_Editor_Popup
*/
public function setMedia( $media ) {
$this->media = $media;
update_metadata( 'post', $this->wp_post_id, self::BRIZY_MEDIA, $media );
}
/**
* @return mixed
*/
public function get_template() {
return get_post_meta( $this->getWpPostId(), '_wp_page_template', true );
}
/**
* @return array
*/
public function getCloudId() {
return $this->cloudId;
}
/**
* @param array $cloudId
*
* @return Brizy_Editor_Popup
*/
public function setCloudId( $cloudId ) {
$this->cloudId = $cloudId;
return $this;
}
public function jsonSerialize() {
$data = get_object_vars( $this );
$data['editor_data'] = base64_decode( $data['editor_data'] );
$data['cloudId'] = $this->getCloudId();
$data['meta'] = $this->getMeta();
unset( $data['wp_post'] );
return $data;
}
/**
* @param $data
*/
public function loadInstanceData() {
parent::loadInstanceData();
$storage = $this->getStorage();
$data = $storage->get( self::BRIZY_POST, false );
if ( isset( $data['cloudId'] ) ) {
$this->cloudId = $data['cloudId'];
}
}
/**
* @return array|mixed
*/
public function convertToOptionValue() {
$data = parent::convertToOptionValue();
$data['cloudId'] = $this->getCloudId();
return $data;
}
public function createResponse( $fields = array() ) {
$p_id = (int) $this->getWpPostId();
$the_title = get_the_title( $p_id );
if ( empty( $fields ) ) {
$fields = array(
'uid',
'meta',
'data',
'status'
);
}
$global = array(
'data' => $this->get_editor_data(),
'uid' => $this->getUid(),
'status' => get_post_status( $p_id ),
'dataVersion' => $this->getCurrentDataVersion(),
'meta' => $this->getMeta()
);
return $global;
}
//
// /**
// * @param Brizy_Editor_Popup $post
// * @param array $fields
// *
// * @return array
// */
// public static function postData( Brizy_Editor_Popup $post, $fields = array() ) {
//
// $p_id = (int) $post->getWpPostId();
//
// if ( empty( $fields ) ) {
// $fields = array( 'uid', 'id', 'meta', 'data', 'status' );
// }
//
// $global = array();
//
// if ( in_array( 'uid', $fields ) ) {
// $global['uid'] = $post->getUid();
// }
// if ( in_array( 'status', $fields ) ) {
// $global['status'] = get_post_status( $p_id );
// }
// if ( in_array( 'data', $fields ) ) {
// $global['data'] = $post->get_editor_data();
// }
// if ( in_array( 'meta', $fields ) ) {
// $global['meta'] = $post->getMeta();
// }
//
//
// return $global;
// }
}

View File

@@ -0,0 +1,36 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_PostStatus {
const STATUS_PUBLISH = 'publish';
const STATUS_FUTURE = 'future';
const STATUS_DRAFT = 'draft';
const STATUS_PENDING = 'pending';
const STATUS_PRIVATE = 'private';
const STATUS_TRASH = 'trash';
const STATUS_INHERIT = 'inherit';
const STATUS_AUTODRAFT = 'auto-draft';
public static function getStatusFromWpStatus( $wp_status ) {
switch ( $wp_status ) {
case 'publish':
return self::STATUS_PUBLISH;
case 'future':
return self::STATUS_FUTURE;
case 'draft':
return self::STATUS_DRAFT;
case 'pending':
return self::STATUS_PENDING;
case 'private':
return self::STATUS_PRIVATE;
case 'trash':
return self::STATUS_TRASH;
case 'inherit':
return self::STATUS_INHERIT;
case 'auto-draft':
return self::STATUS_AUTODRAFT;
}
}
}

View File

@@ -0,0 +1,836 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Post extends Brizy_Editor_Entity {
use Brizy_Editor_AutoSaveAware;
const BRIZY_POST = 'brizy-post';
const BRIZY_POST_NEEDS_COMPILE_KEY = 'brizy-need-compile';
const BRIZY_POST_SIGNATURE_KEY = 'brizy-post-signature';
const BRIZY_POST_HASH_KEY = 'brizy-post-hash';
const BRIZY_POST_EDITOR_VERSION = 'brizy-post-editor-version';
const BRIZY_POST_COMPILER_VERSION = 'brizy-post-compiler-version';
const BRIZY_POST_PLUGIN_VERSION = 'brizy-post-plugin-version';
static protected $instance = null;
static protected $compiled_page = [];
/**
* @var string
*/
protected $compiled_html;
/**
* @var array
*/
protected $compiled_scripts;
/**
* @var array
*/
protected $compiled_styles;
/**
* @var string
*/
protected $compiled_html_body;
/**
* @var string
*/
protected $compiled_html_head;
/**
* @var bool
*/
protected $needs_compile;
/**
* Json for the editor.
*
* @var string
*/
protected $editor_data;
/**
* @var bool
*/
protected $uses_editor;
/**
* @var string
*/
protected $editor_version;
/**
* @var string
*/
protected $compiler_version;
/**
* @var string
*/
protected $pro_plugin_version;
/**
* @var string
*/
protected $plugin_version;
/**
* Brizy_Editor_Post2 constructor.
*
* @param $postId
*
* @throws Exception
*/
public function __construct( $postId, $uid = null ) {
if ( $uid ) {
$this->uid = $uid;
}
parent::__construct( $postId );
// create the uid if the editor is enabled for this post
if ( $this->uses_editor() ) {
$this->createUid();
}
}
/**
* @param $apost
*
* @return Brizy_Editor_Post|mixed
* @throws Exception
*/
public static function get( $apost, $uid = null ) {
$wp_post_id = $apost;
if ( $apost instanceof WP_Post ) {
$wp_post_id = $apost->ID;
}
if ( isset( self::$instance[ $wp_post_id ] ) ) {
return self::$instance[ $wp_post_id ];
}
return self::$instance[ $wp_post_id ] = new self( $wp_post_id, $uid );
}
/**
* @param $postId
*
* @return Brizy_Editor_Block|Brizy_Editor_Post|mixed
* @throws Exception
*/
public function duplicateTo( $postId ) {
$newPost = parent::duplicateTo( $postId );
// copy current data to new post
$newPost->set_template( $this->get_template() );
$storage = $this->getStorage();
$newStorage = $newPost->getStorage();
$newStorage->loadStorage( $storage->get_storage() );
$newPost->loadInstanceData();
$newPost->saveStorage();
return $newPost;
}
/**
* Clear all cached instances;
*/
public static function cleanClassCache() {
self::$instance = array();
}
/**
* @return string
*/
public function serialize() {
$get_object_vars = get_object_vars( $this );
unset( $get_object_vars['wp_post_id'] );
unset( $get_object_vars['wp_post'] );
unset( $get_object_vars['api_page'] );
unset( $get_object_vars['store_assets'] );
unset( $get_object_vars['assets'] );
return serialize( $get_object_vars );
}
/**
* @param $data
*/
public function unserialize( $data ) {
parent::unserialize( $data ); // TODO: Change the autogenerated stub
}
public function createResponse( $fields = array() ) {
$p_id = (int) $this->getWpPostId();
$the_title = get_the_title( $p_id );
$global = array(
'title' => $the_title,
'slug' => sanitize_title( $the_title ),
'data' => $this->get_editor_data(),
'id' => $p_id,
'is_index' => false,
'template' => get_page_template_slug( $p_id ),
'status' => get_post_status( $p_id ),
'url' => get_the_permalink( $p_id ),
'dataVersion' => $this->getCurrentDataVersion()
);
return $global;
}
public function convertToOptionValue() {
return array(
'compiled_html' => $this->get_encoded_compiled_html(),
'compiled_scripts' => $this->getCompiledScripts(),
'compiled_styles' => $this->getCompiledStyles(),
'compiled_html_body' => $this->get_compiled_html_body(),
'compiled_html_head' => $this->get_compiled_html_head(),
'editor_version' => $this->editor_version,
'compiler_version' => $this->compiler_version,
'plugin_version' => $this->plugin_version,
'pro_plugin_version' => $this->pro_plugin_version,
'editor_data' => $this->editor_data,
Brizy_Editor_Constants::USES_BRIZY => $this->uses_editor()
);
}
/**
* Mark all brizy post that needs compile
*/
public static function mark_all_for_compilation() {
global $wpdb;
$wpdb->update( $wpdb->postmeta, array( 'meta_value' => 1 ), array( 'meta_key' => self::BRIZY_POST_NEEDS_COMPILE_KEY ) );
}
public function savePost( $createRevision = false ) {
$postarr = [
'ID' => $this->getWpPostId(),
'post_content' => $this->getPostContent( $createRevision )
];
$this->deleteOldAutosaves( $this->getWpPostId() );
if ( $createRevision ) {
$post_type_object = get_post_type_object( $this->getWpPost()->post_type );
if ( current_user_can( $post_type_object->cap->publish_posts ) ) {
$postarr['post_status'] = $this->getWpPost()->post_status;
}
} else {
remove_action( 'post_updated', 'wp_save_post_revision' );
}
wp_update_post( $postarr );
$this->createUid();
}
private function getPostContent( $noFilters ) {
$post = $this->getWpPost();
$emptyContent = '<div class="brz-root__container"></div>';
$versionTime = '<!-- version:' . time() . ' -->';
$excluded = [
Brizy_Admin_Blocks_Main::CP_GLOBAL,
Brizy_Admin_Blocks_Main::CP_SAVED,
Brizy_Admin_Templates::CP_TEMPLATE,
Brizy_Admin_Popups_Main::CP_POPUP
];
if ( in_array( $post->post_type, $excluded ) ) {
return $emptyContent . $versionTime;
}
if ( $noFilters ) {
$content = $post->post_content;
} else {
$context = new Brizy_Content_Context( Brizy_Editor_Project::get(), null, $post, null );
$placeholderProvider = new Brizy_Content_PlaceholderWpProvider( $context );
$context->setProvider( $placeholderProvider );
$extractor = new \BrizyPlaceholders\Extractor( $placeholderProvider );
list( $placeholders, $placeholderInstances, $content ) = $extractor->extract( $this->get_compiled_page()->getPageContent() );
$replacer = new \BrizyPlaceholders\Replacer( $placeholderProvider );
$content = $replacer->replaceWithExtractedData( $placeholders, $placeholderInstances, $content, $context );
$content = $extractor->stripPlaceholders( $content );
$content = apply_filters( 'brizy_content', $content, Brizy_Editor_Project::get(), $post );
}
$content = strpos( $content, 'brz-root__container' ) ? preg_replace( '/<!-- version:\d+ -->/', '', $content ) : $emptyContent;
return $content . $versionTime;
}
/**
* @param int $autosave
*
* @return bool|Brizy_Editor_Entity
*/
public function save( $autosave = 0 ) {
parent::save( $autosave );
if ( $autosave == 0 ) {
$this->saveStorage();
} else {
$this->auto_save_post( $this->getWpPost(), function ( $autosaveObject ) {
$autosavePost = $this->populateAutoSavedData( $autosaveObject );
$autosavePost->saveStorage();
} );
}
return true;
}
/**
* @return bool
* @throws Brizy_Editor_Exceptions_ServiceUnavailable
* @throws Exception
*/
public function compile_page() {
Brizy_Logger::instance()->notice( 'Compile page', array( $this ) );
$compiledData = Brizy_Editor_User::get()->compile_page( Brizy_Editor_Project::get(), $this );
$compiledData['pageHtml'] = Brizy_SiteUrlReplacer::hideSiteUrl( $compiledData['pageHtml'] );
foreach ( $compiledData['pageScripts'] as $i => $set ) { //pro || free
foreach ( $set as $k => $scripts ) { // groups
if ( $k == 'libsSelectors' ) {
continue;
}
if ( $k == 'main' ) {
if ( isset( $compiledData['pageScripts'][ $i ][ $k ]['content']['url'] ) ) {
$compiledData['pageScripts'][ $i ][ $k ]['content']['url'] = Brizy_SiteUrlReplacer::hideSiteUrl( $compiledData['pageScripts'][ $i ][ $k ]['content']['url'] );
continue;
}
}
foreach ( $scripts as $l => $script ) {
if ( isset( $compiledData['pageScripts'][ $i ][ $k ][ $l ]['content']['url'] ) ) {
$compiledData['pageScripts'][ $i ][ $k ][ $l ]['content']['url'] = Brizy_SiteUrlReplacer::hideSiteUrl( $script['content']['url'] );
}
}
}
}
foreach ( $compiledData['pageStyles'] as $i => $set ) {
foreach ( $set as $k => $styles ) {
if ( $k == 'libsSelectors' ) {
continue;
}
if ( $k == 'main' ) {
if ( isset( $compiledData['pageStyles'][ $i ][ $k ]['content']['url'] ) ) {
$compiledData['pageStyles'][ $i ][ $k ]['content']['url'] = Brizy_SiteUrlReplacer::hideSiteUrl( $compiledData['pageStyles'][ $i ][ $k ]['content']['url'] );
}
continue;
}
foreach ( $styles as $l => $style ) {
if ( isset( $compiledData['pageStyles'][ $i ][ $k ][ $l ]['content']['url'] ) ) {
$compiledData['pageStyles'][ $i ][ $k ][ $l ]['content']['url'] = Brizy_SiteUrlReplacer::hideSiteUrl(
$style['content']['url']
);
}
}
}
}
$this->set_compiled_html( $compiledData['pageHtml'] );
$this->set_compiled_html_head( null );
$this->set_compiled_html_body( null );
$this->set_needs_compile( false );
$this->set_compiler_version( BRIZY_EDITOR_VERSION );
$this->set_plugin_version( BRIZY_VERSION );
$this->set_pro_plugin_version( defined( 'BRIZY_PRO_VERSION' ) ? BRIZY_PRO_VERSION : null );
$this->setCompiledScripts( $compiledData['pageScripts'] );
$this->setCompiledStyles( $compiledData['pageStyles'] );
return true;
}
/**
* @return string
*/
public function get_compiled_html() {
return $this->compiled_html;
}
/**
* @param string $compiled_html
*
* @return Brizy_Editor_Post
*/
public function set_compiled_html( $compiled_html ) {
$this->compiled_html = $compiled_html;
return $this;
}
/**
* @return array
*/
public function getCompiledScripts() {
return $this->compiled_scripts;
}
/**
* @param array $compiled_scripts
*
* @return Brizy_Editor_Post
*/
public function setCompiledScripts( $compiled_scripts ) {
$this->compiled_scripts = $compiled_scripts;
return $this;
}
/**
* @return array
*/
public function getCompiledStyles() {
return $this->compiled_styles;
}
/**
* @param array $compiled_styles
*
* @return Brizy_Editor_Post
*/
public function setCompiledStyles( $compiled_styles ) {
$this->compiled_styles = $compiled_styles;
return $this;
}
/**
* @param $compiled_html
*
* @return $this
*/
public function set_encoded_compiled_html( $compiled_html ) {
if ( ( $decodedData = base64_decode( $compiled_html, true ) ) !== false ) {
$this->set_compiled_html( $decodedData );
} else {
$this->set_compiled_html( $compiled_html );
}
return $this;
}
/**
* @return string
*/
public function get_encoded_compiled_html() {
return base64_encode( $this->get_compiled_html() );
}
/**
* @return string
* @deprecated use get_compiled_html
*/
public function get_compiled_html_body() {
return $this->compiled_html_body;
}
/**
* @return string
* @deprecated use get_compiled_html
*/
public function get_compiled_html_head() {
return $this->compiled_html_head;
}
/**
* @param $html
*
* @return $this
* @deprecated use set_compiled_html
*
*/
public function set_compiled_html_body( $html ) {
$this->compiled_html_body = $html;
return $this;
}
/**
* @param $html
*
* @return $this
* @deprecated use set_compiled_html
*
*/
public function set_compiled_html_head( $html ) {
// remove all title and meta tags.
$this->compiled_html_head = $html;
return $this;
}
/**
* @return string
*/
public function get_editor_data() {
if ( ( $decodedData = base64_decode( $this->editor_data, true ) ) !== false ) {
return $decodedData;
}
return $this->editor_data;
}
/**
* @param $content
*
* @return $this
*/
public function set_editor_data( $content ) {
if ( base64_decode( $content, true ) !== false ) {
$this->editor_data = $content;
} else {
$this->editor_data = base64_encode( $content );
}
return $this;
}
/**
* @return $this
* @throws Brizy_Editor_Exceptions_AccessDenied
*/
public function enable_editor() {
if ( ! $this->can_edit_posts() ) {
throw new Brizy_Editor_Exceptions_AccessDenied( 'Current user cannot edit page' );
}
$this->set_uses_editor( true );
return $this;
}
/**
* @return $this
* @throws Brizy_Editor_Exceptions_AccessDenied
*/
public function disable_editor() {
if ( ! $this->can_edit_posts() ) {
throw new Brizy_Editor_Exceptions_AccessDenied( 'Current user cannot edit page' );
}
$this->set_uses_editor( false );
return $this;
}
/**
* @param string $editor_version
*/
public function set_editor_version( $editor_version ) {
$this->editor_version = $editor_version;
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_POST_EDITOR_VERSION, $editor_version );
}
/**
* @param string $compiler_version
*/
public function set_compiler_version( $compiler_version ) {
$this->compiler_version = $compiler_version;
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_POST_COMPILER_VERSION, $compiler_version );
}
/**
* @param string $plugin_version
*/
public function set_plugin_version( $plugin_version ) {
$this->plugin_version = $plugin_version;
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_POST_PLUGIN_VERSION, $plugin_version );
}
/**
* @param $v
*
* @return $this
*/
public function set_needs_compile( $v ) {
$this->needs_compile = (bool) $v;
update_metadata( 'post', $this->getWpPostId(), self::BRIZY_POST_NEEDS_COMPILE_KEY, (bool) $v );
return $this;
}
/**
* @return bool
*/
public function get_needs_compile() {
return $this->needs_compile;
}
/**
* @return Brizy_Editor_CompiledHtml
*/
public function get_compiled_page() {
if ( isset( self::$compiled_page[ $this->getWpPostId() ] ) ) {
return self::$compiled_page[ $this->getWpPostId() ];
}
return self::$compiled_page[ $this->getWpPostId() ] = new Brizy_Editor_CompiledHtml( $this->get_compiled_html() );
}
public function isCompiledWithCurrentVersion() {
$proVersion = defined( 'BRIZY_PRO_VERSION' ) ? BRIZY_PRO_VERSION : null;
return $this->get_compiler_version() === BRIZY_EDITOR_VERSION && $this->get_pro_plugin_version() === $proVersion && $this->plugin_version===BRIZY_VERSION;
}
/**
* @return array
*/
public function get_templates() {
$type = get_post_type( $this->getWpPostId() );
$templates = array(
array(
'id' => '',
'title' => __( 'Default', 'brizy' )
)
);
foreach ( wp_get_theme()->get_page_templates( null, $type ) as $key => $title ) {
$templates[] = [
'id' => $key,
'title' => $title
];
}
return apply_filters( "brizy:$type:templates", $templates );
}
/**
* @param string $aTemplate
*
* @return $this
*/
public function set_template( $aTemplate ) {
$aTemplate = apply_filters( 'brizy_post_template', $aTemplate );
if ( $aTemplate == '' ) {
delete_post_meta( $this->getWpPostId(), '_wp_page_template' );
} else {
update_post_meta( $this->getWpPostId(), '_wp_page_template', $aTemplate );
}
return $this;
}
/**
* @return mixed
*/
public function get_template() {
return get_post_meta( $this->getWpPostId(), '_wp_page_template', true );
}
/**
* @return string
*/
public function get_compiler_version() {
return $this->compiler_version;
}
/**
* @return string
*/
public function get_pro_plugin_version() {
return $this->pro_plugin_version;
}
/**
* @param string $pro_plugin_version
*
* @return Brizy_Editor_Post
*/
public function set_pro_plugin_version( $pro_plugin_version ) {
$this->pro_plugin_version = $pro_plugin_version;
return $this;
}
/**
* @return string
*/
public function get_editor_version() {
return $this->editor_version;
}
/**
* @return string
* @deprecated Use getEditUrl()
*/
public function edit_url() {
return self::getEditUrl( $this->getWpPostId() );
}
/**
* Will return the key on witch the object data will be saved in storage
*
* @return mixed
*/
protected function getObjectKey() {
return self::BRIZY_POST;
}
/**
* Load all object data
*/
protected function loadInstanceData() {
// get the storage values
$storage = $this->getStorage();
//$storageData = $storage->get_storage();
$storage_post = $storage->get( $this->getObjectKey(), false );
// check for deprecated forms of posts
if ( $storage_post instanceof self ) {
$this->set_editor_data( $storage_post->editor_data );
$this->set_needs_compile( true );
$this->save();
} else if ( is_array( $storage_post ) ) {
if ( isset( $storage_post['compiled_html'] ) ) {
$this->set_encoded_compiled_html( $storage_post['compiled_html'] );
}
if ( isset( $storage_post['compiled_scripts'] ) ) {
$this->setCompiledScripts( $storage_post['compiled_scripts'] );
}
if ( isset( $storage_post['compiled_styles'] ) ) {
$this->setCompiledStyles( $storage_post['compiled_styles'] );
}
$proVersion = defined( 'BRIZY_PRO_VERSION' ) ? BRIZY_PRO_VERSION : null;
$data_needs_compile = isset( $storage_post['needs_compile'] ) ? $storage_post['needs_compile'] : true;
$this->set_editor_data( $storage_post['editor_data'] );
$this->set_needs_compile( metadata_exists( 'post', $this->getWpPostId(), self::BRIZY_POST_NEEDS_COMPILE_KEY ) ? (bool) get_post_meta( $this->getWpPostId(), self::BRIZY_POST_NEEDS_COMPILE_KEY, true ) : $data_needs_compile );
$this->set_editor_version( isset( $storage_post['editor_version'] ) ? $storage_post['editor_version'] : BRIZY_EDITOR_VERSION );
$this->set_compiler_version( isset( $storage_post['compiler_version'] ) ? $storage_post['compiler_version'] : BRIZY_EDITOR_VERSION );
$this->set_plugin_version( isset( $storage_post['plugin_version'] ) ? $storage_post['plugin_version'] : null );
$this->set_pro_plugin_version( isset( $storage_post['pro_plugin_version'] ) ? $storage_post['pro_plugin_version'] : null );
$this->compiled_html_head = isset( $storage_post['compiled_html_head'] ) ? $storage_post['compiled_html_head'] : null;
$this->compiled_html_body = isset( $storage_post['compiled_html_body'] ) ? $storage_post['compiled_html_body'] : null;
}
}
/**
* @param self $autosave
*
* @return mixed
*/
protected function populateAutoSavedData( $autosave ) {
$autosave->set_template( $this->get_template() );
$autosave->set_editor_data( $this->get_editor_data() );
$autosave->set_editor_version( $this->get_editor_version() );
$autosave->set_needs_compile( true );
return $autosave;
}
public static function get_post_list( $searchTerm, $postType, $excludePostType = array(), $offset = 0, $limit = 20 ) {
global $wp_post_types, $wpdb;
$searchQuery = '';
$postLabel = $wp_post_types[ $postType ]->label;
// not sure iw we will have this case :D
if ( is_array( $excludePostType ) && in_array( $postType, $excludePostType ) ) {
return [];
}
if ( $searchTerm ) {
$searchQuery = " AND post_title LIKE %s";
}
$postStatus = $postType == 'attachment' ? "'inherit'" : "'publish','pending','draft','future','private'";
$query = <<<SQL
SELECT
p.ID,
p.post_title as title,
p.post_title as post_title,
%s as post_type,
%s as post_type_label,
pm.meta_value as 'uid'
FROM
$wpdb->posts p
LEFT JOIN $wpdb->postmeta pm ON pm.post_id=p.ID and pm.meta_key='brizy_post_uid'
WHERE
p.post_type='%s' and p.post_status IN ($postStatus) $searchQuery
ORDER BY p.post_title ASC
LIMIT %d,%d
SQL;
$posts = $wpdb->get_results( $wpdb->prepare( $query, $postType, $postLabel, $postType, $offset, $limit ) );
foreach ( $posts as $i => $p ) {
$postTitle = apply_filters( 'the_title', $p->post_title );
$p->post_title = $postTitle;
$p->title = $postTitle;
$p->uid = self::create_uid( $p->ID, $p->uid );
$p->ID = (int) $p->ID;
}
return $posts;
}
private static function create_uid( $postId, $uid ) {
if ( ! $uid ) {
$uid = md5( $postId . time() );
update_post_meta( $postId, 'brizy_post_uid', $uid );
}
return $uid;
}
/**
* @return WP_Post
* @deprecated Use getWpPost();
*
*/
public function get_wp_post() {
return $this->getWpPost();
}
}

View File

@@ -0,0 +1,845 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
include_once ABSPATH . "wp-admin/includes/class-wp-filesystem-base.php";
include_once ABSPATH . "wp-admin/includes/class-wp-filesystem-direct.php";
class Brizy_Editor_Project extends Brizy_Editor_Entity {
use Brizy_Editor_AutoSaveAware;
const BRIZY_PROJECT = 'brizy-project';
/**
* @var Brizy_Editor_Project
*/
static protected $instance = null;
/**
* @var Brizy_Editor_API_Project
*/
protected $api_project = null;
//---------------------------------------------------------------------------------------------------
protected $id;
protected $title;
protected $globals;
protected $name;
protected $user;
protected $template;
protected $created;
protected $updated;
protected $languages;
protected $pluginVersion;
protected $editorVersion;
protected $signature;
protected $accounts;
protected $license_key;
protected $forms;
protected $cloud_account_id;
protected $cloud_token;
protected $cloudContainer;
protected $cloud_project;
protected $image_optimizer_settings;
protected $data;
//---------------------------------------------------------------------------------------------------
protected $isDataChanged = false;
//---------------------------------------------------------------------------------------------------
/**
* Brizy_Editor_Project constructor.
*
* @param WP_Post $post
*
* @throws Exception
*/
public function __construct( WP_Post $post ) {
$this->setWpPostId( $post->ID );
$this->loadInstanceData();
}
protected function getObjectKey() {
return self::BRIZY_PROJECT;
}
protected function loadInstanceData() {
$this->loadProjectData( $this->getStorage()->get_storage() );
}
protected function populateAutoSavedData( $autosave ) {
$autosave->loadProjectData( $this->convertToOptionValue() );
}
public function getStorage() {
return Brizy_Editor_Storage_Project::instance( $this->getWpPostId() );
}
public static function cleanClassCache() {
self::$instance = array();
}
static public function registerCustomPostType() {
register_post_type( self::BRIZY_PROJECT,
array(
'public' => false,
'has_archive' => false,
'description' => __( 'Brizy Project.' ),
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => false,
'hierarchical' => false,
'show_in_rest' => false,
'exclude_from_search' => true,
'supports' => array( 'title', 'revisions', 'page-attributes' )
)
);
}
/**
* @return Brizy_Editor_Project|mixed
* @throws Exception
*/
public static function get( $apost = null, $uid = null ) {
$wp_post_id = $apost;
if ( $apost instanceof WP_Post ) {
$wp_post_id = $apost->ID;
}
if ( ! $wp_post_id && isset( self::$instance[ $wp_post_id ] ) ) {
return self::$instance[ $wp_post_id ];
}
try {
if ( is_null( $wp_post_id ) ) {
$wp_post = self::getPost();
} else {
$wp_post = get_post( $wp_post_id );
}
if ( isset( self::$instance[ $wp_post->ID ] ) ) {
return self::$instance[ $wp_post->ID ];
}
} catch ( Exception $e ) {
Brizy_Logger::instance()->exception( $e );
throw $e;
}
return self::$instance[ $wp_post->ID ] = new self( $wp_post );
}
/**
* @return false|WP_Post
* @throws Exception
*/
static protected function getPost() {
global $wpdb;
$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 ", self::BRIZY_PROJECT ),
OBJECT
);
if ( is_null( $row ) ) {
Brizy_Logger::instance()->critical( 'Failed to check if the project exist.', [] );
throw new Exception( 'Failed to check if the project exist.' );
}
if ( isset( $row[0] ) ) {
return WP_Post::get_instance( $row[0]->ID );
}
$post_id = self::createPost();
return WP_Post::get_instance( $post_id );
}
/**
* @return int|WP_Error
* @throws Exception
*/
private static function createPost() {
global $wpdb;
$defaultJsonPath = Brizy_Editor_UrlBuilder::editor_build_path( 'defaults.json' );
if ( ! file_exists( $defaultJsonPath ) ) {
$message = 'Failed to create the default project data. ' . $defaultJsonPath . ' was not found. ';
Brizy_Logger::instance()->critical( $message, [ $message ] );
throw new Exception( $message );
}
$project_data = array(
'id' => md5( uniqid( 'Local project', true ) ),
'title' => 'Brizy Project',
'name' => uniqid( 'Local project', true ),
'user' => null,
'template' => array( 'slug' => 'brizy' ),
'created' => new DateTime(),
'updated' => new DateTime(),
'languages' => array(),
'pluginVersion' => BRIZY_VERSION,
'editorVersion' => BRIZY_EDITOR_VERSION,
'signature' => Brizy_Editor_Signature::get(),
'accounts' => array(),
'forms' => array(),
'data' => base64_encode( file_get_contents( $defaultJsonPath ) ),
'cloudContainer' => null,
'brizy-license-key' => null,
'brizy-cloud-token' => null,
'brizy-cloud-account-id' => null,
'brizy-cloud-project' => null,
'image-optimizer-settings' => array(),
);
try {
$wpdb->query( 'START TRANSACTION' );
$wpdb->insert( $wpdb->posts, [
'post_type' => self::BRIZY_PROJECT,
'post_title' => 'Brizy Project',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 0,
'post_content' => '',
'post_excerpt' => '',
'post_password' => '',
'to_ping' => '',
'pinged' => '',
'post_parent' => 0,
'menu_order' => 0,
'guid' => '',
'post_date' => current_time( 'mysql' ),
'post_date_gmt' => current_time( 'mysql', 1 ),
] );
$post_id = $wpdb->insert_id;
$storage = Brizy_Editor_Storage_Project::instance( $post_id );
$storage->loadStorage( $project_data );
$wpdb->query( 'COMMIT' );
Brizy_Logger::instance()->notice( 'Create new project', array( 'id' => $post_id ) );
return $post_id;
} catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' );
throw $e;
}
}
/**
* This will be returned by api when project is requested
*/
public function createResponse( $fields = array() ) {
$data = array(
'id' => $this->getId(),
'data' => $this->getDataAsJson(),
'dataVersion' => $this->getCurrentDataVersion()
);
return $data;
}
/**
* @return array
*/
public function convertToOptionValue() {
return array(
'id' => $this->id,
'title' => $this->title,
'name' => $this->name,
'user' => $this->user,
'template' => $this->template,
'created' => $this->created,
'updated' => $this->updated,
//'languages' => $this->languages,
'pluginVersion' => $this->pluginVersion,
'editorVersion' => $this->editorVersion,
'signature' => $this->signature,
'accounts' => $this->accounts,
'forms' => $this->forms,
'data' => $this->data,
'brizy-license-key' => $this->license_key,
'brizy-cloud-token' => $this->cloud_token,
'brizy-cloud-project' => $this->cloud_project,
'brizy-cloud-account-id' => $this->cloud_account_id,
'cloudContainer' => $this->cloudContainer,
'image-optimizer-settings' => $this->image_optimizer_settings,
);
}
protected function loadProjectData( $data ) {
$this->id = isset( $data['id'] ) ? $data['id'] : null;
$this->title = isset( $data['title'] ) ? $data['title'] : null;
$this->name = isset( $data['name'] ) ? $data['name'] : null;
$this->user = isset( $data['user'] ) ? $data['user'] : null;
$this->template = isset( $data['template'] ) ? $data['template'] : null;
$this->created = isset( $data['created'] ) ? $data['created'] : null;
$this->updated = isset( $data['updated'] ) ? $data['updated'] : null;
$this->languages = isset( $data['languages'] ) ? $data['languages'] : null;
$this->pluginVersion = isset( $data['pluginVersion'] ) ? $data['pluginVersion'] : null;
$this->editorVersion = isset( $data['editorVersion'] ) ? $data['editorVersion'] : null;
$this->signature = isset( $data['signature'] ) ? $data['signature'] : null;
$this->accounts = isset( $data['accounts'] ) ? $data['accounts'] : null;
$this->forms = isset( $data['forms'] ) ? $data['forms'] : null;
$this->data = isset( $data['data'] ) ? $data['data'] : null;
$this->license_key = isset( $data['brizy-license-key'] ) ? $data['brizy-license-key'] : null;
$this->cloud_token = isset( $data['brizy-cloud-token'] ) ? $data['brizy-cloud-token'] : null;
$this->cloud_project = isset( $data['brizy-cloud-project'] ) ? $data['brizy-cloud-project'] : null;
$this->cloud_account_id = isset( $data['brizy-cloud-account-id'] ) ? $data['brizy-cloud-account-id'] : null;
$this->cloudContainer = isset( $data['cloudContainer'] ) ? $data['cloudContainer'] : null;
$this->image_optimizer_settings = isset( $data['image-optimizer-settings'] ) ? $data['image-optimizer-settings'] : array();
}
/**
* This saves ony data.. it does not touch the wordpress post
*
* @return bool
*/
public function save( $autosave = 0 ) {
parent::save( $autosave );
if ( ! $this->isDataChanged ) {
return;
}
if ( $autosave == 0 ) {
$this->saveStorage();
} else {
$this->auto_save_post( $this->getWpPost(), function ( self $autoSaveObject ) {
$this->populateAutoSavedData( $autoSaveObject );
$autoSaveObject->saveStorage();
} );
}
}
public function saveStorage() {
$value = $this->convertToOptionValue();
$this->getStorage()->loadStorage( $value );
}
/**
* Create revision
*/
public function savePost() {
if ( ! $this->isDataChanged ) {
return;
}
$post_type = $this->getWpPost()->post_type;
$post_type_object = get_post_type_object( $post_type );
$can_publish = current_user_can( $post_type_object->cap->publish_posts );
$post_status = $can_publish ? 'publish' : 'pending';
$this->deleteOldAutoSaves( $this->getWpPostParentId() );
wp_update_post( array(
'ID' => $this->getWpPostId(),
'post_status' => $post_status,
'post_content' => md5( time() )
) );
}
/**
* @return mixed
*/
public function getTitle() {
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle( $title ) {
$this->title = $title;
}
/**
* @return mixed
*/
public function getName() {
return $this->name;
}
/**
* @param mixed $name
*/
public function setName( $name ) {
$this->name = $name;
}
/**
* @return mixed
*/
public function getUser() {
return $this->user;
}
/**
* @param mixed $user
*/
public function setUser( $user ) {
$this->user = $user;
}
/**
* @return mixed
*/
public function getTemplate() {
return $this->template;
}
/**
* @param mixed $template
*/
public function setTemplate( $template ) {
$this->template = $template;
}
/**
* @return mixed
*/
public function getCreated() {
return $this->created;
}
/**
* @param mixed $created
*/
public function setCreated( $created ) {
$this->created = $created;
}
/**
* @return mixed
*/
public function getUpdated() {
return $this->updated;
}
/**
* @param mixed $updated
*/
public function setUpdated( $updated ) {
$this->updated = $updated;
}
/**
* @return mixed
*/
public function getLanguages() {
return $this->languages;
}
/**
* @param mixed $languages
*/
public function setLanguages( $languages ) {
$this->languages = $languages;
}
/**
* @return mixed
*/
public function getPluginVersion() {
return $this->pluginVersion;
}
/**
* @param mixed $pluginVersion
*/
public function setPluginVersion( $pluginVersion ) {
$this->pluginVersion = $pluginVersion;
}
/**
* @return mixed
*/
public function getEditorVersion() {
return $this->editorVersion;
}
/**
* @param mixed $editorVersion
*/
public function setEditorVersion( $editorVersion ) {
$this->editorVersion = $editorVersion;
}
/**
* @return mixed
*/
public function getSignature() {
return $this->signature;
}
/**
* @param mixed $signature
*/
public function setSignature( $signature ) {
$this->signature = $signature;
}
/**
* @return mixed
*/
public function getAccounts() {
return $this->accounts;
}
/**
* @param mixed $accounts
*/
public function setAccounts( $accounts ) {
$this->accounts = $accounts;
}
/**
* @return mixed
*/
public function getLicenseKey() {
return $this->license_key;
}
/**
* @param mixed $license_key
*/
public function setLicenseKey( $license_key ) {
$this->license_key = $license_key;
}
/**
* @return mixed
*/
public function getForms() {
return $this->forms;
}
/**
* @param mixed $forms
*/
public function setForms( $forms ) {
$this->forms = $forms;
}
/**
* @return mixed
*/
public function getCloudToken() {
return $this->cloud_token;
}
/**
* @param mixed $cloud_token
*/
public function setCloudToken( $cloud_token ) {
$this->cloud_token = $cloud_token;
}
/**
* @return mixed
*/
public function getCloudContainer() {
return $this->cloudContainer;
}
/**
* @param mixed $cloudContainer
*
* @return Brizy_Editor_Project
*/
public function setCloudContainer( $cloudContainer ) {
$this->cloudContainer = $cloudContainer;
return $this;
}
/**
* @return mixed
*/
public function getCloudProject() {
return $this->cloud_project;
}
/**
* @param mixed $cloud_project
*/
public function setCloudProject( $cloud_project ) {
$this->cloud_project = $cloud_project;
}
/**
* @return mixed
*/
public function getCloudAccountId() {
return $this->cloud_account_id;
}
/**
* @param mixed $cloud_account_id
*
* @return Brizy_Editor_Project
*/
public function setCloudAccountId( $cloud_account_id ) {
$this->cloud_account_id = $cloud_account_id;
return $this;
}
//====================================================================================================================================================================================
/**
* @return mixed
*/
public function getGlobals() {
return $this->globals;
}
/**
* @return bool|string
*/
public function getGlobalsAsJson() {
return base64_decode( $this->getGlobals() );
}
/**
* @return array|mixed|object
*/
public function getDecodedGlobals() {
return json_decode( $this->getGlobalsAsJson() );
}
/**
* @param mixed $globals
*
* @return Brizy_Editor_Project
*/
public function setGlobals( $globals ) {
$this->globals = $globals;
return $this;
}
public function setGlobalsAsJson( $globals ) {
$this->setGlobals( base64_encode( $globals ) );
return $this;
}
//====================================================================================================================================================================================
/**
* @return mixed
*/
public function getData() {
return $this->data;
}
/**
* @param mixed $data
*
*
* @return Brizy_Editor_Project
*/
public function setData( $data ) {
$this->isDataChanged = $data !== $this->data;
$this->data = $data;
return $this;
}
public function setDataAsJson( $data ) {
$encodedData = base64_encode( $data );
if ( $encodedData === false ) {
throw new Exception( 'Failed to base64 encode the project data' );
}
$this->setData( $encodedData );
return $this;
}
public function getDataAsJson() {
return base64_decode( $this->getData() );
}
/**
* @return bool|string
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function getDecodedData() {
return json_decode( $this->getDataAsJson() );
}
/**
* @return mixed
*/
public function getId() {
return $this->id;
}
/**
* @return mixed
*/
public function getTemplateSlug() {
$template = $this->getTemplate();
return $template['slug'];
}
/**
* @param null $optimizer_id
* @param null $key
*
* @return array|null
*/
public function getImageOptimizerSettings( $optimizer_id = null, $key = null ) {
if ( $optimizer_id && $key ) {
return isset( $this->image_optimizer_settings[ $optimizer_id ][ $key ] ) ? $this->image_optimizer_settings[ $optimizer_id ][ $key ] : null;
}
return $this->image_optimizer_settings;
}
/**
* @param mixed $image_optimizer_settings
*
* @return Brizy_Editor_Project
*/
public function setImageOptimizerSettings( $image_optimizer_settings ) {
$this->image_optimizer_settings = $image_optimizer_settings;
return $this;
}
/**
* @param $key
* @param $value
*
* @return mixed
*/
public function setMetaValue( $key, $value ) {
wp_raise_memory_limit( 'image' );
if ( is_null( $key ) ) {
throw new InvalidArgumentException( 'The key parameter should not be null' );
}
if ( $key == 'brizy-license-key' ) {
$this->setLicenseKey( $value );
}
if ( $key == 'brizy-cloud-token' ) {
$this->setCloudToken( $value );
}
if ( $key == 'brizy-cloud-account-id' ) {
$this->setCloudAccountId( $value );
}
if ( $key == 'brizy-cloud-project' ) {
$this->setCloudProject( $value );
}
if ( $key == 'brizy-cloud-container' ) {
$this->setCloudContainer( $value );
}
if ( $key == 'image-optimizer-settings' ) {
$this->setImageOptimizerSettings( $value );
}
return $this->$key = $value;
}
/**
* @param $key
*/
public function removeMetaValue( $key ) {
if ( is_null( $key ) ) {
throw new InvalidArgumentException( 'The key parameter should not be null' );
}
if ( $key == 'brizy-license-key' ) {
$this->setLicenseKey( null );
}
if ( $key == 'brizy-cloud-account-id' ) {
$this->setCloudAccountId( null );
}
if ( $key == 'brizy-cloud-token' ) {
$this->setCloudToken( null );
}
if ( $key == 'brizy-cloud-project' ) {
$this->setCloudProject( null );
}
if ( $key == 'image-optimizer-settings' ) {
$this->setImageOptimizerSettings( null );
}
if ( isset( $this->$key ) ) {
unset( $this->$key );
}
}
/**
* @param $key
*
* @return |null
*/
public function getMetaValue( $key ) {
if ( is_null( $key ) ) {
throw new InvalidArgumentException( 'The key parameter should not be null' );
}
if ( $key == 'brizy-license-key' ) {
return $this->getLicenseKey();
}
if ( $key == 'brizy-cloud-account-id' ) {
$this->getCloudAccountId();
}
if ( $key == 'brizy-cloud-token' ) {
return $this->getCloudToken();
}
if ( $key == 'brizy-cloud-project' ) {
return $this->getCloudProject();
}
if ( $key == 'image-optimizer-settings' ) {
return $this->getImageOptimizerSettings();
}
if ( isset( $this->$key ) ) {
return $this->$key;
}
return null;
}
/**
* @return Brizy_Editor_API_Project
*/
public function getApiProject() {
return $this->api_project;
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* This class will add all the images that are used by brizy in a post
*
* Class Brizy_Editor_RestExtend
*/
class Brizy_Editor_RestExtend {
/**
* Brizy_Editor_RestExtend constructor.
*/
public function __construct() {
add_action( 'rest_api_init', function () {
register_rest_field( Brizy_Editor::get()->supported_post_types(), 'brizy_media', array(
'get_callback' => function ( $page ) {
$uid = get_post_meta( $page['id'], 'brizy_post_uid', true );
if($uid)
return $this->get_page_attachments( $uid );
return [];
},
'update_callback' => function ( $karma, $comment_obj ) {
return true;
},
'schema' => array(
'description' => __( 'Brizy attached media' ),
'type' => 'array'
),
) );
} );
add_action( 'rest_api_init', array( $this, 'create_feature_image_focal_point_field' ) );
}
private function get_page_attachments( $uid ) {
global $wpdb;
$query = $wpdb->prepare(
"SELECT
pm.*
FROM
{$wpdb->prefix}postmeta pm
JOIN {$wpdb->prefix}postmeta pm2 ON pm2.post_id=pm.post_id AND pm2.meta_key='brizy_post_uid' AND pm2.meta_value=%s
WHERE pm.meta_key='brizy_attachment_uid'
GROUP BY pm.post_id", $uid );
$results = $wpdb->get_results( $query );
$attachment_data = array();
foreach ( $results as $row ) {
$attachment = get_post( (int) $row->post_id );
$attachment_data[] =
[
'id' => (int) $row->post_id,
'url' => wp_get_attachment_url( (int) $row->post_id ),
'name' => basename( $attachment->guid ),
'meta' => [
'brizy_attachment_uid' => get_post_meta( (int) $row->post_id, 'brizy_attachment_uid', true ),
'brizy_post_uid' => get_post_meta( (int) $row->post_id, 'brizy_post_uid' )
]
];
}
return $attachment_data;
}
public function create_feature_image_focal_point_field() {
if ( ! Brizy_Editor_User::is_user_allowed() ) {
return;
}
$post_types = array_keys( get_post_types( [ 'exclude_from_search' => false, 'show_in_nav_menus' => true ] ) );
$post_types = array_filter( $post_types, function( $post_type ) {
return post_type_supports( $post_type, 'thumbnail' );
} );
register_rest_field( $post_types, 'brizy_attachment_focal_point', array(
'get_callback' => function ( $post, $field_name, $request ) {
return get_post_meta( $post['id'], $field_name, true );
},
'update_callback' => function ( $meta_value, $post ) {
update_post_meta( $post->ID, 'brizy_attachment_focal_point', $meta_value );
}
)
);
}
}

View File

@@ -0,0 +1,163 @@
<?php
class Brizy_Editor_Screenshot_Manager {
const BLOCK_TYPE_NORMAL = 'normal';
const BLOCK_TYPE_GLOBAL = 'global';
const BLOCK_TYPE_SAVED = 'saved';
const BLOCK_TYPE_LAYOUT = 'layout';
/**
* @var Brizy_Editor_UrlBuilder
*/
private $urlBuilder;
/**
* Brizy_Editor_Screenshot_Manager constructor.
*
* @param Brizy_Editor_UrlBuilder $urlBuilder
*/
public function __construct( Brizy_Editor_UrlBuilder $urlBuilder ) {
$this->urlBuilder = $urlBuilder;
}
/**
* @param $screenUid
* @param $blockType
* @param $imageContent
* @param $postId
*
* @return bool
*/
public function saveScreenshot( $screenUid, $blockType, $imageContent, $postId ) {
$path = $this->getScreenshotPath( $screenUid, $blockType, $postId );
if(!$this->validateImageContent( $imageContent )) {
throw new Exception('Invalid image content');
}
$extension = 'jpeg';
$screenFileName = $screenUid . '.' . $extension;
$screenFullPath = $path . DIRECTORY_SEPARATOR . $screenFileName;
try {
return $this->storeThumbnail( $imageContent, $screenFullPath );
} catch ( Exception $e ) {
return false;
}
}
public function getScreenshot( $screenUid, $postId = null ) {
$types = array( self::BLOCK_TYPE_NORMAL, self::BLOCK_TYPE_GLOBAL, self::BLOCK_TYPE_SAVED, self::BLOCK_TYPE_LAYOUT );
foreach ( $types as $type ) {
$filePath = $this->getScreenshotPath( $screenUid, $type, $postId );
$filePath = $filePath . DIRECTORY_SEPARATOR . "{$screenUid}.jpeg";
if ( file_exists( $filePath ) ) {
return $filePath;
}
}
return null;
}
private function getScreenshotPath( $screenUID, $blockType, $postID ) {
$folderPath = null;
switch ( $blockType ) {
case self::BLOCK_TYPE_NORMAL:
$this->urlBuilder->set_post_id( $postID );
$folderPath = $this->urlBuilder->page_upload_path( 'blockThumbnails' );
break;
case self::BLOCK_TYPE_GLOBAL:
$folderPath = $this->urlBuilder->brizy_upload_path( 'blockThumbnails' . DIRECTORY_SEPARATOR . 'global' );
break;
case self::BLOCK_TYPE_SAVED:
$folderPath = $this->urlBuilder->brizy_upload_path( 'blockThumbnails' . DIRECTORY_SEPARATOR . 'saved' );
break;
case self::BLOCK_TYPE_LAYOUT:
$folderPath = $this->urlBuilder->brizy_upload_path( 'blockThumbnails' . DIRECTORY_SEPARATOR . 'layout' );
break;
default:
return null;
}
return $folderPath;
}
/**
* @param $content
* @param $filePath
*
* @return bool
*/
private function storeThumbnail( $content, $filePath ) {
$store_file = $this->storeFile( $content, $filePath );
if ( $store_file ) {
$store_file = $this->resizeImage( $filePath );
}
return $store_file;
}
/**
* @param $content
* @param $thumbnailFullPath
*
* @return bool
*/
private function storeFile( $content, $thumbnailFullPath ) {
$path = dirname( $thumbnailFullPath );
if ( ! file_exists( $path ) ) {
if ( ! @mkdir( $path, 0755, true ) ) {
return false;
}
}
return file_put_contents( $thumbnailFullPath, $content ) !== false;
}
/**
* @param $thumbnailFullPath
*
* @return bool
*/
private function resizeImage( $thumbnailFullPath ) {
try {
$imageEditor = wp_get_image_editor( $thumbnailFullPath );
if ( $imageEditor instanceof WP_Error ) {
throw new Exception( $imageEditor->get_error_message() );
}
$imageEditor->resize( 600, 600 );
$result = $imageEditor->save( $thumbnailFullPath );
return is_array( $result );
} catch ( Exception $e ) {
return false;
}
}
/**
* @param $imageContent
*/
protected function validateImageContent( $imageContent ) {
file_put_contents( $tmpFilePath = tempnam( get_temp_dir(), 'screen' ), $imageContent );
$mime = Brizy_Public_AssetProxy::get_mime( $tmpFilePath );
if ( $mime !== 'image/jpeg' ) {
return false;
}
unlink( $tmpFilePath );
return true;
}
}

View File

@@ -0,0 +1,6 @@
<?php
interface Brizy_Editor_SignatureInterface {
public function checkSignature();
}

View File

@@ -0,0 +1,39 @@
<?php
class Brizy_Editor_Signature {
/**
* @param $term
*
* @return string
*/
static public function cleanTerm( $term ) {
return trim( str_ireplace(
array( 'http://', '\\', '/' ),
array( '' ),
$term
) );
}
/**
* @return array
*/
static private function getSignatureParts() {
return array(
get_option( 'siteurl' ),
defined('WP_SITEURL')?WP_SITEURL:'',
dirname( __FILE__ )
);
}
/**
* @return string
*/
static public function get() {
$pieces = self::getSignatureParts();
$md_5 = md5( self::cleanTerm( implode( '-', $pieces ) ) );
return $md_5;
}
}

View File

@@ -0,0 +1,67 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
abstract class Brizy_Editor_Storage_Abstract {
public function loadStorage( $value ) {
$this->update_storage( $value );
}
/**
* @param string $key
* @param $value
*
* @return Brizy_Editor_Storage_Abstract
*/
public function set( $key, $value ) {
$storage = $this->get_storage();
$storage[ $key ] = $value;
$this->update_storage( $storage );
return $this;
}
/**
* @param $key
* @param bool $thorw_if_notset
*
* @return mixed
* @throws Brizy_Editor_Exceptions_NotFound
*/
public function get( $key, $thorw_if_notset = true ) {
$storage = $this->get_storage();
if ( isset( $storage[ $key ] ) ) {
return $storage[ $key ];
}
if ( $thorw_if_notset ) {
throw new Brizy_Editor_Exceptions_NotFound( "The key [{$key}] was not found in storage." );
}
return null;
}
public function delete( $key ) {
$storage = $this->get_storage();
if ( isset( $storage[ $key ] ) ) {
unset( $storage[ $key ] );
$this->update_storage( $storage );
}
return $this;
}
/**
* @param array $storage
*
* @return Brizy_Editor_Storage_Abstract
*/
abstract protected function update_storage( $storage );
/**
* @return array
*/
abstract public function get_storage();
}

View File

@@ -0,0 +1,46 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Storage_Common extends Brizy_Editor_Storage_Abstract {
const KEY = 'brizy';
/**
* @return Brizy_Editor_Storage_Common
*/
public static function instance() {
static $instance;
if ( ! $instance ) {
$instance = new self();
}
return $instance;
}
/**
* @return array
*/
public function get_storage() {
$get_option = (array) get_option( $this->key(), array() );
return $get_option;
}
/**
* @param array $storage
*
* @return $this
*/
protected function update_storage( $storage ) {
update_option( $this->key(), $storage );
return $this;
}
protected function key() {
return self::KEY;
}
}

View File

@@ -0,0 +1,12 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Storage_PostSignature extends Brizy_Editor_Storage_Post {
const BRIZY_POST_SIGNATURE_KEY = 'brizy-post-signature';
protected function key() {
return self::BRIZY_POST_SIGNATURE_KEY;
}
}

View File

@@ -0,0 +1,61 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Storage_Post extends Brizy_Editor_Storage_Abstract {
const META_KEY = 'brizy';
protected $id;
/**
* @param $id
*
* @return Brizy_Editor_Storage_Post
*/
public static function instance( $id ) {
return new self( $id );
}
protected function __construct( $id ) {
$this->id = (int) $id;
}
protected function get_id() {
return $this->id;
}
/**
* @todo: rename this to get_data
*
* @return array
*/
public function get_storage() {
wp_cache_delete( $this->get_id(), 'post_meta');
$get_metadata = get_metadata( 'post', $this->get_id(), $this->key(), true );
if ( is_array( $get_metadata ) ) {
return $get_metadata;
}
return array();
}
/**
* @param array $storage
*
* @return $this
*/
protected function update_storage( $storage ) {
update_metadata( 'post', $this->get_id(), $this->key(), $storage );
return $this;
}
protected function key() {
return self::META_KEY;
}
}

View File

@@ -0,0 +1,21 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Storage_ProjectGlobals extends Brizy_Editor_Storage_Project {
const META_KEY = 'brizy-project-globals';
protected function key() {
return self::META_KEY;
}
/**
* @param $id
*
* @return Brizy_Editor_Storage_Post
*/
public static function instance( $id ) {
return new self( $id );
}
}

View File

@@ -0,0 +1,30 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_Storage_Project extends Brizy_Editor_Storage_Post {
const META_KEY = 'brizy-project';
protected function key() {
return self::META_KEY;
}
/**
* @param $id
*
* @return Brizy_Editor_Storage_Post
*/
public static function instance( $id ) {
return new self( $id );
}
public function loadStorage( $value ) {
if(!isset($value['data']) || is_null($value['data']) || empty($value['data'])) {
Brizy_Logger::instance()->critical( 'Execution stopped. Attempt to save invalid project data.', array( $value ) );
throw new Exception('Execution stopped. Attempt to save invalid project data.');
}
parent::loadStorage( $value );
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 1/18/19
* Time: 12:20 PM
*/
class Brizy_Editor_Story extends Brizy_Editor_Post
{
use Brizy_Editor_AutoSaveAware;
/**
* @var string
*/
protected $meta;
/**
* @var string
*/
protected $media;
/**
* @var self;
*/
static protected $block_instance = null;
public static function cleanClassCache()
{
self::$block_instance = array();
}
/**
* @param $apost
* @param null $uid
*
* @return Brizy_Editor_Story|Brizy_Editor_Post|mixed
* @throws Exception
*/
public static function get($apost, $uid = null)
{
$wp_post_id = $apost;
if ($apost instanceof WP_Post) {
$wp_post_id = $apost->ID;
}
if (isset(self::$block_instance[$wp_post_id])) {
return self::$block_instance[$wp_post_id];
}
return self::$block_instance[$wp_post_id] = new self($wp_post_id, $uid);
}
/**
* Brizy_Editor_Story constructor.
*
* @param $wp_post_id
* @param null $uid
*
* @throws Brizy_Editor_Exceptions_NotFound
* @throws Brizy_Editor_Exceptions_UnsupportedPostType
*/
public function __construct($wp_post_id, $uid = null)
{
if ($uid) {
$this->uid = $uid;
}
parent::__construct($wp_post_id);
}
/**
* @return bool
*/
public function uses_editor()
{
return true;
}
/**
* This should always return true
*
* @param $val
*
* @return $this
*/
public function set_uses_editor($val)
{
parent::set_uses_editor(true);
return $this;
}
public function save($autosave = 0)
{
parent::save($autosave);
if ($autosave !== 1) {
$this->savePost();
}
}
}

View File

@@ -0,0 +1,173 @@
<?php
trait Brizy_Editor_Synchronizable {
/**
* @var array
*/
protected $cloudId;
/**
* @var array
*/
protected $cloudAccountId;
/**
* @var string[]
*/
protected $synchronizedWith = [];
/**
* As our block class has two responsabilities :(
* we are forced to devine this method to restrict the logic of this
* trait only to instances that will return true
*
* @return mixed
*/
abstract protected function canBeSynchronized();
// /**
// * @return array
// */
// public function getCloudId() {
// return $this->cloudId;
// }
//
// /**
// * @param array $cloudId
// *
// * @return Brizy_Editor_Synchronizable
// */
// protected function setCloudId( $cloudId ) {
// $this->cloudId = $cloudId;
//
// return $this;
// }
// /**
// * @param string $meta
// *
// * @return Brizy_Editor_Block
// */
// public function setContainer( $container ) {
// update_metadata( 'post', $this->getWpPostId(), 'brizy-cloud-container', $container );
// }
//
// /**
// * @return array|false|mixed|string|null
// */
// public function getContainer() {
// return get_metadata( 'post', $this->getWpPostId(), 'brizy-cloud-container', true );
// }
//
//
// /**
// * @return array
// */
// protected function getCloudAccountId() {
// return $this->cloudAccountId;
// }
//
// /**
// * @param array $cloudAccountId
// *
// * @return Brizy_Editor_Synchronizable
// */
// protected function setCloudAccountId( $cloudAccountId ) {
// $this->cloudAccountId = $cloudAccountId;
//
// return $this;
// }
/**
* @param $cloudAccountId
*
* @return string|null
*/
public function getCloudId( $cloudAccountId ) {
if ( isset( $this->synchronizedWith[ $cloudAccountId ] ) ) {
return $this->synchronizedWith[ $cloudAccountId ];
}
return null;
}
/**
* Load synchronisation data
*/
public function loadSynchronizationData() {
$key = 'brizy-cloud-synchronised-with';
$this->synchronizedWith = get_metadata( 'post', $this->getWpPostId(), $key, true );
if ( ! is_array( $this->synchronizedWith ) ) {
$this->synchronizedWith = [];
}
}
/**
* @return bool
*/
public function isCloudUpdateRequired() {
if ( $this->canBeSynchronized() ) {
return (bool) get_metadata( 'post', $this->getWpPostId(), 'brizy-cloud-update-required', true );
}
return false;
}
/**
* @param bool $cloudUpdateRequired
*
* @return Brizy_Editor_Block
*/
// public function setCloudUpdateRequired( $cloudUpdateRequired ) {
//
// if ( $this->canBeSynchronized() ) {
// update_metadata( 'post', $this->getWpPostId(), 'brizy-cloud-update-required', (int) $cloudUpdateRequired ? true : false );
// }
//
// return $this;
// }
/**
* @param $cloudAccountId
* @param $cloudId
*
* @return $this
*/
public function setSynchronized( $cloudAccountId, $cloudId ) {
if ( $this->canBeSynchronized() ) {
$key = 'brizy-cloud-synchronised-with';
$this->synchronizedWith[ $cloudAccountId ] = $cloudId;
update_metadata( 'post', $this->getWpPostId(), $key, $this->synchronizedWith );
//$this->setCloudUpdateRequired( false );
}
return $this;
}
public function isSynchronized( $cloudAccountId ) {
if ( $this->canBeSynchronized() ) {
return isset( $this->synchronizedWith[ $cloudAccountId ] );
}
return false;
}
/**
* We should allow only the new versions of blocks and layouts to be syncronized
*
* @param $cloudAccountId
*
* @return bool
*/
public function isSynchronizable( $cloudAccountId ) {
if ( $this->canBeSynchronized() ) {
return metadata_exists( 'post', $this->getWpPostId(), 'brizy-media' );
}
return false;
}
}

View File

@@ -0,0 +1,436 @@
<?php
class Brizy_Editor_UrlBuilder
{
/**
* @var Brizy_Editor_Project
*/
protected $project;
/**
* @var Brizy_Editor_Post
*/
protected $post;
/**
* @var int
*/
protected $post_id;
/**
* @var array
*/
protected $upload_dir;
/**
* Brizy_Editor_UrlBuilder constructor.
*
* @param Brizy_Editor_Project|null $project
* @param int|null $post_id
*/
public function __construct($project = null, $post_id = null)
{
$this->post_id = $post_id;
$this->upload_dir = Brizy_Admin_UploadDir::getUploadDir(null, true);
}
/**
* @return Brizy_Admin_UrlIterator
*/
public function compiler_url()
{
return Brizy_Config::getCompilerUrls();
}
public function application_form_notification_url()
{
$urls = array(Brizy_Config::BRIZY_APPLICATION_FORM_NOTIFICATION_URL);
return new Brizy_Admin_UrlIterator($urls);
}
/**
* @param string $path
* @param string $path
*
* @return string
*/
public function plugin_url($path = '')
{
if ($path) {
$path = '/' . ltrim($path, '/');
}
return BRIZY_PLUGIN_URL . $path;
}
/**
* @param string $path
* @param string $path
*
* @return string
*/
public function plugin_path($path = '')
{
if ($path) {
$path = '/' . ltrim($path, '/');
}
return BRIZY_PLUGIN_PATH . $path;
}
/**
* @param $post
*/
public function set_post_id($post_id)
{
$this->post_id = $post_id;
}
public function multipass_url()
{
return set_url_scheme(admin_url('admin-ajax.php')) . "?action=brizy_multipass_create&client_id=" . Brizy_Config::BRIZY_APPLICATION_FORM_ID;
}
public function proxy_url($end_point)
{
$params = array();
if ($this->post_id) {
$params[Brizy_Editor::prefix('_post')] = ((int)$this->post_id);
}
// do not move this line
$params[Brizy_Editor::prefix()] = $end_point;
return add_query_arg($params, home_url('/'));
}
/**
* @param string $end_point
*
* @return string
*/
// public function media_proxy_url( $end_point = '' ) {
//
// $end_point = ltrim( $end_point, "/" );
//
// return $this->proxy_url( "/media/" . $end_point );
// }
/**
* @param $path
*
* @return string
*/
public function upload_path($path = null)
{
if ($path) {
$path = '/' . ltrim($path, '/');
}
return wp_normalize_path($this->upload_dir['basedir'] . $path);
}
/**
* @param $path
*
* @return string
*/
public function upload_url($path = null)
{
if ($path) {
$path = "/" . ltrim($path, "/");
}
return $this->upload_dir['baseurl'] . $path;
}
/**
* @param $path
*
* @return string
*/
public function brizy_upload_path($path = null)
{
if ($path) {
$path = ltrim($path, '/');
}
return $this->upload_path(sprintf(Brizy_Config::LOCAL_PAGE_ASSET_STATIC_URL, $path));
}
/**
* @param $path
*
* @return string
*/
public function wp_upload_path($path = null)
{
if ( $path ) {
$path = ltrim( $path, '/' );
}
return $this->upload_dir['path'] . '/' . $path;
}
/**
* @param $path
*
* @return string
*/
public function wp_upload_relative_path( $path )
{
$path = ltrim( $path, '/' );
if ( empty( $this->upload_dir['subdir'] ) || $this->upload_dir['subdir'] == '/' ) {
return $path;
}
return ltrim( $this->upload_dir['subdir'] . '/' . $path, '/' );
}
/**
* @param $path
*
* @return string
*/
public function brizy_upload_relative_path($path = null)
{
if ($path) {
$path = ltrim($path, '/');
}
return ltrim(sprintf(Brizy_Config::LOCAL_PAGE_ASSET_STATIC_URL, $path), "/");
}
/**
* @param $path
*
* @return string
*/
public function brizy_upload_url($path = null)
{
if ($path) {
$path = ltrim($path, "/");
}
return $this->upload_url(sprintf(Brizy_Config::LOCAL_PAGE_ASSET_STATIC_URL, $path));
}
/**
* This will return the relative path to the upload dir.
* ex: /brizy/pages/3/x.jpg
*
* @param null $path
* @param null $post_id
*
* @return string
*/
public function page_upload_path($path = null, $post_id = null)
{
if (is_null($post_id) && $this->post_id) {
$post_id = (int)$this->post_id;
}
if ($path) {
$path = '/' . ltrim($path, '/');
}
return $this->brizy_upload_path($post_id . $path);
}
public function page_upload_relative_path($path = null, $post_id = null)
{
if (is_null($post_id) && $this->post_id) {
$post_id = (int)$this->post_id;
}
if ($path) {
$path = '/' . ltrim($path, '/');
}
return $this->brizy_upload_relative_path($post_id . $path);
}
/**
* @param null $path
* @param null $post_id
*
* @return string
*/
public function page_upload_url($path = null, $post_id = null)
{
if (is_null($post_id) && $this->post_id) {
$post_id = (int)$this->post_id;
}
if ($path) {
$path = '/' . ltrim($path, '/');
}
return $this->brizy_upload_url($post_id . $path);
}
/**
* @param null $path
*
* @return string
*/
public function editor_asset_path($path = null)
{
if ($path) {
$path = '/' . ltrim($path, '/');
}
return $this->brizy_upload_path('editor' . $path);
}
/**
* @param null $path
*
* @return string
*/
public function editor_build_url()
{
return Brizy_Config::EDITOR_BUILD_URL;
}
/**
* @param null $path
*
* @return string
*/
static public function editor_build_path($path = null)
{
if ($path) {
$path = '/' . ltrim(
str_replace(array('/', '\\'), '/', $path),
'/');
}
return Brizy_Config::EDITOR_BUILD_PATH . $path;
}
/**
* @param null $path
*
* @return string
*/
public function media_asset_path($path = null)
{
if ($path) {
$path = '/' . ltrim($path, '/');
}
return $this->brizy_upload_path("media" . $path);
}
/**
* @param null $path
*
* @return string
*/
public function media_asset_url($path = null)
{
if ($path) {
$path = "/" . ltrim($path, "/");
}
return $this->brizy_upload_url("media" . $path);
}
/**
* @param null $path
*
* @return string
*/
public function external_media_url($path = null)
{
if ($path) {
$path = "/" . ltrim($path, "/");
}
$url = Brizy_Config::MEDIA_IMAGE_URL . $path;
$urls = array();
foreach (Brizy_Config::getEditorBaseUrls() as $baseUrl) {
$urls[] = $baseUrl . $url;
}
return new Brizy_Admin_UrlIterator($urls);
}
/**
* @param null $path
*
* @return string
*/
public function external_custom_file($uid, $fileName = null)
{
$result = [];
$brizyCloudUrls = Brizy_Config::getEditorBaseUrls();
foreach ($brizyCloudUrls as $url) {
$result[] = (string)$url . '/customfile/' . $uid . '/' . $fileName;
}
return new Brizy_Admin_UrlIterator($result);
}
/**
* @param null $path
* @param null $template_version
*
* @return Brizy_Admin_UrlIterator
*/
public function external_asset_url($path = null, $template_version = null)
{
if (is_null($template_version)) {
$template_version = BRIZY_EDITOR_VERSION;
}
if ($path) {
$path = "/" . ltrim($path, "/");
}
$urls = array();
foreach (Brizy_Config::getStaticUrls() as $url) {
$urls[] = sprintf($url . $path, $template_version);
}
return new Brizy_Admin_UrlIterator($urls);
}
/**
* @param null $template_version
*
* @return string
*/
public function external_fonts_url($template_version = null)
{
if (is_null($template_version)) {
$template_version = BRIZY_EDITOR_VERSION;
}
$url = Brizy_Config::getFontsUrl();
return sprintf($url, $template_version);
}
}

View File

@@ -0,0 +1,183 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_User {
private static $is_allowed_for_current_user;
private static $instance;
/**
* @var Brizy_Editor_API_AccessToken
*/
private $token;
/**
* @var Brizy_Editor_Storage_Common
*/
private $common_storage;
/**
* @var string
*/
private $platform_user_id;
/**
* @var string
*/
private $platform_user_email;
/**
* @var string
*/
private $platform_user_signature;
/**
* Brizy_Editor_User constructor.
*
* @param $common_storage
*
* @throws Brizy_Editor_Exceptions_NotFound
*/
protected function __construct( $common_storage ) {
$this->common_storage = $common_storage;
$this->platform_user_id = $common_storage->get( 'platform_user_id' );
$this->platform_user_email = $common_storage->get( 'platform_user_email' );
$this->platform_user_signature = $common_storage->get( 'platform_user_signature' );
$token_data = $common_storage->get( 'access-token', false );
if ( $token_data instanceof Brizy_Editor_API_AccessToken ) {
$this->token = $token_data;
$common_storage->set( 'access-token', $token_data->convertToOptionValue() );
} elseif ( is_array( $token_data ) ) {
$this->token = Brizy_Editor_API_AccessToken::createFromSerializedData( $token_data );
}
}
/**
* @return Brizy_Editor_User
* @throws Brizy_Editor_Exceptions_ServiceUnavailable
* @throws Exception
*/
public static function get() {
if ( self::$instance ) {
return self::$instance;
}
$user = null;
try {
$user = new Brizy_Editor_User( Brizy_Editor_Storage_Common::instance() );
} catch ( Brizy_Editor_Exceptions_NotFound $e ) {
Brizy_Logger::instance()->notice( 'New user created' );
Brizy_Editor_Storage_Common::instance()->set( 'platform_user_local', true );
Brizy_Editor_Storage_Common::instance()->set( 'platform_user_id', uniqid( 'user', true ) );
Brizy_Editor_Storage_Common::instance()->set( 'platform_user_email', self::generateRandomEmail() );
Brizy_Editor_Storage_Common::instance()->set( 'platform_user_signature', Brizy_Editor_Signature::get() );
$user = new Brizy_Editor_User( Brizy_Editor_Storage_Common::instance() );
}
return self::$instance = $user;
}
public static function reload() {
return self::$instance = new self( Brizy_Editor_Storage_Common::instance() );
}
/**
* @return string
*/
static protected function generateRandomEmail() {
$uniqid = 'brizy-' . md5( uniqid( '', true ) );
return $uniqid . '@brizy.io';
}
/**
* @param Brizy_Editor_Project $project
* @param Brizy_Editor_Post $post
*
* @return array
* @throws Brizy_Editor_API_Exceptions_Exception
* @throws Brizy_Editor_Http_Exceptions_BadRequest
* @throws Brizy_Editor_Http_Exceptions_ResponseException
* @throws Brizy_Editor_Http_Exceptions_ResponseNotFound
* @throws Brizy_Editor_Http_Exceptions_ResponseUnauthorized
* @throws Exception
*/
public function compile_page( $project, $post ) {
$editor_data = $post->get_editor_data();
$config = Brizy_Editor_Editor_Editor::get( $project, $post )->config(Brizy_Editor_Editor_Editor::COMPILE_CONTEXT);
$urlBuilder = new Brizy_Editor_UrlBuilder( $project, $post->getWpPostId() );
return $this->get_client()->compile_page( $project, $editor_data, $config, $urlBuilder->compiler_url() );
}
public static function is_administrator() {
if ( ! is_user_logged_in() ) {
return false;
}
return current_user_can( 'manage_options' ) || is_super_admin();
}
public static function is_user_allowed() {
if ( ! is_user_logged_in() ) {
return false;
}
if ( Brizy_Editor_User::is_administrator() ) {
return true;
}
if ( is_null( self::$is_allowed_for_current_user ) ) {
self::$is_allowed_for_current_user =
(
current_user_can( Brizy_Admin_Capabilities::CAP_EDIT_WHOLE_PAGE ) ||
current_user_can( Brizy_Admin_Capabilities::CAP_EDIT_CONTENT_ONLY )
);
}
return self::$is_allowed_for_current_user;
}
protected function get_token() {
return $this->token;
}
protected function get_client() {
return new Brizy_Editor_API_Client( $this->get_token() );
}
/**
* @return string
*/
public function getPlatformUserId() {
return $this->platform_user_id;
}
/**
* @return string
*/
public function getPlatformUserEmail() {
return $this->platform_user_email;
}
/**
* @return string
*/
public function getPlatformUserSignature() {
return $this->platform_user_signature;
}
}

View File

@@ -0,0 +1,22 @@
<?php if ( ! defined( 'ABSPATH' ) ) {
die( 'Direct access forbidden.' );
}
class Brizy_Editor_View {
public static function render( $path, $args = array() ) {
$file = $path . '.php';
if ( ! file_exists( $file ) ) {
return;
}
extract( $args );
include $file;
}
public static function get( $path, $args = array() ) {
ob_start();
self::render( $path, $args );
return ob_get_clean();
}
}

View File

@@ -0,0 +1,67 @@
<?php
class Brizy_Editor_Zip_ArchiveItem {
/**
* @var Brizy_Editor_Post
*/
private $post;
/**
* @var bool
*/
private $pro;
/**
* @var string
*/
private $uid;
public function __construct( $uid, $isPro ) {
$this->pro = $isPro;
$this->uid = $uid;
}
/**
* @return Brizy_Editor_Post
*/
public function getPost() {
return $this->post;
}
/**
* @param Brizy_Editor_Post $post
*
* @return Brizy_Editor_Zip_ArchiveItem
*/
public function setPost( $post ) {
$this->post = $post;
return $this;
}
/**
* @return bool
*/
public function isPro() {
return $this->pro;
}
/**
* @param bool $pro
*
* @return Brizy_Editor_Zip_ArchiveItem
*/
public function setIsPro( $pro ) {
$this->pro = $pro;
return $this;
}
/**
* @return mixed
*/
public function getUid() {
return $this->uid;
}
}

View File

@@ -0,0 +1,14 @@
<?php
interface Brizy_Editor_Zip_ArchiverInterface {
public function createZip( $posts, $fileName );
public function createFromZip( $zipPath );
public function getEditorVersion();
public function isVersionSupported($version);
public function getScreenshotType($archiveType);
}

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