-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaianalytics.php
231 lines (197 loc) · 8.02 KB
/
aianalytics.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
<?php
/**
* AI Analytics Module
*
* @author Smalk AI
* @copyright 2024 Smalk AI
* @license AFL 3.0
*/
if (!defined('_PS_VERSION_')) {
exit;
}
// Load Composer's autoloader
require_once __DIR__ . '/vendor/autoload.php';
class AiAnalytics extends Module
{
public function __construct()
{
$this->name = AiAnalyticsConstants::MODULE_NAME;
$this->tab = 'analytics_stats';
$this->version = '1.0.0';
$this->author = 'Smalk AI';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('AI Analytics');
$this->description = $this->l('Get real-time analytics on AI agents and human visitors from AI Search, and control your brand visibility on Answer Engines (ChatGPT, Perplexity, etc.).');
$this->ps_versions_compliancy = ['min' => '8.0.0', 'max' => _PS_VERSION_];
}
public function install()
{
// Initialize configuration
Configuration::updateValue(AiAnalyticsConstants::ACCESS_TOKEN_KEY, '');
Configuration::updateValue(AiAnalyticsConstants::IS_ENABLED_KEY, false);
Configuration::updateValue(AiAnalyticsConstants::LAST_CRON_KEY, time());
// Install admin controller tab
$tab = new Tab();
$tab->active = 1;
$tab->class_name = 'AdminAiAnalytics';
$tab->name = array();
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = 'AI Analytics';
}
$tab->id_parent = (int)Tab::getIdFromClassName('AdminParentModules');
$tab->module = $this->name;
return parent::install() &&
$this->registerHook('displayHeader') && // Changed from 'header' to 'displayHeader'
$this->registerHook('displayBackOfficeHeader') &&
$this->registerHook('actionFrontControllerSetMedia') &&
$this->registerHook('actionAdminMetaBeforeWriteRobotsFile') &&
$this->registerHook('actionCronJob') &&
$tab->add();
}
public function uninstall()
{
// Uninstall admin controller tab
$id_tab = (int)Tab::getIdFromClassName('AdminAiAnalytics');
if ($id_tab) {
$tab = new Tab($id_tab);
$tab->delete();
}
// Remove configuration
Configuration::deleteByName(AiAnalyticsConstants::ACCESS_TOKEN_KEY);
Configuration::deleteByName(AiAnalyticsConstants::IS_ENABLED_KEY);
Configuration::deleteByName(AiAnalyticsConstants::CACHE_PROJECT_KEY);
Configuration::deleteByName(AiAnalyticsConstants::LAST_CRON_KEY);
return parent::uninstall();
}
public function hookDisplayHeader()
{
$projectKey = $this->getProjectKey();
if (!empty($projectKey)) {
return '<script type="text/javascript" src="' . $this->_path . 'views/js/ai-analytics.js" data-aianalytics-key="' . Tools::safeOutput($projectKey) . '"></script>';
}
return '<script type="text/javascript" src="' . $this->_path . 'views/js/ai-analytics.js"></script>';
}
public function hookActionFrontControllerSetMedia()
{
// Only handle analytics visit request
$analytics = Analytics::getInstance($this);
$analytics->sendVisitRequest();
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookDisplayBackOfficeHeader()
{
if (Tools::getValue('configure') == $this->name) {
// Add jQuery first
$this->context->controller->addJquery();
// Then add your CSS
$this->context->controller->addCSS($this->_path . 'views/css/ai-analytics-admin.css');
}
}
/**
* Hook: Modify robots.txt content
*/
public function hookActionAdminMetaBeforeWriteRobotsFile($params)
{
if (isset($params['robotsFile'])) {
$params['robotsFile'] = AiAnalyticsRobotsTxt::modifyRobotsTxt($params['robotsFile']);
}
}
/**
* Hook: Handle cron tasks
*/
public function hookActionCronJob()
{
if (AiAnalyticsCron::shouldRun()) {
AiAnalyticsCron::clearCache();
}
}
/**
* Load the configuration form
*/
public function getContent()
{
$output = '';
// Process form submission
if ((Tools::isSubmit('submitAianalytics')) && Tools::getValue('token') === Tools::getAdminTokenLite('AdminModules')) {
// Clear the project cache before updating the token
Configuration::updateValue(AiAnalyticsConstants::CACHE_PROJECT_KEY, '');
// Update configuration values
Configuration::updateValue(AiAnalyticsConstants::ACCESS_TOKEN_KEY, Tools::getValue('AIANALYTICS_ACCESS_TOKEN'));
Configuration::updateValue(AiAnalyticsConstants::IS_ENABLED_KEY, Tools::getValue('AIANALYTICS_ENABLED') ? 1 : 0);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
// Assign template variables
$this->context->smarty->assign(array(
'module_dir' => $this->_path,
'AIANALYTICS_ACCESS_TOKEN' => Configuration::get(AiAnalyticsConstants::ACCESS_TOKEN_KEY),
'AIANALYTICS_ENABLED' => Configuration::get(AiAnalyticsConstants::IS_ENABLED_KEY),
'current' => $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name,
'configure' => $this->name,
'token' => Tools::getAdminTokenLite('AdminModules')
));
return $output . $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
}
private function getProjectKey()
{
if (!Configuration::get(AiAnalyticsConstants::IS_ENABLED_KEY)) {
return '';
}
$cachedData = Configuration::get(AiAnalyticsConstants::CACHE_PROJECT_KEY);
if ($cachedData) {
$cached = json_decode($cachedData, true);
if ($cached && isset($cached['time']) &&
(time() - $cached['time'] < AiAnalyticsConstants::CACHE_LIFETIME)) {
return $cached['id'];
}
}
$accessToken = Configuration::get(AiAnalyticsConstants::ACCESS_TOKEN_KEY);
if (empty($accessToken)) {
return '';
}
try {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => AiAnalyticsConstants::API_BASE_URL . '/projects',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Api-Key ' . $accessToken
],
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpCode == 200) {
$project = json_decode($response, true);
if (!empty($project) && isset($project['id'])) {
Configuration::updateValue(
AiAnalyticsConstants::CACHE_PROJECT_KEY,
json_encode(['id' => $project['id'], 'time' => time()])
);
return $project['id'];
}
}
} catch (Exception $e) {
PrestaShopLogger::addLog(
'AI Analytics Project Key Error: ' . $e->getMessage(),
3,
null,
AiAnalyticsConstants::MODULE_NAME
);
}
return '';
}
}