PluginProbe
Adminify – White Label, Admin Menu Editor, Login Customizer / 1.0.3
Adminify – White Label, Admin Menu Editor, Login Customizer v1.0.3
4.3.1 4.3.0 4.2.26 4.2.25 4.2.24 4.2.23 4.2.22 4.2.21 4.2.20 4.2.19 4.2.18 4.2.17 4.2.16 4.2.15 4.2.14 4.2.13 4.2.12 4.2.11 4.2.10 4.2.9 4.2.8 4.2.7 4.2.6 4.2.5 4.1.17 All 164 releases
adminify / inc / Modules / GooglePageSpeed / GooglePageSpeed.php

GooglePageSpeed.php in Adminify – White Label, Admin Menu Editor, Login Customizer 1.0.3, at inc/Modules/GooglePageSpeed/GooglePageSpeed.php

334 lines 11.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace WPAdminify\Inc\Modules\GooglePageSpeed;
4
5 use WPAdminify\Inc\Modules\PageSpeed_Insight\PageSpeed_Insight;
6 use WPAdminify\Inc\Admin\AdminSettings;
7 use WPAdminify\Inc\Utils;
8
9 // no direct access allowed
10 if (!defined('ABSPATH')) exit;
11
12 /**
13 * WP Adminify
14 * Module: Google Pagespeed
15 *
16 * @author Jewel Theme <support@jeweltheme.com>
17 */
18
19 if (!class_exists('GooglePageSpeed')) {
20
21 class GooglePageSpeed
22 {
23
24 public $url;
25
26 public $insight;
27
28 public $options;
29
30 public function __construct()
31 {
32
33 $needed_keys = ['google_pagepseed_user_roles', 'google_pagepseed_api_key'];
34
35 $this->options = (array) array_intersect_key(AdminSettings::get_instance()->get(), array_flip($needed_keys));
36
37 // $this->url = WP_ADMINIFY_URL . 'inc/Modules/GooglePageSpeed';
38
39 add_action('admin_menu', [$this, 'GooglePageSpeed'], 47);
40
41 // add_action('network_admin_menu', [$this, 'GooglePageSpeed'], 47);
42
43 add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
44
45 add_action('wp_ajax_adminify_page_speed', [$this, 'handle_adminify_page_speed']);
46
47 add_action('init', [$this, 'maybe_create_tables'], 0);
48 }
49
50 public function is_module_active()
51 {
52
53 $mopdule_roles = array_filter((array) $this->options['google_pagepseed_user_roles']);
54
55 if (empty($mopdule_roles)) return true;
56
57 $user = wp_get_current_user();
58
59 return !empty(array_intersect($mopdule_roles, $user->roles));
60 }
61
62 /**
63 * Google Pagespeed Menu
64 */
65 public function GooglePageSpeed()
66 {
67
68 if (!$this->is_module_active()) return;
69
70 add_submenu_page(
71 'wp-adminify-settings',
72 esc_html__('Google Pagespeed Insights by WP Adminify', WP_ADMINIFY_TD),
73 esc_html__('Pagespeed Insights', WP_ADMINIFY_TD),
74 apply_filters('jltwp_adminify_capability', 'manage_options'),
75 'adminify-pagespeed-insights', // Page slug, will be displayed in URL
76 [$this, 'jltwp_adminify_menu_editor_contents']
77 );
78 }
79
80 public function jltwp_adminify_menu_editor_contents()
81 {
82 echo '<div class="wrap"><div id="wp-adminify--page-speed-app"></div></div>';
83 }
84
85 public function load_insight_class()
86 {
87
88 require_once 'class-pagespeed-insights.php';
89
90 if (!($this->insight instanceof PageSpeed_Insight)) {
91 $this->insight = new PageSpeed_Insight($this->options['google_pagepseed_api_key']);
92 }
93
94 return $this->insight;
95 }
96
97 public function handle_adminify_page_speed()
98 {
99
100 check_ajax_referer('__adminify-page_speed-secirity__');
101
102 if (!empty($_POST['route'])) {
103 $route_handler = 'handle_' . $_POST['route'];
104 if (is_callable(get_class($this), $route_handler)) $this->$route_handler($_POST);
105 }
106
107 wp_send_json_error(['message' => __('Something is wrong, no route found')], 400);
108 }
109
110 private function _get_analyze_data($url)
111 {
112
113 $data = [
114 'desktop' => null,
115 'mobile' => null
116 ];
117
118 $result = $this->insight->run_insight($url, ['strategy' => 'desktop']);
119 if (!empty($result) && $result['responseCode'] == 200 && !empty($result['data'])) {
120 $data['desktop'] = $result['data'];
121
122 $result_mobile = $this->insight->run_insight($url, ['strategy' => 'mobile']);
123 if (!empty($result_mobile) && $result_mobile['responseCode'] == 200 && !empty($result_mobile['data'])) {
124 $data['mobile'] = $result_mobile['data'];
125 return $data;
126 }
127 }
128
129 return false;
130 }
131
132 public function handle_new_analyze($data)
133 {
134
135 check_ajax_referer('__adminify-page_speed-secirity__');
136
137 if (empty($data['url']) || !wp_http_validate_url($data['url'])) wp_send_json_error(['message' => __('Something is wrong, URL is missing or wrong formatted')], 400);
138
139 set_time_limit(300);
140
141 $this->load_insight_class();
142
143 $analyze_data = $this->_get_analyze_data($data['url']);
144
145 if ($analyze_data === false) wp_send_json_error(['message' => __('Couldn\'t fetch the result, Please try again later')], 503);
146
147 $saved = $this->save_analyze($analyze_data);
148
149 if (empty($saved)) wp_send_json_error(['message' => __('Couldn\'t save the result, Please try again later')], 500);
150
151 wp_send_json_success($saved);
152 }
153
154 public function save_analyze($analyze_data)
155 {
156
157 $data_desktop = $analyze_data['desktop'];
158 $data_mobile = $analyze_data['mobile'];
159 $url = $data_desktop->id;
160 $score_desktop = $data_desktop->lighthouseResult->categories->performance->score * 100;
161 $score_mobile = $data_mobile->lighthouseResult->categories->performance->score * 100;
162 $screenshot = $data_desktop->lighthouseResult->audits->{'final-screenshot'}->details->data;
163
164 // unset( $data_desktop->lighthouseResult->audits->{'final-screenshot'} );
165 // unset( $data_mobile->lighthouseResult->audits->{'final-screenshot'} );
166
167 $data = array(
168 "url" => $url,
169 "score_desktop" => (int) $score_desktop,
170 "score_mobile" => (int) $score_mobile,
171 "data_desktop" => json_encode($data_desktop),
172 "data_mobile" => json_encode($data_mobile),
173 "screenshot" => $screenshot,
174 "time" => current_time('mysql'),
175 );
176
177 global $wpdb;
178
179 $result = $wpdb->insert("{$wpdb->prefix}adminify_page_speed", $data, array(
180 'url' => '%s',
181 'score_desktop' => '%d',
182 'score_mobile' => '%d',
183 'data_desktop' => '%s',
184 'data_mobile' => '%s',
185 'screenshot' => '%s',
186 'time' => '%s',
187 ));
188
189 if (empty($result)) return false;
190
191 return $wpdb->insert_id;
192 }
193
194 public function handle_count_total($data)
195 {
196 check_ajax_referer('__adminify-page_speed-secirity__');
197
198 global $wpdb;
199
200 $table_name = $wpdb->prefix . 'adminify_page_speed';
201
202 $total_query = "SELECT COUNT(*) FROM $table_name";
203 $total = $wpdb->get_var($total_query);
204
205 wp_send_json_success($total);
206 }
207
208 public function handle_fetch_histories($data)
209 {
210
211 check_ajax_referer('__adminify-page_speed-secirity__');
212
213 global $wpdb;
214
215 $table_name = $wpdb->prefix . 'adminify_page_speed';
216 $fields = 'id, url, score_desktop, score_mobile, time, screenshot';
217 $items_per_page = empty($data['items_per_page']) ? 1 : abs((int) $data['items_per_page']);
218 $page = empty($data['page']) ? 1 : abs((int) $data['page']);
219 $offset = ($page * $items_per_page) - $items_per_page;
220
221 $query = "SELECT {$fields} FROM $table_name";
222
223 $total_query = "SELECT COUNT(1) FROM (${query}) AS combined_table";
224 $total = $wpdb->get_var($total_query);
225
226 $histories = $wpdb->get_results($query . ' ORDER BY time DESC LIMIT ' . $offset . ', ' . $items_per_page, ARRAY_A);
227
228 foreach ($histories as &$history) {
229 $history['formated_date'] = date("Y-m-d", strtotime($history['time']));
230 $history['formated_time'] = date("H:i:s", strtotime($history['time']));
231 }
232
233 wp_send_json_success([
234 'total' => (int) $total,
235 'histories' => (array) $histories
236 ]);
237 }
238
239 public function handle_fetch_history($data)
240 {
241
242 check_ajax_referer('__adminify-page_speed-secirity__');
243
244 if (empty($data['id'])) wp_send_json_error('Something is wrong, Try again later', 400);
245
246 global $wpdb;
247
248 $table_name = $wpdb->prefix . 'adminify_page_speed';
249 $history_id = $data['id'];
250 $fields = 'id, url, score_desktop, score_mobile, data_desktop, data_mobile, time';
251
252 $history = $wpdb->get_row($wpdb->prepare("SELECT {$fields} FROM $table_name WHERE id = %d", $history_id), ARRAY_A);
253
254 if (empty($history) || $wpdb->last_error !== '') wp_send_json_error($wpdb->last_error, 400);
255
256 $history["data_desktop"] = json_decode($history["data_desktop"], true);
257 $history["data_mobile"] = json_decode($history["data_mobile"], true);
258
259 wp_send_json_success([
260 'history' => $history
261 ]);
262 }
263
264 public function handle_delete_history()
265 {
266
267 check_ajax_referer('__adminify-page_speed-secirity__');
268
269 if (empty($_POST['ids'])) wp_send_json_error('Something is wrong, Try again later', 400);
270
271 global $wpdb;
272
273 $ids = implode(',', array_map('absint', $_POST['ids']));
274 $wpdb->query("DELETE FROM {$wpdb->prefix}adminify_page_speed WHERE ID IN($ids)");
275
276 if ($wpdb->last_error !== '') wp_send_json_error($wpdb->last_error, 400);
277
278 wp_send_json_success([
279 'message' => 'History has been deleted'
280 ]);
281 }
282
283 public function enqueue_scripts()
284 {
285
286 wp_enqueue_style('wp-adminify--page-speed', WP_ADMINIFY_URL . 'assets/admin/css/wp-adminify--page-speed.css', [], WP_ADMINIFY_VER);
287
288 $data = [
289 'adminurl' => admin_url(),
290 'ajaxurl' => admin_url('admin-ajax.php'),
291 'nonce' => wp_create_nonce('__adminify-page_speed-secirity__'),
292 'is_pro' => wp_validate_boolean(jltwp_adminify()->can_use_premium_code__premium_only()),
293 'pro_notice' => Utils::adminify_upgrade_pro()
294 ];
295
296 wp_localize_script('wp-adminify--page-speed', 'wp_adminify__pagespeed_data', $data);
297
298 wp_enqueue_script('wp-adminify--page-speed');
299 }
300
301 public function maybe_create_tables()
302 {
303
304 global $wpdb;
305
306 // delete_option( "{$wpdb->prefix}adminify_page_speed_db_version" );
307
308 $db_version = '1.0';
309
310 if (get_option("{$wpdb->prefix}adminify_page_speed_db_version") == $db_version) return; // vail early
311
312 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
313
314 $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}adminify_page_speed (
315 id BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
316 url VARCHAR(255) NOT NULL,
317 score_desktop VARCHAR(3) NOT NULL,
318 score_mobile VARCHAR(3) NOT NULL,
319 data_desktop MEDIUMTEXT NOT NULL,
320 data_mobile MEDIUMTEXT NOT NULL,
321 screenshot MEDIUMTEXT NOT NULL,
322 time DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
323 PRIMARY KEY (id)
324 )" . $wpdb->get_charset_collate() . ";";
325
326 if (get_option("{$wpdb->prefix}adminify_page_speed_db_version") < $db_version) {
327 dbDelta($sql);
328 }
329
330 update_option("{$wpdb->prefix}adminify_page_speed_db_version", $db_version);
331 }
332 }
333 }
334