-
Notifications
You must be signed in to change notification settings - Fork 0
/
analizador.php
484 lines (394 loc) · 15.5 KB
/
analizador.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
<?php
/**
* Analizador
*
* @package ANALIZADOR
* @author Villalba Juan Manuel Pedro
* @license gplv3
* @version 1.0.0
*
* @wordpress-plugin
* Plugin Name: Analizador
* Plugin URI: https://analizador.ar
* Description: Analizador Web Simple
* Version: 1.0.0
* Author: Villalba Juan Manuel Pedro
* Author URI: https://hexome.cloud/
* Text Domain: analizador
* Domain Path: /languages
* License: GPLv3
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
* You should have received a copy of the GNU General Public License
* along with Analizador. If not, see <https://www.gnu.org/licenses/gpl-2.0.html/>.
*/
if ( ! defined( 'ABSPATH' ) ) exit;
// Definir constantes
define( 'ANALIZADOR_PLUGIN_VERSION', '1.0.1' );
define( 'ANALIZADOR_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'ANALIZADOR_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
// Incluir la clase helper
require_once ANALIZADOR_PLUGIN_PATH . 'Includes/Helper.php';
use \ANALIZADOR\Includes\Helper as helper;
/*
function Analizador_plugin_display_alert( string $str, int $status ) {
return helper::display_alert( (string) $str, (int) $status );
}
*/
add_action('wp_dashboard_setup', 'analizador_setup_widget_desktop');
function analizador_setup_widget_desktop() {
wp_add_dashboard_widget(
'analizador_setup_widget_desktop',
'Analizador Web Simple Desktop',
'analizador_setup_widget'
);
}
add_action('admin_init', function(){
$token = get_option('analizador_key_token', '');
$website_id = get_option('analizador_website_id', '');
if (is_admin() && $token && $website_id):
add_action('admin_enqueue_scripts', function () {
wp_enqueue_script(
'chart',
'https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js',
array(),
null,
true
);
});
endif;
});
function trigger_visitor_data_cron_event() {
$response = wp_remote_post(
get_rest_url() . '/wp/v2/events/' . 'store_visitor_data_cron_job',
array(
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . get_auth_token(),
),
)
);
if (is_wp_error($response) || !empty($response['errors'])) {
echo 'Error triggering cron event: ' . $response->get_error_message();
} else {
echo 'Cron event triggered successfully.';
}
}
function analizador_setup_widget() {
$token = get_option('analizador_key_token', '');
$website_id = get_option('analizador_website_id', '');
echo '
<a href="options-general.php?page=analizador-settings" class="analizador-settings">
<span class="dashicons dashicons-admin-generic analizador-settings-icon" alt="Configuraciones del Analizador Web"></span>
</a>
<a class="analizador-settings">
<span id="changeChartTypeButton" class="dashicons dashicons-randomize analizador-settings-icon" alt="Change View Chart"></span>
</a>
<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="analizador-settings">
<input type="hidden" name="action" value="manual_refresh_data">
' . wp_nonce_field('manual_refresh_data_nonce', 'manual_refresh_data_nonce') . '
<button type="submit" class="dashicons dashicons-update analizador-refresh-icon" title="Actualizar Datos"></button>
</form>
';
if ($website_id) {
$pageviews_7_days = get_option('analizador_stats_7_days_pageviews', []);
$pageviews_15_days = get_option('analizador_stats_15_days_pageviews', []);
$pageviews_30_days = get_option('analizador_stats_30_days_pageviews', []);
$visitors_7_days = get_option('analizador_stats_7_days_visitors', []);
$visitors_15_days = get_option('analizador_stats_15_days_visitors', []);
$visitors_30_days = get_option('analizador_stats_30_days_visitors', []);
$page_7_days = get_option('analizador_stats_7_days_page', []);
$page_15_days = get_option('analizador_stats_15_days_page', []);
$page_30_days = get_option('analizador_stats_30_days_page', []);
echo '<script>
let dataChart = {};
var statsData = {
"7_days": {
"pageviews": ' . json_encode($pageviews_7_days) . ',
"visitors": ' . json_encode($visitors_7_days) . ',
"page": ' . json_encode($page_7_days) . '
},
"15_days": {
"pageviews": ' . json_encode($pageviews_15_days) . ',
"visitors": ' . json_encode($visitors_15_days) . ',
"page": ' . json_encode($page_15_days) . '
},
"30_days": {
"pageviews": ' . json_encode($pageviews_30_days) . ',
"visitors": ' . json_encode($visitors_30_days) . ',
"page": ' . json_encode($page_30_days) . '
}
};
</script>
';
echo '<div data-website-id="' . esc_attr($website_id) . '" id="analizador-website-id">
<span onclick="sevenDays()" class="badge-analizador">7 ' . __("days") . '</span>
<span onclick="fifteenDays()" class="badge-analizador">15 ' . __("days") . '</span>
<span onclick="thirtyDays()" class="badge-analizador">30 ' . __("days") . '</span>
<canvas id="canvas" width="640" height="480"></canvas>
</br>
<h2>Top content over the last</h2>
<table class="wp-list-table widefat striped">
<thead>
<tr>
<th scope="col">Page</th>
<th scope="col">Visits</th>
</tr>
</thead>
<tbody id="page-rating">
<!-- Data will be dynamically populated here -->
</tbody>
</table>
<script>
function sevenDays() {
dataChart.chartService(7);
dataChart.pageService(7);
}
function fifteenDays() {
dataChart.chartService(15);
dataChart.pageService(15);
}
function thirtyDays() {
dataChart.chartService(30);
dataChart.pageService(30);
}
</script>
</div>';
return;
}
if (!$token) {
echo '<p>No se ha configurado el Analizador Key Token. Por favor, configúralo <a href="' . admin_url('options-general.php?page=analizador-settings') . '">aquí</a>.</p>';
return;
}
$home_url = get_home_url();
$parsed_url = parse_url($home_url);
$site_url = $parsed_url['host'];
$response = wp_remote_get('https://analizador.ar/api/v1/websites?search=' . urlencode($site_url), array(
'headers' => array(
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
)
));
if (is_wp_error($response)) {
echo '<p>Error al obtener los datos.</p>';
return;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
$site_exists = false;
if (isset($data['data']) && is_array($data['data'])) {
echo '<ul>';
foreach ($data['data'] as $site) {
echo '<li><a href="http://' . esc_html($site['url']) . '" target="_blank">' . esc_html($site['url']) . '</a></li>';
if ($site['url'] === $site_url) {
$site_exists = true;
if ($site_exists) {
update_option('analizador_website_id', sanitize_text_field($site['id']));
}
}
}
echo '</ul>';
} else {
echo '<p>No se encontraron sitios web.</p>';
}
if (!$site_exists) {
$helper = new helper();
$website_success= $helper->create_website($token, $home_url);
if ($website_success) {
echo $website_success;
}
}
}
add_action('admin_menu', 'analizador_settings_page');
function analizador_settings_page() {
add_options_page(
'Configuración de Analizador',
'Analizador Settings',
'manage_options',
'analizador-settings',
'analizador_settings_page_html'
);
}
function register_cron_handler() {
include_once 'cron-handler.php';
}
add_action('admin_post_manual_refresh_data', 'handle_manual_refresh_data');
function handle_manual_refresh_data() {
if ( !isset( $_POST['manual_refresh_data_nonce'] ) || !wp_verify_nonce( $_POST['manual_refresh_data_nonce'], 'manual_refresh_data_nonce' ) ) {
wp_die('Nonce verification failed');
}
store_visitor_data();
wp_redirect( $_SERVER['HTTP_REFERER'] );
exit;
}
add_action('admin_post_manual_refresh_data', 'register_cron_handler');
function add_refresh_data_button() {
?>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="manual_refresh_data">
<?php wp_nonce_field('manual_refresh_data_nonce', 'manual_refresh_data_nonce'); ?>
<button type="submit" class="button button-primary">Get Manual Data</button>
</form>
<?php
if (isset($_GET['message'])) {
if ($_GET['message'] == 'success') {
echo '<div class="notice notice-success is-dismissible"><p>Operación finalizada con éxito.</p></div>';
} elseif ($_GET['message'] == 'error') {
echo '<div class="notice notice-error is-dismissible"><p>Error al programar la tarea cron.</p></div>';
} elseif ($_GET['message'] == 'queued') {
echo '<div class="notice notice-warning is-dismissible"><p>Ya hay una tarea en cola.</p></div>';
}
}
}
function analizador_settings_page_html() {
if (!current_user_can('manage_options')) {
return;
}
if (isset($_POST['analizador_key_token'])) {
update_option('analizador_key_token', sanitize_text_field($_POST['analizador_key_token']));
echo '<div class="updated"><p>' . __("Token Saved Successfully") . '.</p></div>';
}
$token = get_option('analizador_key_token', '');
?>
<div class="wrap">
<h1><?= __("Setting of Analizador") ?></h1>
<div class="analizador-registration-prompt">
<p>
<?= __("The Key Token Analyzer is obtained within our website") ?>
<ol>
<li> <a href="https://analizador.ar/signup"><?= __("SignUp your Account.") ?></a></li>
<li> <a href="https://analizador.ar/settings/api"><?= __("Get <span>Analizador Key Token</span>.") ?></a></li>
<li> <?= __("Wait for the system to record data or refresh information manually.") ?> </li>
<li><?= __("Get started with the product.") ?></li>
</ol>
</p>
</div>
<?php
?>
<div class="refresh-data-box">
<h3><?=__("Update Manual Data")?></h3>
<div class="inside">
<?php add_refresh_data_button(); ?>
</div>
</div>
<style>
.refresh-data-box {
border: 1px solid #ddd;
background-color: #f9f9f9;
padding: 20px;
margin-bottom: 20px;
}
.refresh-data-box h3 {
margin-top: 0;
}
</style>
<?php
?>
<?php
?>
<div class="refresh-data-box">
<h3><?=__("Analizador Key Token")?></h3>
<div class="inside">
<form method="POST">
<table class="form-table">
<tr valign="top">
<th scope="row"><?= __("Analizador Key Token")?></th>
<td><input type="password" name="analizador_key_token" value="<?php echo esc_attr(md5($token)); ?>" class="regular-text" /></td>
</tr>
</table>
<?php submit_button(__("Save Token")); ?>
</form>
</div>
</div>
<style>
.refresh-data-box {
border: 1px solid #ddd;
background-color: #f9f9f9;
padding: 20px;
margin-bottom: 20px;
}
.refresh-data-box h3 {
margin-top: 0;
}
</style>
<?php
?>
</div>
<?php
}
add_action('admin_init', 'verificar_analizador_key_token');
function verificar_analizador_key_token() {
if (is_admin() && !isset($_GET['page']) || $_GET['page'] !== 'analizador-settings') {
$token = get_option('analizador_key_token', '');
if (!$token) {
wp_redirect(admin_url('options-general.php?page=analizador-settings'));
exit;
}
}
}
function conditionally_add_script($plugin_slug) {
$token = get_option('analizador_key_token', '');
if ($token) {
add_action( 'wp_footer', function() {
if ( !is_admin() ) {
?>
<script data-host="https://analizador.ar" data-dnt="false" src="https://analizador.ar/js/script.js" id="ZwSg9rf6GA" async defer></script>
<?php
}
});
}
}
add_action( 'init', 'conditionally_add_script' );
add_action( 'wp_loaded', 'schedule_store_visitor_data_cron' );
function schedule_store_visitor_data_cron() {
if ( ! wp_next_scheduled( 'store_visitor_data_cron_job' ) ) {
wp_schedule_event( time(), 'daily', 'store_visitor_data_cron_job' );
}
}
add_action( 'store_visitor_data_cron_job', 'store_visitor_data' );
function store_visitor_data() {
$token = get_option( 'analizador_key_token', '' );
if ( ! $token ) {
return;
}
$site_id = get_option( 'analizador_website_id', '' );
if ( ! $site_id ) {
return;
}
$periods = array(
'7_days' => '-7 days',
'15_days' => '-15 days',
'30_days' => '-30 days',
);
$metrics = ['browser', 'campaign', 'city', 'continent', 'country', 'device', 'event', 'landing_page', 'language', 'os', 'page', 'pageviews', 'pageviews_hours', 'referrer', 'resolution', 'visitors', 'visitors_hours'];
$helper = new helper();
$helper->reset_stats();
foreach ( $periods as $period => $interval ) {
foreach ($metrics as $metric) {
$from_date = date( 'Y-m-d', strtotime( $interval ) );
$to_date = date( 'Y-m-d' );
$last_update = get_option( "analizador_stats_{$period}_{$metric}_last_update", 0 );
$update_limit = ( strpos( $period, 'days' ) !== false ) ? 3 : 24;
if ( current_time( 'timestamp' ) - $last_update >= HOUR_IN_SECONDS / $update_limit ) {
$stats = wp_remote_get("https://analizador.ar/api/v1/stats/{$site_id}?from={$from_date}&to={$to_date}&name={$metric}", [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
]
]);
if ( ! is_wp_error( $stats ) && $stats['response']['code'] === 200 ) {
$stats_body = wp_remote_retrieve_body( $stats );
$stats_data = json_decode( $stats_body, true );
update_option( "analizador_stats_{$period}_{$metric}", $stats_data );
update_option( "analizador_stats_{$period}_{$metric}_last_update", current_time( 'timestamp' ) );
}
}
}
}
}
add_action('admin_enqueue_scripts', 'agregar_estilos_y_scripts');
function agregar_estilos_y_scripts() {
wp_enqueue_style('mi_widget_estilos', plugin_dir_url(__FILE__) . 'styles.css');
wp_enqueue_script('mi_widget_scripts', plugin_dir_url(__FILE__) . 'scripts.js', array('jquery'), null, true);
}
?>