· 5 years ago · Nov 21, 2019, 09:44 AM
1<?php
2if (!defined('ABSPATH')) {
3 exit; // Exit if accessed directly
4}
5
6class QUBELY
7{
8
9 protected $api_base_url = 'http://qubely.io/wp-json/restapi/v2/';
10 protected $qubely_api_request_body;
11 protected $qubely_api_request_body_default;
12
13 protected $option_keyword = 'qubely_global_options';
14
15 /**
16 * QUBELY constructor
17 */
18 public function __construct()
19 {
20 $this->qubely_api_request_body_default = array(
21 'request_from' => 'qubely'
22 //'request_qubely_version' => QUBELY_VERSION,
23 );
24 $this->qubely_api_request_body = apply_filters('qubely_api_request_body', array());
25
26 // Editor Load
27 add_action('enqueue_block_editor_assets', array($this, 'qubely_editor_assets'));
28
29 // Editor Load
30 add_action('admin_enqueue_scripts', array($this, 'qubely_admin_assets'));
31
32 // Block Categories
33 add_filter('block_categories', array($this, 'qubely_block_categories'), 1, 2);
34
35 // Add Styles and Scripts
36 add_action('wp_enqueue_scripts', array($this, 'qubely_enqueue_style'));
37
38 // Add post meta key
39 $this->add_global_settings_post_meta();
40
41 // Common style
42
43 $this->enqueue_block_css();
44
45 add_action('rest_api_init', array($this, 'register_api_hook'));
46 add_action('delete_post', array($this, 'before_delete_post'), 10);
47
48 //Get layout and block from Server and Cache
49 add_action('wp_ajax_qubely_get_sections', array($this, 'qubely_get_sections'));
50 add_action('wp_ajax_qubely_get_layouts', array($this, 'qubely_get_layouts'));
51
52 add_action('wp_ajax_qubely_get_single_layout', array($this, 'qubely_get_single_layout'));
53 add_action('wp_ajax_qubely_get_single_block', array($this, 'qubely_get_single_section'));
54
55 add_action('wp_ajax_qubely_get_saved_block', array($this, 'qubely_get_saved_block'));
56 add_action('wp_ajax_qubely_delete_saved_block', array($this, 'qubely_delete_saved_block'));
57
58 add_action('wp_ajax_qubely_send_form_data', array($this, 'qubely_send_form_data'));
59
60 // dynamic blocks
61 add_action('init', array($this, 'init_dynamic_blocks'));
62 }
63
64 /**
65 * Init dynamic blocks frontend
66 */
67 public function init_dynamic_blocks()
68 {
69 require_once QUBELY_DIR_PATH . 'core/blocks/postgrid.php';
70 }
71
72 /**
73 * Load Editor Styles and Scripts
74 * @since 1.0.0
75 */
76 public function qubely_editor_assets()
77 {
78 wp_enqueue_script('qubely-blocks-js', QUBELY_DIR_URL . 'assets/js/qubely.min.js', array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor'), QUBELY_VERSION, true);
79
80 $palette = get_theme_support( 'qubely-color-palette' );
81 $palette = array_replace( array('#062040','#566372','#2084F9','#F3F3F3','#EEEEEE','#FFFFFF'), ($palette ? $palette[0] : array()) );
82 wp_localize_script('qubely-blocks-js', 'qubely_admin', array(
83 'plugin' => QUBELY_DIR_URL,
84 'ajax' => admin_url('admin-ajax.php'),
85 'pro_enable' => defined('QUBELY_PRO_VERSION') ? true : false,
86 'shapes' => $this->getSvgShapes(),
87 'all_taxonomy' => $this->get_all_taxonomy(),
88 'image_sizes' => $this->get_all_image_sizes(),
89 'palette' => $palette
90 ));
91 }
92
93 /**
94 * Load SvgShapes
95 * @since 1.0.0
96 */
97 public function getSvgShapes()
98 {
99 $shape_path = QUBELY_DIR_PATH . 'assets/shape';
100 $shapes = glob($shape_path . '/*.svg');
101 $shapeArray = array();
102 if (count($shapes)) {
103 foreach ($shapes as $shape) {
104 $shapeArray[str_replace(array('.svg', $shape_path . '/'), '', $shape)] = file_get_contents($shape);
105 }
106 }
107 return $shapeArray;
108 }
109
110
111 /**
112 * Load SvgShapes
113 * @since 1.0.0
114 */
115 public function getSvgDivider()
116 {
117 $divider_path = QUBELY_DIR_PATH . 'assets/divider';
118 $dividers = glob($divider_path . '/*.svg');
119 $dividerArray = array();
120 if (count($dividers)) {
121 foreach ($dividers as $divider) {
122 $dividerArray[str_replace(array('.svg', $divider_path . '/'), '', $divider)] = file_get_contents($divider);
123 }
124 }
125 return $dividerArray;
126 }
127
128
129 /**
130 * Admin Style & Script
131 * @since 1.0.0
132 */
133 public function qubely_admin_assets()
134 {
135 wp_enqueue_style('qubely-animation', QUBELY_DIR_URL . 'assets/css/animation.css', false, QUBELY_VERSION);
136 wp_enqueue_style('font-awesome', QUBELY_DIR_URL . 'assets/css/font-awesome.min.css', false, QUBELY_VERSION);
137 wp_enqueue_style('qubely-options', QUBELY_DIR_URL . 'assets/css/options.css', false, QUBELY_VERSION);
138 wp_enqueue_script('qubely-magnific-popup', QUBELY_DIR_URL . 'assets/js/jquery.magnific-popup.min.js', array('jquery'), QUBELY_VERSION, true);
139 wp_enqueue_style('qubely-magnific-popup-style', QUBELY_DIR_URL . 'assets/css/magnific-popup.css', false, QUBELY_VERSION);
140 }
141
142
143 /**
144 * Get Post Types.
145 *
146 * @since 1.0.9
147 */
148 public static function get_post_types()
149 {
150
151 $post_types = get_post_types(
152 array(
153 'public' => true,
154 'show_in_rest' => true,
155 ),
156 'objects'
157 );
158
159 $options = array();
160
161 foreach ($post_types as $post_type) {
162 if ('product' === $post_type->name) {
163 continue;
164 }
165
166 $options[] = array(
167 'value' => $post_type->name,
168 'label' => $post_type->label,
169 );
170 }
171
172 return $options;
173 }
174
175 /**
176 * Get all taxonomies.
177 *
178 * @since 1.0.9
179 */
180 public static function get_all_taxonomy()
181 {
182
183 $post_types = self::get_post_types();
184
185 $taxonomy_array = array();
186
187 foreach ($post_types as $value) {
188 $post_type = $value['value'];
189
190 $taxonomies = get_object_taxonomies($post_type, 'objects');
191 $data = array();
192
193 foreach ($taxonomies as $tax_slug => $tax) {
194 if (!$tax->public || !$tax->show_ui) {
195 continue;
196 }
197
198 $data[$tax_slug] = $tax;
199
200 $terms = get_terms($tax_slug);
201
202 $related_tax = array();
203
204 if (!empty($terms)) {
205 foreach ($terms as $term) {
206 $related_tax[] = array(
207 'value' => $term->term_id,
208 'label' => $term->name,
209 );
210 }
211
212 $taxonomy_array[$post_type]['terms'][$tax_slug] = $related_tax;
213 }
214 }
215 $taxonomy_array[$post_type]['taxonomy'] = $data;
216 }
217
218 return $taxonomy_array;
219 }
220 /**
221 * Get all image sizes.
222 *
223 * @since 1.0.9
224 */
225 public static function get_all_image_sizes()
226 {
227
228 global $_wp_additional_image_sizes;
229
230 $sizes = get_intermediate_image_sizes();
231 $image_sizes = array();
232
233 $image_sizes[] = array(
234 'value' => 'full',
235 'label' => esc_html__('Full', 'qubely'),
236 );
237
238 foreach ($sizes as $size) {
239 if (in_array($size, array('thumbnail', 'medium', 'medium_large', 'large'), true)) {
240 $image_sizes[] = array(
241 'value' => $size,
242 'label' => ucwords(trim(str_replace(array('-', '_'), array(' ', ' '), $size))),
243 );
244 } else {
245 $image_sizes[] = array(
246 'value' => $size,
247 'label' => sprintf(
248 '%1$s (%2$sx%3$s)',
249 ucwords(trim(str_replace(array('-', '_'), array(' ', ' '), $size))),
250 $_wp_additional_image_sizes[$size]['width'],
251 $_wp_additional_image_sizes[$size]['height']
252 ),
253 );
254 }
255 }
256 return $image_sizes;
257 }
258
259
260 /**
261 * Frontend Style & Script
262 * @since 1.0.0
263 */
264 public function qubely_enqueue_style()
265 {
266 if(get_post_meta(get_the_ID(), '_qubely_css', true) != '') {
267 wp_enqueue_style('qubely-animation', QUBELY_DIR_URL . 'assets/css/animation.css', false, QUBELY_VERSION);
268 wp_enqueue_style('qubely-font-awesome', QUBELY_DIR_URL . 'assets/css/font-awesome.min.css', false, QUBELY_VERSION);
269 wp_enqueue_style('qubely-style-min', QUBELY_DIR_URL . 'assets/css/style.min.css', false, QUBELY_VERSION);
270 wp_enqueue_script('qubely-magnific-popup-script', QUBELY_DIR_URL . 'assets/js/jquery.magnific-popup.min.js', array('jquery'), QUBELY_VERSION);
271 wp_enqueue_style('qubely-magnific-popup-style', QUBELY_DIR_URL . 'assets/css/magnific-popup.css', false, QUBELY_VERSION);
272 wp_enqueue_script('qubely-interaction', QUBELY_DIR_URL .'assets/js/interaction.js', array('jquery'), QUBELY_VERSION, true );
273 wp_enqueue_script('common-script', QUBELY_DIR_URL . 'assets/js/common-script.min.js', array('jquery'), QUBELY_VERSION);
274 wp_localize_script('common-script', 'qubely_urls', array(
275 'plugin' => QUBELY_DIR_URL,
276 'ajax' => admin_url('admin-ajax.php')
277 ));
278 }
279 }
280
281 /**
282 * Block Category Add
283 * @since 1.0.0
284 */
285 public function qubely_block_categories($categories, $post)
286 {
287 return array_merge(
288 array(
289 array(
290 'slug' => 'qubely',
291 'title' => __('Qubely', 'qubely'),
292 )
293 ),
294 $categories
295 );
296 }
297
298
299 /**
300 * @since 1.0.0-BETA
301 * Add post meta
302 */
303 public function add_global_settings_post_meta()
304 {
305 register_meta('post', 'qubely_global_settings', [
306 'show_in_rest' => true,
307 'single' => true,
308 'type' => 'string'
309 ]);
310
311 // @since 1.2.0
312 register_meta('post', 'qubely_interactions', [
313 'show_in_rest' => true,
314 'single' => true,
315 'type' => 'string'
316 ]);
317 }
318
319
320 /**
321 * @since 1.0.0-BETA
322 * qubely api routes
323 */
324 public function register_api_hook()
325 {
326 // For update global options
327 register_rest_route(
328 'qubely/v1',
329 '/global_settings/',
330 array(
331 array(
332 'methods' => 'GET',
333 'callback' => array($this, 'get_global_option')
334 ),
335 array(
336 'methods' => 'POST',
337 'callback' => array($this, 'update_global_option'),
338 'permission_callback' => function () {
339 return current_user_can('edit_posts');
340 },
341 'args' => array()
342 )
343 )
344 );
345 // For css file save
346 register_rest_route(
347 'qubely/v1',
348 '/save_block_css/',
349 array(
350 array(
351 'methods' => 'POST',
352 'callback' => array($this, 'save_block_css'),
353 'permission_callback' => function () {
354 return current_user_can('edit_posts');
355 },
356 'args' => array()
357 )
358 )
359 );
360 // Get the Content by ID
361 register_rest_route(
362 'qubely/v1',
363 '/qubely_get_content/',
364 array(
365 array(
366 'methods' => 'POST',
367 'callback' => array($this, 'qubely_get_content'),
368 'permission_callback' => function () {
369 return current_user_can('edit_posts');
370 },
371 'args' => array()
372 )
373 )
374 );
375 // Append Qubely CSS
376 register_rest_route(
377 'qubely/v1',
378 '/append_qubely_css/',
379 array(
380 array(
381 'methods' => 'POST',
382 'callback' => array($this, 'append_qubely_css_callback'),
383 'permission_callback' => function () {
384 return current_user_can('edit_posts');
385 },
386 'args' => array()
387 )
388 )
389 );
390
391 }
392
393
394 public function append_qubely_css_callback($request)
395 {
396 try {
397 global $wp_filesystem;
398 if (!$wp_filesystem) {
399 require_once(ABSPATH . 'wp-admin/includes/file.php');
400 }
401 $params = $request->get_params();
402 $css = $params['css'];
403 $post_id = (int) sanitize_text_field($params['post_id']);
404 if( $post_id ){
405 $filename = "qubely-css-{$post_id}.css";
406 $upload_dir = wp_upload_dir();
407 $dir = trailingslashit($upload_dir['basedir']) . 'qubely/';
408 if(file_exists($dir.$filename)) {
409 $file = fopen($dir.$filename, "a");
410 fwrite($file, $css);
411 fclose($file);
412 }
413 $get_data = get_post_meta($post_id, '_qubely_css', true);
414 update_post_meta($post_id, '_qubely_css', $get_data.$css);
415
416 wp_send_json_success(['success' => true, 'message' => 'Update done'.$get_data]);
417 }
418 } catch (Exception $e) {
419 wp_send_json_error(['success' => false, 'message' => $e->getMessage()]);
420 }
421 }
422
423 public function qubely_get_content($request)
424 {
425 $params = $request->get_params();
426 try{
427 if (isset($params['postId'])) {
428 return ['success' => true, 'data'=> get_post($params['postId'])->post_content, 'message' => 'Get Data Success!!'];
429 }
430 } catch (Exception $e){
431 return ['success' => false, 'message' => $e->getMessage()];
432 }
433 }
434
435 /**
436 * @since 1.0.0-BETA
437 * Api for update global option fields
438 */
439 public function update_global_option($request)
440 {
441 try {
442 $params = $request->get_params();
443 if (!isset($params['settings']))
444 throw new Exception("Settings parameter is missing!");
445
446 $settings = $params['settings'];
447
448 if (get_option($this->option_keyword) == false) {
449 add_option($this->option_keyword, $settings);
450 } else {
451 update_option($this->option_keyword, $settings);
452 }
453
454 return ['success' => true, 'message' => "Global option updated!"];
455 } catch (Exception $e) {
456 return ['success' => false, 'message' => $e->getMessage()];
457 }
458 }
459
460 /**
461 * @since 1.0.0-BETA
462 * API For Get Global options
463 */
464 public function get_global_option()
465 {
466 try {
467
468 $settings = get_option($this->option_keyword);
469
470 $settings = $settings == false ? json_decode('{}') : json_decode($settings);
471
472 $palette = get_theme_support( 'qubely-color-palette' );
473
474 if ($palette) {
475 $palette = array_replace( array('#062040','#566372','#2084F9','#F3F3F3','#EEEEEE','#FFFFFF'), ($palette ? $palette[0] : array()) );
476 $settings->colorPreset1 = $palette[0];
477 $settings->colorPreset2 = $palette[1];
478 $settings->colorPreset3 = $palette[2];
479 $settings->colorPreset4 = $palette[3];
480 $settings->colorPreset5 = $palette[4];
481 $settings->colorPreset6 = $palette[6];
482 }
483 return ['success' => true, 'settings' => $settings];
484 } catch (Exception $e) {
485 return ['success' => false, 'message' => $e->getMessage()];
486 }
487 }
488
489 /**
490 * @since 1.0.0-BETA
491 * Save block css for each post in a css file and enqueue the file to the post page
492 */
493 public function save_block_css($request)
494 {
495 try {
496 global $wp_filesystem;
497 if (!$wp_filesystem) {
498 require_once(ABSPATH . 'wp-admin/includes/file.php');
499 }
500
501 $params = $request->get_params();
502 $post_id = (int) sanitize_text_field($params['post_id']);
503
504 if( $params['is_remain'] ) {
505 $qubely_block_css = $params['block_css'];
506 $filename = "qubely-css-{$post_id}.css";
507
508 $qubely_block_json = $params['interaction'];
509 $jsonfilename = "qubely-json-{$post_id}.json";
510
511 $upload_dir = wp_upload_dir();
512 $dir = trailingslashit($upload_dir['basedir']) . 'qubely/';
513
514 // Add Import in first
515 $import_first = $this->set_import_url_to_top_css($qubely_block_css);
516
517 //development
518 update_post_meta($post_id, '_qubely_css', $import_first);
519 if( $qubely_block_json ){
520 update_post_meta($post_id,'_qubely_interaction_json',$qubely_block_json);
521 }
522
523 WP_Filesystem(false, $upload_dir['basedir'], true);
524
525 if (!$wp_filesystem->is_dir($dir)) {
526 $wp_filesystem->mkdir($dir);
527 }
528 //If fail to save css in directory, then it will show a message to user
529 if (!$wp_filesystem->put_contents($dir . $filename, $import_first)) {
530 throw new Exception(__('CSS can not be saved due to permission!!!', 'qubely'));
531 }
532
533 //If fail to save css in directory, then it will show a message to user
534 if ( ! $wp_filesystem->put_contents( $dir . $jsonfilename, $qubely_block_json ) ) {
535 throw new Exception(__('JSON can not be saved due to permission!!!', 'qubely'));
536 }
537
538 return ['success' => true, 'message' => __('Qubely block css file has been updated.', 'qubely')];
539 } else {
540 delete_post_meta($post_id, '_qubely_css');
541 delete_post_meta($post_id, '_qubely_interaction_json');
542 $this->delete_post_resource($post_id);
543 }
544 } catch (Exception $e) {
545 return ['success' => false, 'message' => $e->getMessage()];
546 }
547 }
548
549
550 /**
551 * @since 1.0.2
552 * Set font import to the top of the CSS file
553 */
554 public function set_import_url_to_top_css($get_css = ''){
555 $css_url = "@import url('https://fonts.googleapis.com/css?family=";
556 $google_font_exists = substr_count($get_css, $css_url);
557
558 if ($google_font_exists){
559 $pattern = sprintf(
560 '/%s(.+?)%s/ims',
561 preg_quote($css_url, '/'), preg_quote("');", '/')
562 );
563
564 if (preg_match_all($pattern, $get_css, $matches)) {
565 $fonts = $matches[0];
566 $get_css = str_replace($fonts, '', $get_css);
567 if( preg_match_all( '/font-weight[ ]?:[ ]?[\d]{3}[ ]?;/' , $get_css, $matche_weight ) ){ // short out font weight
568 $weight = array_map( function($val){
569 $process = trim( str_replace( array( 'font-weight',':',';' ) , '', $val ) );
570 if( is_numeric( $process ) ){
571 return $process;
572 }
573 }, $matche_weight[0] );
574 foreach ( $fonts as $key => $val ) {
575 $fonts[$key] = str_replace( "');",'', $val ).':'.implode( ',',$weight )."');";
576 }
577 }
578
579 //Multiple same fonts to single font
580 $fonts = array_unique($fonts);
581 $get_css = implode('', $fonts).$get_css;
582 }
583 }
584 return $get_css;
585 }
586
587
588 /**
589 * @return bool|false|int
590 *
591 * determine if current single page is WP Page Builder Page
592 */
593 private function is_qubely_single()
594 {
595 $post_id = get_the_ID();
596
597 if (!$post_id) {
598 return false;
599 }
600 return $post_id;
601 }
602
603 /**
604 *
605 * determine if wppb editor is open
606 *
607 * @since V.1.0.0
608 * @return bool
609 *
610 * @since v.1.0.0
611 */
612 private function is_editor_screen()
613 {
614 if (!empty($_GET['action']) && $_GET['action'] === 'wppb_editor') {
615 return true;
616 }
617 return false;
618 }
619
620
621 /**
622 * Enqueue post style
623 * If css save option fileSystem then enqueue file
624 * Or add inline to the header
625 */
626 public function enqueue_block_css()
627 {
628 // if(!isset($_GET['preview'])){
629 $option_data = get_option('qubely_options');
630 $css_save_as = isset($option_data['css_save_as']) ? $option_data['css_save_as'] : 'wp_head';
631 if ($css_save_as == 'filesystem') {
632 add_action('wp_enqueue_scripts', array($this, 'enqueue_block_css_file'));
633 } else {
634 add_action('wp_head', array($this, 'add_block_inline_css'), 100);
635 }
636 // }
637 }
638
639 /**
640 *
641 * Return reference id
642 *
643 * @since 1.2.5
644 * @return bool
645 */
646 public function reference_id($parse_blocks) {
647 $extra_id = array();
648 if (!empty($parse_blocks)) {
649 foreach ($parse_blocks as $key => $block) {
650 if( $block['blockName'] == 'core/block') {
651 $extra_id[] = $block['attrs']['ref'];
652 }
653 if (count($block['innerBlocks']) > 0) {
654 $extra_id = array_merge( $this->reference_id($block['innerBlocks']), $extra_id );
655 }
656 }
657 }
658 return $extra_id;
659 }
660
661
662 /**
663 * Enqueue block css file
664 * Check if css path exists and it has current post page
665 * Then enqueue file
666 */
667 public function enqueue_block_css_file()
668 {
669 $post_id = $this->is_qubely_single();
670 $upload_dir = wp_get_upload_dir();
671 $upload_css_dir = trailingslashit($upload_dir['basedir']);
672 $css_path = $upload_css_dir . "qubely/qubely-css-{$post_id}.css";
673 $json_path = $upload_css_dir . "qubely/qubely-json-{$post_id}.json";
674
675 if (file_exists($css_path)) {
676 $css_dir_url = trailingslashit($upload_dir['baseurl']);
677 $css_url = $css_dir_url . "qubely/qubely-css-{$post_id}.css";
678 if (!$this->is_editor_screen()) {
679 wp_enqueue_style("qubely-post-{$post_id}", $css_url, false, QUBELY_VERSION);
680 }
681 // Reusable Blocks CSS add
682 if( $post_id ) {
683 $content_post = get_post($post_id);
684 if(isset($content_post->post_content)) {
685 $content = $content_post->post_content;
686 $parse_blocks = parse_blocks($content);
687 $css_id = $this->reference_id($parse_blocks);
688 if (is_array($css_id)) {
689 if (!empty($css_id)) {
690 $css_id = array_unique($css_id);
691 foreach ($css_id as $value) {
692 $css = $upload_css_dir . "qubely/qubely-css-{$value}.css";
693 if (file_exists($upload_css_dir . "qubely/qubely-css-{$value}.css")) {
694 wp_enqueue_style("qubely-post-{$value}", trailingslashit($upload_dir['baseurl'])."qubely/qubely-css-{$value}.css", false, QUBELY_VERSION);
695 }
696 }
697 }
698 }
699 }
700 }
701 } else {
702 wp_register_style('qubely-post-data', false);
703 wp_enqueue_style('qubely-post-data');
704 wp_add_inline_style('qubely-post-data', get_post_meta(get_the_ID(), '_qubely_css', true));
705 }
706 if ( !file_exists( $json_path ) ) {
707 $this->print_interaction_json_to_header();
708 }else{
709 $blockJson = file_get_contents($json_path);
710 if( $blockJson != "{}" ){
711 echo '<script type="text/javascript"> var qubelyInteraction = '.$blockJson.'</script>';
712 }
713 }
714 }
715
716 /**
717 * Check current post page open and css path exists
718 * Then read the css file content from css path
719 * Then add inline css to the header
720 */
721 public function add_block_inline_css()
722 {
723 $post_id = $this->is_qubely_single();
724
725 if ($post_id) {
726 $upload_dir = wp_get_upload_dir();
727 $upload_css_dir = trailingslashit($upload_dir['basedir']);
728 $css_path = $upload_css_dir . "qubely/qubely-css-{$post_id}.css";
729 $json_path = $upload_css_dir . "qubely/qubely-json-{$post_id}.json";
730
731 if (file_exists($css_path)) {
732 $blockCss = file_get_contents($css_path);
733 echo '<style type="text/css">' . $blockCss . '</style>';
734 } else {
735 echo '<style type="text/css">' . get_post_meta(get_the_ID(), '_qubely_css', true) . '</style>';
736 }
737
738 if ( !file_exists( $json_path ) ) {
739 $this->print_interaction_json_to_header();
740 }else{
741 $blockJson = file_get_contents($json_path);
742 if( $blockJson != "{}" ){
743 echo '<script type="text/javascript"> var qubelyInteraction = '.$blockJson.'</script>';
744 }
745 }
746 }
747 }
748
749 /**
750 * @since 1.2.0
751 * Interaction Add
752 */
753 public function print_interaction_json_to_header(){
754 $post_id = get_the_ID();
755 $interactionJson = get_post_meta($post_id, '_qubely_interaction_json', true);
756 if( $interactionJson != '{}' && $interactionJson != '' ){
757 echo '<script type="text/javascript"> var qubelyInteraction = '.$interactionJson.'</script>';
758 }
759 }
760
761 /**
762 * Check if the post has been delete operation
763 */
764 public function before_delete_post()
765 {
766 // $this->delete_post_resource();
767 }
768 /**
769 * Delete post releated data
770 * @delete post css file
771 */
772 private function delete_post_resource( $post_id = '' )
773 {
774 $post_id = $post_id ? $post_id : $this->is_qubely_single();
775 if ($post_id) {
776 $upload_dir = wp_get_upload_dir();
777 $upload_css_dir = trailingslashit($upload_dir['basedir']);
778 $css_path = $upload_css_dir . "qubely/qubely-css-{$post_id}.css";
779 $json_path = $upload_css_dir . "qubely/qubely-json-{$post_id}.json";
780 if (file_exists($css_path)) {
781 unlink($css_path);
782 }
783 if (file_exists($json_path)) {
784 unlink($json_path);
785 }
786 }
787 }
788
789 /**
790 * @since 1.0.0-BETA
791 * Get Blocks
792 */
793 public function qubely_get_sections()
794 {
795 // $cachedBlockFile = "qubely-blocks.json";
796 // $cache_time = ( 60*60*24*7 ); //cached for 7 days
797
798 $sectionData = array();
799
800 // $upload_dir = wp_upload_dir();
801 // $dir = trailingslashit( $upload_dir[ 'basedir' ] ) . 'qubely/cache/';
802 // $file_path_name = $dir . $cachedBlockFile;
803
804 /* if ( file_exists( $file_path_name ) && ( filemtime( $file_path_name ) + $cache_time ) > time() ) {
805 $getBlocksFromCached = file_get_contents( $file_path_name );
806 $sectionData = json_decode( $getBlocksFromCached, true );
807 $cached_at = 'Last cached: '.human_time_diff( filemtime($file_path_name), current_time( 'timestamp') ). ' ago';
808
809 wp_send_json( array( 'success' => true, 'cached_at' => $cached_at, 'data' => $sectionData ) );
810 } else { */
811 $sectionData = $this->load_blocks_from_server();
812 //}
813
814 wp_send_json_success($sectionData);
815 }
816
817 /**
818 * @since 1.0.0-BETA
819 * Load Blocks from Server
820 */
821 public function load_blocks_from_server()
822 {
823
824 $apiUrl = $this->api_base_url . 'sections';
825
826 $post_args = array('timeout' => 120);
827 $body_param = array_merge($this->qubely_api_request_body_default, array('request_for' => 'get_all_sections'));
828 $post_args['body'] = array_merge($body_param, $this->qubely_api_request_body);
829 $blockRequest = wp_remote_post($apiUrl, array());
830 if (is_wp_error($blockRequest)) {
831 wp_send_json_error(array('messages' => $blockRequest->get_error_messages()));
832 }
833 $blockData = json_decode($blockRequest['body'], true);
834 /* $cachedBlockFile = "qubely-blocks.json";
835 $upload_dir = wp_upload_dir();
836 $dir = trailingslashit( $upload_dir[ 'basedir' ] ) . 'qubely/cache/';
837 $file_path_name = $dir . $cachedBlockFile;
838 if ( ! file_exists( $dir ) ) {
839 mkdir( $dir, 0777, true );
840 }
841 file_put_contents( $file_path_name, json_encode( $blockData ) ); // Put template content to cached directory
842 */
843 return $blockData;
844 }
845
846 /**
847 * @since 1.0.0-BETA
848 * Get Blocks
849 */
850 public function qubely_get_layouts()
851 {
852 // $cachedLayoutFile = "qubely-layouts.json";
853 // $cache_time = ( 60*60*24*7 ); //cached for 7 days
854
855 $layoutData = array();
856
857 // $upload_dir = wp_upload_dir();
858 // $dir = trailingslashit( $upload_dir[ 'basedir' ] ) . 'qubely/cache/';
859 // $file_path_name = $dir . $cachedLayoutFile;
860
861 /* if ( file_exists( $file_path_name ) && ( filemtime( $file_path_name ) + $cache_time ) > time() ) {
862 $getLayoutFromCached = file_get_contents($file_path_name);
863 $layoutData = json_decode($getLayoutFromCached, true);
864 $cached_at = 'Last cached: '.human_time_diff( filemtime( $file_path_name ), current_time( 'timestamp' ) ). ' ago';
865
866 wp_send_json( array( 'success' => true, 'cached_at' => $cached_at, 'data' => $layoutData ) );
867 } else { */
868 $layoutData = $this->load_layouts_from_server();
869 //}
870
871 wp_send_json_success($layoutData);
872 }
873
874 /**
875 * @since 1.0.0-BETA
876 * Load Blocks from Server
877 */
878 public function load_layouts_from_server()
879 {
880
881 $apiUrl = $this->api_base_url . 'layouts';
882
883 $post_args = array('timeout' => 120);
884 $body_param = array_merge($this->qubely_api_request_body_default, array('request_for' => 'get_all_layouts'));
885 $post_args['body'] = array_merge($body_param, $this->qubely_api_request_body);
886 $layoutRequest = wp_remote_post($apiUrl, $post_args);
887 if (is_wp_error($layoutRequest)) {
888 wp_send_json_error(array('messages' => $layoutRequest->get_error_messages()));
889 }
890 $layoutData = json_decode($layoutRequest['body'], true);
891 /* $cachedLayoutFile = "qubely-layouts.json";
892 $upload_dir = wp_upload_dir();
893 $dir = trailingslashit( $upload_dir[ 'basedir' ] ) . 'qubely/cache/';
894 $file_path_name = $dir . $cachedLayoutFile;
895 if ( ! file_exists( $dir ) ) {
896 mkdir( $dir, 0777, true );
897 }
898 file_put_contents( $file_path_name, json_encode( $layoutData ) ); // Put template content to cached directory
899 */
900 return $layoutData;
901 }
902
903
904 /**
905 * @since 1.0.0
906 * Get single layout
907 */
908 public function qubely_get_single_layout()
909 {
910 $layout_id = (int) sanitize_text_field($_REQUEST['layout_id']);
911
912 // $cache_time = ( 60*60*24*7 ); //cached for 7 days
913 // $cachedSingleLayoutFile = "qubely-single-layout-{$layout_id}.json";
914 // $upload_dir = wp_upload_dir();
915 // $dir = trailingslashit( $upload_dir['basedir'] ) . 'qubely/cache/layouts/';
916 // $file_path_name = $dir . $cachedSingleLayoutFile;
917 // Checking if exists file and cache validity true
918 /* if ( file_exists( $file_path_name ) && ( filemtime( $file_path_name ) + $cache_time ) > time() ) {
919 $getSingleLayoutFromCached = file_get_contents( $file_path_name );
920 $layoutData = json_decode( $getSingleLayoutFromCached, true );
921 } else { */
922 $layoutData = $this->load_and_cache_single_layout_from_server($layout_id);
923 //}
924 wp_send_json_success($layoutData);
925 }
926
927 /**
928 * @since 1.0.0(Stable)
929 * Get single layout
930 */
931 public function qubely_get_single_section()
932 {
933 $section_id = (int) sanitize_text_field($_REQUEST['block_id']);
934 $sectionData = $this->load_and_cache_single_section_from_server($section_id);
935 wp_send_json_success($sectionData);
936 }
937
938 /**
939 * @since 1.0.0(Stable)
940 * Get single section
941 */
942 public function load_and_cache_single_section_from_server($section_id = 0)
943 {
944 if (!$section_id) {
945 return false;
946 }
947 $apiUrl = $this->api_base_url . 'single-section';
948
949 $post_args = array('timeout' => 120);
950
951 $body_param = array_merge(
952 $this->qubely_api_request_body_default,
953 array('request_for' => 'get_single_section', 'section_id' => $section_id)
954 );
955 $post_args['body'] = array_merge($body_param, $this->qubely_api_request_body);
956 $sectionRequest = wp_remote_post($apiUrl, $post_args);
957
958 if (is_wp_error($sectionRequest)) {
959 wp_send_json_error(array('messages' => $sectionRequest->get_error_messages()));
960 }
961
962 $sectionData = json_decode($sectionRequest['body'], true);
963
964 return $sectionData;
965 }
966
967
968 /**
969 * @since 1.0.0-BETA
970 * Load single layout and cache it
971 */
972 public function load_and_cache_single_layout_from_server($layout_id = 0)
973 {
974 if (!$layout_id) {
975 return false;
976 }
977 $apiUrl = $this->api_base_url . 'single-layout';
978
979 $post_args = array('timeout' => 120);
980
981 $body_param = array_merge(
982 $this->qubely_api_request_body_default,
983 array('request_for' => 'get_single_layout', 'layout_id' => $layout_id)
984 );
985 $post_args['body'] = array_merge($body_param, $this->qubely_api_request_body);
986 $layoutRequest = wp_remote_post($apiUrl, $post_args);
987
988 if (is_wp_error($layoutRequest)) {
989 wp_send_json_error(array('messages' => $layoutRequest->get_error_messages()));
990 }
991
992 $layoutData = json_decode($layoutRequest['body'], true);
993 /* $cachedLayoutFile = "qubely-single-layout-{$layout_id}.json";
994 $upload_dir = wp_upload_dir();
995 $dir = trailingslashit( $upload_dir[ 'basedir' ] ) . 'qubely/cache/layouts/';
996 $file_path_name = $dir . $cachedLayoutFile;
997 if ( ! file_exists( $dir ) ) {
998 mkdir( $dir, 0777, true );
999 }
1000 file_put_contents( $file_path_name, json_encode( $layoutData ) ); */
1001
1002 return $layoutData;
1003 }
1004
1005 /**
1006 * @since 1.0.0-BETA
1007 * Get saved blocks
1008 */
1009 public function qubely_get_saved_block()
1010 {
1011 $args = array(
1012 'post_type' => 'wp_block',
1013 'post_status' => 'publish'
1014 );
1015 $r = wp_parse_args(null, $args);
1016 $get_posts = new WP_Query;
1017 $wp_blocks = $get_posts->query($r);
1018 wp_send_json_success($wp_blocks);
1019 }
1020
1021 /**
1022 * @since 1.0.0-BETA
1023 * Delete saved blocks
1024 */
1025 public function qubely_delete_saved_block()
1026 {
1027 $block_id = (int) sanitize_text_field($_REQUEST['block_id']);
1028 $deleted_block = wp_delete_post($block_id);
1029 wp_send_json_success($deleted_block);
1030 }
1031
1032
1033 /**
1034 * Ajax for sending form data
1035 * @return boolean,void Return false if failure, echo json on success
1036 */
1037 public function qubely_send_form_data()
1038 {
1039 if (isset($_POST['captcha']) && $_POST['recaptcha'] == 'true') {
1040 $captcha = $_POST['captcha'];
1041 $secretKey = $_POST['recaptcha-secret-key'];
1042 $verify = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$captcha}");
1043
1044 if (!is_array($verify) || !isset($verify['body'])) {
1045 wp_send_json(__('Cannot validate captcha', 'qubely'), 400);
1046 }
1047
1048 $verified = json_decode($verify['body']);
1049 if (!$verified->success) {
1050 wp_send_json(__('Captcha validation error', 'qubely'), 400);
1051 }
1052 }
1053
1054 //Settings data
1055 $fieldErrorMessage = ($_POST['field-error-message']) ? base64_decode($_POST['field-error-message']) : '';
1056 $formSuccessMessage = ($_POST['form-success-message']) ? base64_decode($_POST['form-success-message']) : '';
1057 $formErrorMessage = ($_POST['form-error-message']) ? base64_decode($_POST['form-error-message']) : '';
1058 $emailReceiver = ($_POST['email-receiver']) ? base64_decode($_POST['email-receiver']) : '';
1059 $emailHeaders = ($_POST['email-headers']) ? base64_decode($_POST['email-headers']) : '';
1060 $emailFrom = ($_POST['email-from']) ? base64_decode($_POST['email-from']) : '';
1061 $emailSubject = ($_POST['email-subject']) ? base64_decode($_POST['email-subject']) : '';
1062 $emailBody = ($_POST['email-body']) ? base64_decode($_POST['email-body']) : '';
1063
1064 $fieldNames = [];
1065 $validation = false;
1066 $formInputArray = $_POST['qubely-form-input'];
1067 foreach ($formInputArray as $key => $value) {
1068 if (preg_match("/[*]$/", $key)) {
1069 if (empty($value)) {
1070 $validation = true;
1071 }
1072 $key = str_replace('*', '', $key);
1073 }
1074 $fieldNames[$key] = $value;
1075 }
1076
1077 if ($validation || (isset($_POST['qubely-form-has-policy']) && empty($_POST['qubely-form-has-policy']))) {
1078 wp_send_json(__($formErrorMessage, 'qubely'), 400);
1079 }
1080
1081 $replyToMail = $replyToName = $cc = $bcc = $fromName = $fromEmail = '';
1082 if ($emailFrom != '') {
1083 $emailFrom = explode(':', $emailFrom);
1084 if (count($emailFrom) > 0) {
1085 $fromName = isset($emailFrom[0]) ? trim($emailFrom[0]) : '';
1086 $fromEmail = isset($emailFrom[1]) ? trim($emailFrom[1]) : '';
1087 }
1088 }
1089
1090 $emailHeaders = explode("\n", $emailHeaders);
1091 foreach ($emailHeaders as $_header) {
1092 $_header = explode(':', $_header);
1093 if (count($_header) > 0) {
1094 if (strtolower($_header[0]) == 'reply-to')
1095 $replyToMail = isset($_header[1]) ? trim($_header[1]) : '';
1096 if (strtolower($_header[0]) == 'reply-name')
1097 $replyToName = isset($_header[1]) ? trim($_header[1]) : '';
1098 if (strtolower($_header[0]) == 'cc')
1099 $cc = isset($_header[1]) ? trim($_header[1]) : '';
1100 if (strtolower($_header[0]) == 'bcc')
1101 $bcc = isset($_header[1]) ? trim($_header[1]) : '';
1102 }
1103 }
1104
1105 foreach ($fieldNames as $name => $value) {
1106 $value = is_array($fieldNames[$name]) ? implode(', ', $fieldNames[$name]) : $value;
1107 $emailBody = str_replace("{{" . $name . "}}", $value, $emailBody);
1108 $emailSubject = str_replace("{{" . $name . "}}", $value, $emailSubject);
1109 $replyToName = str_replace("{{" . $name . "}}", $value, $replyToName);
1110 $replyToMail = str_replace("{{" . $name . "}}", $value, $replyToMail);
1111 $fromName = str_replace("{{" . $name . "}}", $value, $fromName);
1112 $cc = str_replace("{{" . $name . "}}", $value, $cc);
1113 $bcc = str_replace("{{" . $name . "}}", $value, $bcc);
1114 }
1115
1116 // Subject Structure
1117 $siteName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
1118 $emailSubject = str_replace("{{site-name}}", $siteName, $emailSubject);
1119
1120 $headers[] = 'Content-Type: text/html; charset=UTF-8';
1121 $headers[] = 'From: ' . $fromName . ' <' . $fromEmail . '>';
1122 $headers[] = 'Reply-To: ' . $replyToName . ' <' . $replyToMail . '>';
1123 $headers[] = 'Cc: <' . $cc . '>';
1124 $headers[] = 'Bcc: <' . $bcc . '>';
1125
1126 //Send E-Mail Now or through error msg
1127 try {
1128 $isMail = wp_mail($emailReceiver, $emailSubject, $emailBody, $headers);
1129 if ($isMail) {
1130 $responseData['status'] = 1;
1131 $responseData['msg'] = __($formSuccessMessage, 'qubely');
1132 } else {
1133 $responseData['status'] = 0;
1134 $responseData['msg'] = __($formErrorMessage, 'qubely');
1135 }
1136 wp_send_json_success($responseData);
1137 } catch (\Exception $e) {
1138 $responseData['status'] = 0;
1139 $responseData['msg'] = $e->getMessage();
1140 wp_send_json_error($responseData);
1141 }
1142 }
1143}
1144new QUBELY();