PageRenderTime 47ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/homeprezzo-embed.php

https://bitbucket.org/homeprezzo/homeprezzo-wp-embed
PHP | 445 lines | 337 code | 86 blank | 22 comment | 26 complexity | bb3baa023599dff5333e046da5e4d4a1 MD5 | raw file
  1. <?php
  2. /**
  3. * Plugin Name: HomePrezzo Embed
  4. * Plugin URI:
  5. * Description: Provides embed codes to HomePrezzo Prezzos via WordPress shortcodes
  6. * Version: 1.0.0
  7. * Author: HomePrezzo
  8. * Author URI: https://homeprezzo.com.au
  9. * Text Domain: homeprezzo-embed
  10. * License: GPL-2.0+
  11. * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
  12. */
  13. class HomeprezzoEmbed {
  14. const prefix = 'homeprezzo_embed_';
  15. private $settings = [
  16. 'client_id' => '',
  17. 'client_secret' => '',
  18. 'scope' => 'readPrezzo readUserProfile readJournoAiContent suggestionSearch',
  19. 'accessToken' => '',
  20. 'accessTokenExpiry' => '',
  21. 'refreshToken' => '',
  22. 'refreshTokenExpiry' => '',
  23. 'username' => '',
  24. ];
  25. private $config = [
  26. 'scope' => 'readPrezzo readUserProfile readJournoAiContent suggestionSearch',
  27. ];
  28. private static $instance;
  29. public static function getInstance() {
  30. # If the plugin has not been instantiated
  31. if (null === static::$instance) {
  32. # Instantiate the plugin as a static instance
  33. static::$instance = new HomeprezzoEmbed();
  34. }
  35. # Return the plugin instance
  36. return static::$instance;
  37. }
  38. protected function __construct() {
  39. $this->config['redirect'] = (
  40. (
  41. (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ||
  42. (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
  43. )
  44. ? preg_replace("/http:/", 'https:', get_site_url())
  45. : get_site_url()
  46. ) . '/index.php?homeprezzo-embed';
  47. register_activation_hook(__FILE__, array($this, 'activate'));
  48. register_deactivation_hook(__FILE__, array($this, 'deactivate'));
  49. self::add_shortcodes();
  50. self::add_filters();
  51. self::add_actions();
  52. self::add_options_page();
  53. self::add_javascript();
  54. self::add_rewrites();
  55. self::add_editor_plugins();
  56. self::add_editor_buttons();
  57. }
  58. private function __clone() {
  59. }
  60. private function __wakeup() {
  61. }
  62. private function getSetting($setting) {
  63. $settings = get_option(self::prefix . 'settings', $this->settings);
  64. return (isset($settings[$setting])) ? $settings[$setting] : NULL;
  65. }
  66. private function setSetting($setting, $value) {
  67. $settings = get_option(self::prefix . 'settings', $this->settings);
  68. $settings[$setting] = $value;
  69. update_option(self::prefix . 'settings', $settings);
  70. }
  71. private function getConfig($option) {
  72. return $this->config[$option];
  73. }
  74. public function activate() {
  75. add_option(self::prefix . 'settings', $this->settings);
  76. }
  77. public function deactivate() {
  78. delete_option(self::prefix . 'settings');
  79. }
  80. public function add_shortcodes() {
  81. add_shortcode('hpe', array($this, 'shortcode_embed'));
  82. }
  83. public function shortcode_embed($atts) {
  84. $embed_url = 'https://app.homeprezzo.com.au/embed.js?id=' . urlencode($atts['p']);
  85. if (isset($atts['c'])) {
  86. $embed_url .= '&background=' . urlencode(urlencode($atts['c']));
  87. }
  88. $embed = "
  89. <div class=\"homeprezzo-embed\">
  90. <script language=\"javascript\" src=\"{$embed_url}\"></script>
  91. </div>
  92. ";
  93. return $embed;
  94. }
  95. public function add_filters() {
  96. add_filter('query_vars', array($this, 'query_vars'));
  97. }
  98. public function add_actions() {
  99. add_action('parse_request', array($this, 'request_parsers'));
  100. }
  101. public function add_rewrites() {
  102. add_action('init', array($this, 'rewrites'));
  103. }
  104. public function add_editor_buttons() {
  105. add_filter('mce_buttons', array($this, 'register_mce_embed_button'));
  106. }
  107. public function add_editor_plugins() {
  108. add_filter('mce_external_plugins', array($this, 'enqueue_mce_embed'));
  109. add_action("admin_print_footer_scripts", array($this, 'enqueue_qtags'));
  110. }
  111. public function enqueue_mce_embed($plugins) {
  112. $plugins['homeprezzo_embed_shortcode'] = plugin_dir_url(__FILE__) . 'js/mce.homeprezzo-embed.js';
  113. return $plugins;
  114. }
  115. public function register_mce_embed_button($buttons) {
  116. $buttons[] = 'homeprezzo-embed-shortcode';
  117. return $buttons;
  118. }
  119. public function rewrites() {
  120. add_rewrite_rule('^homeprezzo-embed/?', 'index.php?homeprezzo-embed', 'top');
  121. add_rewrite_rule('^homeprezzo-embed/prezzos/?', 'index.php?homeprezzo-embed=0&f=prezzos', 'top');
  122. }
  123. public function request_parsers($wp) {
  124. if (
  125. array_key_exists('homeprezzo-embed', $wp->query_vars) &&
  126. array_key_exists('code', $wp->query_vars)
  127. ) {
  128. self::doRemoteAuth($wp->query_vars);
  129. }
  130. elseif (
  131. array_key_exists('homeprezzo-embed', $wp->query_vars) &&
  132. array_key_exists('f', $wp->query_vars)
  133. ) {
  134. if (!self::getSetting('accessToken')) {
  135. header('Content-Type: text/json');
  136. print json_encode([
  137. 'error' => 'No Access Token'
  138. ]);
  139. exit;
  140. }
  141. /*var_dump(strtotime(self::getSetting('accessTokenExpiry')),
  142. self::getSetting('accessTokenExpiry'),
  143. time(),
  144. date("Y-m-d H:i:s", time()),
  145. (strtotime(self::getSetting('accessTokenExpiry')) - time()));
  146. exit;*/
  147. if ((strtotime(self::getSetting('accessTokenExpiry')) - time()) < 3600) {
  148. self::refreshToken();
  149. }
  150. switch ($wp->query_vars['f']) {
  151. case 'prezzos':
  152. self::fetchPrezzos();
  153. break;
  154. }
  155. }
  156. }
  157. private function fetchPrezzos() {
  158. $response = wp_remote_get('https://api.homeprezzo.com.au/v1/prezzos', [
  159. 'headers' => [
  160. 'Authorization' => 'Bearer ' . self::getSetting('accessToken'),
  161. ],
  162. ]);
  163. if ($response['response']['code'] === 200) {
  164. header('Content-Type: text/json');
  165. print $response['body'];
  166. exit;
  167. }
  168. else {
  169. header('Content-Type: text/json');
  170. print json_encode([
  171. //'error' => 'Error Fetching Prezzos'
  172. 'error' => $response
  173. ]);
  174. exit;
  175. }
  176. }
  177. private function refreshToken() {
  178. $response = wp_remote_post('https://api.homeprezzo.com.au/oauth/token', [
  179. 'method' => 'POST',
  180. 'body' => [
  181. 'refresh_token' => self::getSetting('refreshToken'),
  182. 'grant_type' => 'refresh_token',
  183. 'client_id' => self::getSetting('client_id'),
  184. 'client_secret' => self:: getSetting('client_secret'),
  185. ],
  186. ]);
  187. if ($response['response']['code'] === 200) {
  188. $data = json_decode($response['body']);
  189. self::setSetting('accessToken', $data->accessToken);
  190. self::setSetting('accessTokenExpiry', $data->accessTokenExpiresAt);
  191. self::setSetting('refreshToken', $data->refreshToken);
  192. self::setSetting('refreshTokenExpiry', $data->refreshTokenExpiresAt);
  193. }
  194. else {
  195. header('Content-Type: text/json');
  196. print json_encode([
  197. //'error' => 'Token Refresh Failed'
  198. 'error' => $response,
  199. ]);
  200. exit;
  201. }
  202. }
  203. private function doRemoteAuth($query) {
  204. $response = wp_remote_post('https://api.homeprezzo.com.au/oauth/token', [
  205. 'method' => 'POST',
  206. 'body' => [
  207. 'code' => $query['code'],
  208. 'client_id' => self::getSetting('client_id'),
  209. 'client_secret' => self::getSetting('client_secret'),
  210. 'grant_type' => 'authorization_code',
  211. ],
  212. ]);
  213. if ($response['response']['code'] === 200) {
  214. $data = json_decode($response['body']);
  215. self::setSetting('accessToken', $data->accessToken);
  216. self::setSetting('accessTokenExpiry', $data->accessTokenExpiresAt);
  217. self::setSetting('refreshToken', $data->refreshToken);
  218. self::setSetting('refreshTokenExpiry', $data->refreshTokenExpiresAt);
  219. self::setSetting('username', $data->user->username);
  220. print '
  221. <html>
  222. <head></head>
  223. <body>
  224. <script>
  225. window.parent.location.reload();
  226. </script>
  227. </body>
  228. </html>
  229. ';
  230. exit;
  231. }
  232. }
  233. public function query_vars($qvars) {
  234. $qvars[] = 'homeprezzo-embed';
  235. $qvars[] = 'code';
  236. $qvars[] = 'f';
  237. return $qvars;
  238. }
  239. public function isAuthenticated() {
  240. if (
  241. self::getSetting('refreshToken') &&
  242. (
  243. self::getSetting('refreshTokenExpiry') &&
  244. strtotime(self::getSetting('refreshTokenExpiry')) > time()
  245. )
  246. ) {
  247. return true;
  248. }
  249. return false;
  250. }
  251. public function getUsername() {
  252. return $this->getSetting('username');
  253. }
  254. public function add_javascript() {
  255. add_action('admin_enqueue_scripts', array($this, 'enqueue_javascript_core'));
  256. }
  257. public function enqueue_javascript_core() {
  258. $data = [
  259. 'settings' => [
  260. 'client_id' => self::getSetting('client_id'),
  261. 'icon' => plugin_dir_url(__FILE__) . 'assets/images/homeprezzo-icon-32.png',
  262. ]
  263. ];
  264. wp_enqueue_script('homeprezzo-embed', plugin_dir_url(__FILE__) . 'js/homeprezzo-embed.js',[
  265. 'jquery',
  266. 'jquery-ui-dialog',
  267. 'wp-color-picker',
  268. ]);
  269. wp_localize_script('homeprezzo-embed', 'HomeprezzoEmbed', $data);
  270. wp_enqueue_style('wp-jquery-ui-dialog');
  271. wp_enqueue_style('wp-color-picker');
  272. }
  273. public function enqueue_qtags() {
  274. if (wp_script_is("quicktags")) {
  275. ?>
  276. <script type="text/javascript">
  277. QTags.addButton(
  278. "homeprezzo_embed",
  279. "prezzo",
  280. homeprezzoEmbedQTagsCallback
  281. );
  282. function homeprezzoEmbedQTagsCallback()
  283. {
  284. $.fn.homeprezzoEmbed('qtags');
  285. }
  286. </script>
  287. <?php
  288. }
  289. }
  290. public function add_options_page() {
  291. require_once('lib/RationalOptionPages.php');
  292. $pages = [
  293. self::prefix . 'settings' => [
  294. 'parent_slug' => 'options-general.php',
  295. 'page_title' => __('HomePrezzo Embed', 'text-domain'),
  296. 'icon_url' => 'dashicons-chart-area',
  297. ]
  298. ];
  299. if (!(self::getSetting('client_id') && self::getSetting('client_secret'))) {
  300. $pages[self::prefix . 'settings']['sections']['client_authentication'] = [
  301. 'id' => 'client_authentication',
  302. 'title' => __('Client Authentication', 'text-domain'),
  303. 'fields' => [
  304. 'client_id' => [
  305. 'title' => __('Client ID', 'text-domain'),
  306. 'type' => 'text',
  307. 'class' => 'client-id regular-text',
  308. ],
  309. 'client_secret' => [
  310. 'title' => __('Client Secret', 'text-domain'),
  311. 'type' => 'password',
  312. 'class' => 'client-secret regular-text',
  313. ],
  314. ],
  315. ];
  316. if (self::getSetting('client_id') && self::getSetting('client_secret')) {
  317. $pages[self::prefix . 'settings']['sections']['client_authentication']['text'] =
  318. '<p><a href="#" data-context="homeprezzo-embed-client-detail" data-alt-text="' .
  319. __('Click to hide your client details', 'text-domain') . '">' .
  320. __('Click to edit your client details', 'text-domain') . '</a>';
  321. }
  322. else {
  323. $pages[self::prefix . 'settings']['sections']['client_authentication']['text'] =
  324. '<p>' . __('Please supply your client credentials below. If you don\'t yet
  325. have client credentials please contact us at ', 'text-domain') .
  326. '<a href="mailto:support@homeprezzo.com">support@homeprezzo.com</a>.';
  327. }
  328. }
  329. if (self::getSetting('client_id') && self::getSetting('client_secret')) {
  330. $pages[self::prefix . 'settings']['sections']['user_authentication'] = [
  331. 'title' => __('User Authentication', 'text-domain'),
  332. ];
  333. if (self::isAuthenticated()) {
  334. $pages[self::prefix . 'settings']['sections']['user_authentication']['text'] =
  335. "<p>" .
  336. sprintf(
  337. __("You're connected to HomePrezzo as %s", 'text-domain'),
  338. self::getUsername()
  339. ) .
  340. "</p>";
  341. }
  342. else {
  343. $pages[self::prefix . 'settings']['sections']['user_authentication']['text'] =
  344. "
  345. <p>" . __("Authorize the plugin to use a HomePrezzo user's data.", 'text-domain') . "</p>
  346. <p><button type=\"button\" data-context=\"homeprezzo-embed-connect\">" . __("Click to Connect", 'text-domain') .
  347. "</button></p><div data-context=\"homeprezzo-embed-connect-dialog\" title=\"Connect to HomePrezzo\">
  348. <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')) . "\" />
  349. </div>
  350. ";
  351. }
  352. }
  353. $options = new RationalOptionPages($pages);
  354. }
  355. }
  356. HomeprezzoEmbed::getInstance();