/homeprezzo-embed.php
PHP | 445 lines | 337 code | 86 blank | 22 comment | 26 complexity | bb3baa023599dff5333e046da5e4d4a1 MD5 | raw file
- <?php
-
- /**
- * Plugin Name: HomePrezzo Embed
- * Plugin URI:
- * Description: Provides embed codes to HomePrezzo Prezzos via WordPress shortcodes
- * Version: 1.0.0
- * Author: HomePrezzo
- * Author URI: https://homeprezzo.com.au
- * Text Domain: homeprezzo-embed
- * License: GPL-2.0+
- * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
- */
-
- class HomeprezzoEmbed {
-
- const prefix = 'homeprezzo_embed_';
-
- private $settings = [
- 'client_id' => '',
- 'client_secret' => '',
- 'scope' => 'readPrezzo readUserProfile readJournoAiContent suggestionSearch',
- 'accessToken' => '',
- 'accessTokenExpiry' => '',
- 'refreshToken' => '',
- 'refreshTokenExpiry' => '',
- 'username' => '',
- ];
-
- private $config = [
- 'scope' => 'readPrezzo readUserProfile readJournoAiContent suggestionSearch',
- ];
-
- private static $instance;
-
- public static function getInstance() {
-
- # If the plugin has not been instantiated
- if (null === static::$instance) {
-
- # Instantiate the plugin as a static instance
- static::$instance = new HomeprezzoEmbed();
- }
-
- # Return the plugin instance
- return static::$instance;
- }
-
- protected function __construct() {
-
- $this->config['redirect'] = (
- (
- (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ||
- (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
- )
- ? preg_replace("/http:/", 'https:', get_site_url())
- : get_site_url()
- ) . '/index.php?homeprezzo-embed';
-
- register_activation_hook(__FILE__, array($this, 'activate'));
- register_deactivation_hook(__FILE__, array($this, 'deactivate'));
- self::add_shortcodes();
- self::add_filters();
- self::add_actions();
- self::add_options_page();
- self::add_javascript();
- self::add_rewrites();
- self::add_editor_plugins();
- self::add_editor_buttons();
-
- }
-
- private function __clone() {
- }
-
- private function __wakeup() {
- }
-
- private function getSetting($setting) {
-
- $settings = get_option(self::prefix . 'settings', $this->settings);
-
- return (isset($settings[$setting])) ? $settings[$setting] : NULL;
-
- }
-
- private function setSetting($setting, $value) {
-
- $settings = get_option(self::prefix . 'settings', $this->settings);
-
- $settings[$setting] = $value;
-
- update_option(self::prefix . 'settings', $settings);
-
- }
-
- private function getConfig($option) {
- return $this->config[$option];
- }
-
- public function activate() {
-
- add_option(self::prefix . 'settings', $this->settings);
-
- }
-
- public function deactivate() {
-
- delete_option(self::prefix . 'settings');
-
- }
-
- public function add_shortcodes() {
- add_shortcode('hpe', array($this, 'shortcode_embed'));
- }
-
- public function shortcode_embed($atts) {
- $embed_url = 'https://app.homeprezzo.com.au/embed.js?id=' . urlencode($atts['p']);
- if (isset($atts['c'])) {
- $embed_url .= '&background=' . urlencode(urlencode($atts['c']));
- }
- $embed = "
- <div class=\"homeprezzo-embed\">
- <script language=\"javascript\" src=\"{$embed_url}\"></script>
- </div>
- ";
- return $embed;
- }
-
- public function add_filters() {
-
- add_filter('query_vars', array($this, 'query_vars'));
-
- }
-
- public function add_actions() {
-
- add_action('parse_request', array($this, 'request_parsers'));
-
- }
-
- public function add_rewrites() {
- add_action('init', array($this, 'rewrites'));
- }
-
- public function add_editor_buttons() {
- add_filter('mce_buttons', array($this, 'register_mce_embed_button'));
- }
-
- public function add_editor_plugins() {
- add_filter('mce_external_plugins', array($this, 'enqueue_mce_embed'));
- add_action("admin_print_footer_scripts", array($this, 'enqueue_qtags'));
- }
-
- public function enqueue_mce_embed($plugins) {
- $plugins['homeprezzo_embed_shortcode'] = plugin_dir_url(__FILE__) . 'js/mce.homeprezzo-embed.js';
- return $plugins;
- }
-
- public function register_mce_embed_button($buttons) {
- $buttons[] = 'homeprezzo-embed-shortcode';
- return $buttons;
- }
-
- public function rewrites() {
- add_rewrite_rule('^homeprezzo-embed/?', 'index.php?homeprezzo-embed', 'top');
- add_rewrite_rule('^homeprezzo-embed/prezzos/?', 'index.php?homeprezzo-embed=0&f=prezzos', 'top');
- }
-
- public function request_parsers($wp) {
- if (
- array_key_exists('homeprezzo-embed', $wp->query_vars) &&
- array_key_exists('code', $wp->query_vars)
- ) {
- self::doRemoteAuth($wp->query_vars);
- }
- elseif (
- array_key_exists('homeprezzo-embed', $wp->query_vars) &&
- array_key_exists('f', $wp->query_vars)
- ) {
- if (!self::getSetting('accessToken')) {
- header('Content-Type: text/json');
- print json_encode([
- 'error' => 'No Access Token'
- ]);
- exit;
- }
- /*var_dump(strtotime(self::getSetting('accessTokenExpiry')),
- self::getSetting('accessTokenExpiry'),
- time(),
- date("Y-m-d H:i:s", time()),
- (strtotime(self::getSetting('accessTokenExpiry')) - time()));
- exit;*/
- if ((strtotime(self::getSetting('accessTokenExpiry')) - time()) < 3600) {
- self::refreshToken();
- }
- switch ($wp->query_vars['f']) {
- case 'prezzos':
- self::fetchPrezzos();
- break;
- }
- }
- }
-
- private function fetchPrezzos() {
-
- $response = wp_remote_get('https://api.homeprezzo.com.au/v1/prezzos', [
- 'headers' => [
- 'Authorization' => 'Bearer ' . self::getSetting('accessToken'),
- ],
- ]);
-
- if ($response['response']['code'] === 200) {
- header('Content-Type: text/json');
- print $response['body'];
- exit;
- }
-
- else {
- header('Content-Type: text/json');
- print json_encode([
- //'error' => 'Error Fetching Prezzos'
- 'error' => $response
- ]);
- exit;
- }
-
- }
-
- private function refreshToken() {
-
- $response = wp_remote_post('https://api.homeprezzo.com.au/oauth/token', [
- 'method' => 'POST',
- 'body' => [
- 'refresh_token' => self::getSetting('refreshToken'),
- 'grant_type' => 'refresh_token',
- 'client_id' => self::getSetting('client_id'),
- 'client_secret' => self:: getSetting('client_secret'),
- ],
- ]);
- if ($response['response']['code'] === 200) {
- $data = json_decode($response['body']);
- self::setSetting('accessToken', $data->accessToken);
- self::setSetting('accessTokenExpiry', $data->accessTokenExpiresAt);
- self::setSetting('refreshToken', $data->refreshToken);
- self::setSetting('refreshTokenExpiry', $data->refreshTokenExpiresAt);
- }
-
- else {
- header('Content-Type: text/json');
- print json_encode([
- //'error' => 'Token Refresh Failed'
- 'error' => $response,
- ]);
- exit;
- }
-
- }
-
- private function doRemoteAuth($query) {
- $response = wp_remote_post('https://api.homeprezzo.com.au/oauth/token', [
- 'method' => 'POST',
- 'body' => [
- 'code' => $query['code'],
- 'client_id' => self::getSetting('client_id'),
- 'client_secret' => self::getSetting('client_secret'),
- 'grant_type' => 'authorization_code',
- ],
- ]);
- if ($response['response']['code'] === 200) {
- $data = json_decode($response['body']);
- self::setSetting('accessToken', $data->accessToken);
- self::setSetting('accessTokenExpiry', $data->accessTokenExpiresAt);
- self::setSetting('refreshToken', $data->refreshToken);
- self::setSetting('refreshTokenExpiry', $data->refreshTokenExpiresAt);
- self::setSetting('username', $data->user->username);
- print '
- <html>
- <head></head>
- <body>
- <script>
- window.parent.location.reload();
- </script>
- </body>
- </html>
- ';
- exit;
- }
- }
-
- public function query_vars($qvars) {
-
- $qvars[] = 'homeprezzo-embed';
- $qvars[] = 'code';
- $qvars[] = 'f';
- return $qvars;
-
- }
-
- public function isAuthenticated() {
-
- if (
- self::getSetting('refreshToken') &&
- (
- self::getSetting('refreshTokenExpiry') &&
- strtotime(self::getSetting('refreshTokenExpiry')) > time()
- )
- ) {
- return true;
- }
- return false;
- }
-
- public function getUsername() {
- return $this->getSetting('username');
- }
-
- public function add_javascript() {
- add_action('admin_enqueue_scripts', array($this, 'enqueue_javascript_core'));
- }
-
- public function enqueue_javascript_core() {
-
- $data = [
- 'settings' => [
- 'client_id' => self::getSetting('client_id'),
- 'icon' => plugin_dir_url(__FILE__) . 'assets/images/homeprezzo-icon-32.png',
- ]
- ];
-
- wp_enqueue_script('homeprezzo-embed', plugin_dir_url(__FILE__) . 'js/homeprezzo-embed.js',[
- 'jquery',
- 'jquery-ui-dialog',
- 'wp-color-picker',
- ]);
- wp_localize_script('homeprezzo-embed', 'HomeprezzoEmbed', $data);
- wp_enqueue_style('wp-jquery-ui-dialog');
- wp_enqueue_style('wp-color-picker');
-
- }
-
- public function enqueue_qtags() {
- if (wp_script_is("quicktags")) {
- ?>
- <script type="text/javascript">
-
- QTags.addButton(
- "homeprezzo_embed",
- "prezzo",
- homeprezzoEmbedQTagsCallback
- );
-
- function homeprezzoEmbedQTagsCallback()
- {
- $.fn.homeprezzoEmbed('qtags');
- }
- </script>
- <?php
- }
- }
-
- public function add_options_page() {
-
- require_once('lib/RationalOptionPages.php');
-
- $pages = [
- self::prefix . 'settings' => [
- 'parent_slug' => 'options-general.php',
- 'page_title' => __('HomePrezzo Embed', 'text-domain'),
- 'icon_url' => 'dashicons-chart-area',
- ]
- ];
-
- if (!(self::getSetting('client_id') && self::getSetting('client_secret'))) {
- $pages[self::prefix . 'settings']['sections']['client_authentication'] = [
- 'id' => 'client_authentication',
- 'title' => __('Client Authentication', 'text-domain'),
- 'fields' => [
- 'client_id' => [
- 'title' => __('Client ID', 'text-domain'),
- 'type' => 'text',
- 'class' => 'client-id regular-text',
- ],
- 'client_secret' => [
- 'title' => __('Client Secret', 'text-domain'),
- 'type' => 'password',
- 'class' => 'client-secret regular-text',
- ],
- ],
- ];
-
- if (self::getSetting('client_id') && self::getSetting('client_secret')) {
- $pages[self::prefix . 'settings']['sections']['client_authentication']['text'] =
- '<p><a href="#" data-context="homeprezzo-embed-client-detail" data-alt-text="' .
- __('Click to hide your client details', 'text-domain') . '">' .
- __('Click to edit your client details', 'text-domain') . '</a>';
- }
- else {
- $pages[self::prefix . 'settings']['sections']['client_authentication']['text'] =
- '<p>' . __('Please supply your client credentials below. If you don\'t yet
- have client credentials please contact us at ', 'text-domain') .
- '<a href="mailto:support@homeprezzo.com">support@homeprezzo.com</a>.';
- }
- }
-
- if (self::getSetting('client_id') && self::getSetting('client_secret')) {
-
- $pages[self::prefix . 'settings']['sections']['user_authentication'] = [
- 'title' => __('User Authentication', 'text-domain'),
- ];
-
- if (self::isAuthenticated()) {
-
- $pages[self::prefix . 'settings']['sections']['user_authentication']['text'] =
- "<p>" .
- sprintf(
- __("You're connected to HomePrezzo as %s", 'text-domain'),
- self::getUsername()
- ) .
- "</p>";
-
- }
-
- else {
-
- $pages[self::prefix . 'settings']['sections']['user_authentication']['text'] =
- "
- <p>" . __("Authorize the plugin to use a HomePrezzo user's data.", 'text-domain') . "</p>
- <p><button type=\"button\" data-context=\"homeprezzo-embed-connect\">" . __("Click to Connect", 'text-domain') .
- "</button></p><div data-context=\"homeprezzo-embed-connect-dialog\" title=\"Connect to HomePrezzo\">
- <iframe scrolling=\"no\" height=\"360\" width=\"100%\" src=\"https://app.homeprezzo.com.au/login-api?client_id=" . urlencode(self::getSetting('client_id')) . "&redirect=" . urlencode(self::getConfig('redirect')) . "&scope=" . urlencode(self::getConfig('scope')) . "\" />
- </div>
- ";
-
- }
-
- }
-
- $options = new RationalOptionPages($pages);
-
- }
-
- }
-
- HomeprezzoEmbed::getInstance();