Repository navigation
Expand file tree
/
Copy pathAsyntai.module.php
More file actions
715 lines (633 loc) · 32.3 KB
/
Copy pathAsyntai.module.php
File metadata and controls
715 lines (633 loc) · 32.3 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
<?php namespace ProcessWire;
/**
* Asyntai - AI Chatbot
*
* AI assistant / chatbot – Provides instant answers to your website visitors.
*
* Optional page sharing: the module serves a signed, read-only feed of the
* pages a logged-out visitor can already view, in the Asyntai store feed
* format (store_feed_v1). Asyntai reads it so the chatbot answers from the
* current pages without a crawl. Nothing on the site is created or changed.
*
* @copyright Copyright (c) 2025, Asyntai
* @license MIT
*
*/
class Asyntai extends WireData implements Module, ConfigurableModule {
const DEFAULT_ORIGIN = 'https://asyntai.com';
const DEFAULT_SCRIPT = 'https://asyntai.com/static/js/chat-widget.js';
/** How far a signed feed call may be from this server's clock. */
const FEED_CLOCK_SKEW = 300;
/** Pages per feed page, and the most a caller may ask for. */
const FEED_PAGE_SIZE = 50;
const FEED_MAX_PAGE_SIZE = 100;
/**
* Module information
*/
public static function getModuleInfo() {
return array(
'title' => 'Asyntai AI chatbot',
'version' => '1.1.0',
'summary' => 'AI assistant / chatbot – Provides instant answers to your website visitors',
'author' => 'Asyntai',
'href' => 'https://asyntai.com/',
'singular' => true,
'autoload' => true,
'icon' => 'comments',
'requires' => 'ProcessWire>=3.0.0',
);
}
/**
* Default configuration
*/
public static function getDefaultConfig() {
return array(
'site_id' => '',
'script_url' => self::DEFAULT_SCRIPT,
'account_email' => '',
// Page sharing. Never shown in a form, never printed into a page.
'feed_token' => '',
'feed_enabled' => '0',
'handshake_token' => '',
'handshake_share' => '0',
);
}
/**
* Populate default config
*/
public function __construct() {
foreach(self::getDefaultConfig() as $key => $value) {
$this->set($key, $value);
}
}
/**
* Initialize the module
*/
public function init() {
// Load saved configuration
$data = $this->wire('modules')->getModuleConfigData($this);
foreach($data as $key => $value) {
$this->set($key, $value);
}
// The signed page feed answers on the site root: /?asyntai_feed=...
$which = $this->wire('input')->get('asyntai_feed');
if($which === 'products' || $which === 'pages') {
$this->handleFeed($which);
}
}
/**
* Called when API is ready
*/
public function ready() {
// Only inject on frontend, not admin
$page = $this->wire('page');
if($page->template == 'admin') return;
$siteId = trim((string) $this->site_id);
if($siteId === '') return;
// Start output buffering to inject script
ob_start(function($html) use ($siteId) {
$scriptUrl = trim((string) $this->script_url);
if($scriptUrl === '') {
$scriptUrl = self::DEFAULT_SCRIPT;
}
// Inject the widget script only after the page's load event: a
// script started before load still holds the load event open until
// its fetch times out, so an unreachable Asyntai server would delay the page.
$scriptTag = '<script type="text/javascript">'
. '(function(){'
. 'var l=function(){'
. 'var s=document.createElement("script");'
. 's.src=' . json_encode($scriptUrl) . ';'
. 's.async=true;'
. 's.setAttribute("data-asyntai-id",' . json_encode($siteId) . ');'
. 's.charset="UTF-8";'
. 'document.head.appendChild(s)'
. '};'
. 'if(document.readyState==="complete"){l()}'
. 'else{window.addEventListener("load",l)}'
. '})();'
. '</script>';
// Only HTML pages. A template that outputs JSON, XML (a sitemap,
// a feed) or plain text has no </body> and is left untouched.
if(stripos($html, '</body>') !== false) {
$html = preg_replace('#</body>#i', $scriptTag . '</body>', $html, 1);
}
return $html;
});
}
// ------------------------------------------------------------------
// Settings storage
// ------------------------------------------------------------------
/** One saved setting, trimmed. */
protected function cfg($key) {
$data = $this->wire('modules')->getConfig($this);
if(is_array($data) && isset($data[$key])) return trim((string) $data[$key]);
$defaults = self::getDefaultConfig();
return isset($defaults[$key]) ? (string) $defaults[$key] : '';
}
/**
* Save some settings and keep every other one. saveModuleConfigData()
* replaces the whole set, so it is always called with the merged set.
*/
protected function saveCfg(array $changes) {
$modules = $this->wire('modules');
$data = $modules->getConfig($this);
if(!is_array($data)) $data = array();
foreach($changes as $key => $value) {
$data[$key] = $value;
$this->set($key, $value);
}
$modules->saveModuleConfigData($this, $data);
}
// ------------------------------------------------------------------
// Admin AJAX
// ------------------------------------------------------------------
/**
* Handle AJAX requests from the settings screen
*/
protected function handleAjaxRequest() {
$input = $this->wire('input');
$action = (string) $input->post('asyntai_action');
// Verify the user has permission
if(!$this->wire('user')->isSuperuser()) {
$this->sendJson(array('success' => false, 'error' => 'Permission denied'), 403);
return;
}
// Every action changes settings, so it must come from this screen.
$csrf = $this->wire('session')->CSRF;
if(!$csrf->hasValidToken()) {
$this->sendJson(array('success' => false, 'error' => 'Your session has expired. Reload the page and try again.'), 403);
return;
}
if($action === 'save') {
$this->handleSave();
} elseif($action === 'reset') {
$this->handleReset();
} elseif($action === 'prepare') {
$this->handlePrepare();
} elseif($action === 'share') {
$this->handleShare();
} elseif($action === 'status') {
$this->handleStatus();
} else {
$this->sendJson(array('success' => false, 'error' => 'Invalid action'), 400);
}
}
/**
* Handle save action: remember the widget id once the owner signed in.
*/
protected function handleSave() {
$input = $this->wire('input');
$siteId = trim((string) $input->post('site_id'));
if(!preg_match('/^[A-Za-z0-9_-]{6,64}$/', $siteId)) {
$this->sendJson(array('success' => false, 'error' => 'missing site_id'), 400);
return;
}
$scriptUrl = trim((string) $input->post('script_url'));
$accountEmail = trim((string) $input->post('account_email'));
$data = array('site_id' => $siteId);
$data['script_url'] = ($scriptUrl !== '' && stripos($scriptUrl, 'https://') === 0) ? $scriptUrl : self::DEFAULT_SCRIPT;
if($accountEmail !== '') {
$data['account_email'] = substr($accountEmail, 0, 255);
}
// The feed token parked by the last "prepare" becomes live now that
// the sign-in it belongs to has finished.
$pending = $this->cfg('handshake_token');
if($pending !== '') {
$data['feed_token'] = $pending;
$data['feed_enabled'] = $this->cfg('handshake_share') === '1' ? '1' : '0';
$data['handshake_token'] = '';
$data['handshake_share'] = '0';
}
try {
$this->saveCfg($data);
$this->sendJson(array(
'success' => true,
'feed_enabled' => $this->cfg('feed_enabled') === '1' && $this->cfg('feed_token') !== '',
));
} catch(\Exception $e) {
$this->sendJson(array(
'success' => false,
'error' => 'Save failed: ' . $e->getMessage()
), 500);
}
}
/**
* Handle reset action. The feed token goes too: a token kept after a
* reset could only ever sign a call nobody should be able to make.
*/
protected function handleReset() {
$this->saveCfg(array(
'site_id' => '',
'script_url' => self::DEFAULT_SCRIPT,
'account_email' => '',
'feed_token' => '',
'feed_enabled' => '0',
'handshake_token' => '',
'handshake_share' => '0',
));
$this->sendJson(array('success' => true));
}
/**
* Park a fresh feed token at Asyntai under a one-time handshake id.
*
* Without "share" nothing is parked, so connecting works exactly as it
* did before page sharing existed.
*/
protected function handlePrepare() {
$share = $this->wire('input')->post('share') === '1';
$state = 'pw_' . bin2hex(random_bytes(12));
if(!$share) {
$this->saveCfg(array('handshake_token' => '', 'handshake_share' => '0'));
$this->sendJson(array('success' => true, 'state' => $state, 'staged' => false));
return;
}
$token = bin2hex(random_bytes(24));
$root = $this->siteRoot();
$body = $this->httpPostJson($this->origin() . '/api/v1/wp-search/stage/', array(
'state' => $state,
'platform' => 'processwire',
'feed_protocol' => 'store_feed_v1',
// A chatbot install must never unlock the paid AI Search bar.
'product' => 'chat',
'site_url' => $root,
'feed_url' => $root . '/?asyntai_feed=products',
'feed_token' => $token,
));
if($body === null) {
$this->sendJson(array('success' => false, 'error' => 'Could not reach Asyntai. Please try again later.'), 502);
return;
}
// Kept aside until the sign-in finishes, so a handshake that is never
// completed does not leave a token that nobody on the other side holds.
$this->saveCfg(array('handshake_token' => $token, 'handshake_share' => '1'));
$this->sendJson(array('success' => true, 'state' => $state, 'staged' => true));
}
/**
* Switch page sharing on or off.
*/
protected function handleShare() {
$on = $this->wire('input')->post('enabled') === '1';
if($on && $this->cfg('feed_token') === '') {
// Connected before page sharing existed, or after a reset: Asyntai
// has no token for this site yet, so the owner signs in once more.
$this->sendJson(array('success' => false, 'needs_connect' => true));
return;
}
$this->saveCfg(array('feed_enabled' => $on ? '1' : '0'));
$this->sendJson(array('success' => true, 'feed_enabled' => $on));
}
/**
* What Asyntai says about the last read of the pages.
*/
protected function handleStatus() {
$siteId = $this->cfg('site_id');
if($siteId === '') {
$this->sendJson(array('success' => true, 'sync' => null));
return;
}
$body = $this->httpGet($this->origin() . '/api/v1/search-widget/status/?widget_id=' . rawurlencode($siteId));
$decoded = $body === null ? null : json_decode($body, true);
$sync = (is_array($decoded) && isset($decoded['sync']) && is_array($decoded['sync'])) ? $decoded['sync'] : null;
$this->sendJson(array('success' => true, 'sync' => $sync === null ? null : array(
'status' => isset($sync['status']) ? (string) $sync['status'] : '',
'count' => isset($sync['count']) ? (int) $sync['count'] : 0,
'error' => isset($sync['error']) ? (string) $sync['error'] : '',
)));
}
// ------------------------------------------------------------------
// The signed page feed (store_feed_v1)
// ------------------------------------------------------------------
protected function handleFeed($which) {
$input = $this->wire('input');
// The live token, and the one parked by the last "prepare". Asyntai
// starts its first read the moment the owner signs in, a moment
// BEFORE this site saves the sign-in result, so the parked token is
// accepted too. It was only ever sent to Asyntai.
$tokens = array();
$live = $this->cfg('feed_token');
if($live !== '' && $this->cfg('feed_enabled') === '1') $tokens[] = $live;
$pending = $this->cfg('handshake_token');
if($pending !== '' && $this->cfg('handshake_share') === '1') $tokens[] = $pending;
if(!$tokens) {
$this->sendFeed(array('ok' => false, 'error' => 'Page sharing is switched off on this site.'), 403);
}
$page = (string) $input->get('page');
$limit = (string) $input->get('limit');
$ids = (string) $input->get('ids');
$ts = (string) $input->get('ts');
$sig = strtolower((string) $input->get('sig'));
if($ts === '' || !ctype_digit($ts)) {
$this->sendFeed(array('ok' => false, 'error' => 'Missing timestamp.'), 403);
}
if(abs(time() - (int) $ts) > self::FEED_CLOCK_SKEW) {
$this->sendFeed(array('ok' => false, 'error' => 'The request has expired.'), 403);
}
// Signed over the raw values, in a fixed order, before any clamping.
$signed = 'page=' . $page . '&limit=' . $limit . '&ids=' . $ids . '&ts=' . $ts;
$valid = false;
foreach($tokens as $token) {
if($sig !== '' && hash_equals(hash_hmac('sha256', $signed, $token), $sig)) $valid = true;
}
if(!$valid) {
$this->sendFeed(array('ok' => false, 'error' => 'Bad signature.'), 403);
}
$pageNo = max(1, (int) $page);
$size = (int) $limit;
if($size < 1 || $size > self::FEED_MAX_PAGE_SIZE) $size = self::FEED_PAGE_SIZE;
// Everything below is read as a logged-out visitor would see it.
$users = $this->wire('users');
if(method_exists($users, 'setCurrentUser')) {
$users->setCurrentUser($users->getGuestUser());
}
try {
if($which === 'pages') {
$this->sendFeed($this->feedPages($pageNo, $size), 200);
}
// A ProcessWire site sells nothing through this module, so the
// catalogue is always empty. It still answers, because Asyntai
// reads the pages address from it.
$this->sendFeed(array(
'ok' => true,
'store' => $this->storeInfo(),
'page' => $pageNo,
'pages' => 0,
'total' => 0,
'categories' => array(),
'products' => array(),
), 200);
} catch(\Throwable $e) {
$this->sendFeed(array('ok' => false, 'error' => 'Could not read pages.'), 500);
}
}
protected function storeInfo() {
$root = $this->siteRoot();
$home = $this->wire('pages')->get('/');
$name = $home && $home->id ? trim(strip_tags((string) $home->title)) : '';
return array(
'name' => $name !== '' ? $name : $this->wire('config')->httpHost,
'url' => $root,
'currency' => '',
'version' => $this->wire('config')->version,
'pages_url' => $root . '/?asyntai_feed=pages',
);
}
/**
* One page of the pages a logged-out visitor can view: published, not in
* the trash or the admin, and viewable by the guest user.
*/
protected function feedPages($pageNo, $size) {
$pages = $this->wire('pages');
$config = $this->wire('config');
$selector = 'has_parent!=' . (int) $config->adminRootPageID
. ', id!=' . (int) $config->adminRootPageID
. ', has_parent!=' . (int) $config->trashPageID
. ', id!=' . (int) $config->trashPageID
. ', status<' . Page::statusUnpublished
. ', include=hidden, sort=id';
$total = (int) $pages->count($selector);
$found = $pages->find($selector . ', start=' . (($pageNo - 1) * $size) . ', limit=' . $size);
$items = array();
foreach($found as $p) {
if(!$p->viewable()) continue;
$title = trim(html_entity_decode(strip_tags((string) $p->title), ENT_QUOTES, 'UTF-8'));
$content = $this->pageText($p);
if($title === '' || $content === '') continue;
$item = array(
'type' => 'page',
'title' => $title,
'url' => $p->httpUrl,
'content' => $content,
);
if($p->hasField('summary')) {
$summary = $this->plainText((string) $p->getFormatted('summary'));
if($summary !== '') $item['summary'] = $summary;
}
$items[] = $item;
}
return array(
'ok' => true,
'page' => $pageNo,
'pages' => (int) ceil($total / max(1, $size)),
'total' => $total,
'items' => $items,
);
}
/** The page's own text fields, in field order, as plain text. */
protected function pageText(Page $p) {
$parts = array();
foreach($p->template->fieldgroup as $field) {
if($field->name === 'title') continue;
$type = $field->type;
if(!($type instanceof FieldtypeText)) continue;
if($type instanceof FieldtypeEmail) continue;
$text = $this->plainText((string) $p->getFormatted($field->name));
if($text !== '') $parts[] = $text;
}
return trim(implode("\n\n", $parts));
}
protected function plainText($html) {
$html = preg_replace('#<(script|style)[^>]*>.*?</\1>#is', ' ', $html);
$html = preg_replace('#<(br|/p|/div|/li|/h[1-6])\b[^>]*>#i', "\n", $html);
$text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
$text = preg_replace("/[ \t]+/", ' ', $text);
$text = preg_replace("/\n\s*\n+/", "\n\n", $text);
return trim($text);
}
protected function sendFeed(array $data, $status) {
while(ob_get_level()) ob_end_clean();
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Robots-Tag: noindex');
echo json_encode($data);
exit;
}
// ------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------
/** Where the module talks to. $config->asyntaiOrigin overrides it for testing. */
protected function origin() {
$custom = (string) $this->wire('config')->asyntaiOrigin;
return $custom !== '' ? rtrim($custom, '/') : self::DEFAULT_ORIGIN;
}
/** The public site root, without a trailing slash. */
protected function siteRoot() {
return rtrim($this->wire('config')->urls->httpRoot, '/');
}
/** WireHttp with one transport only, so a dead origin waits one timeout, not three. */
protected function http() {
$http = new WireHttp();
$http->setTimeout(10);
$http->setHeader('Accept', 'application/json');
$this->wire($http);
return $http;
}
protected function transport() {
return function_exists('curl_init') ? array('use' => 'curl') : array('use' => 'fopen');
}
protected function httpPostJson($url, array $payload) {
$http = $this->http();
$http->setHeader('Content-Type', 'application/json');
$body = $http->send($url, json_encode($payload), 'POST', $this->transport());
$code = (int) $http->getHttpCode();
return ($body === false || $code < 200 || $code >= 300) ? null : $body;
}
protected function httpGet($url) {
$http = $this->http();
$body = $http->get($url, array(), $this->transport());
$code = (int) $http->getHttpCode();
return ($body === false || $code < 200 || $code >= 300) ? null : $body;
}
/**
* Send JSON response
*/
protected function sendJson($data, $status = 200) {
// Clean any output buffers to prevent HTML from being sent
while(ob_get_level()) {
ob_end_clean();
}
// Set headers
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
// Send JSON and exit immediately
echo json_encode($data);
exit;
}
/**
* Build configuration form
*/
public function getModuleConfigInputfields(array $data) {
// Handle AJAX requests FIRST, before any HTML is generated
$input = $this->wire('input');
if($input->post('asyntai_action')) {
$this->handleAjaxRequest();
// handleAjaxRequest will exit, so we never reach here
}
$modules = $this->wire('modules');
$inputfields = $modules->get('InputfieldWrapper');
$siteId = isset($data['site_id']) ? trim((string) $data['site_id']) : '';
$accountEmail = isset($data['account_email']) ? trim((string) $data['account_email']) : '';
$connected = $siteId !== '';
$feedOn = isset($data['feed_enabled'], $data['feed_token'])
&& (string) $data['feed_enabled'] === '1' && trim((string) $data['feed_token']) !== '';
// Add custom markup for status and connection UI
$markup = $modules->get('InputfieldMarkup');
$markup->label = $this->_('Asyntai Connection');
$markup->icon = 'comments';
$statusColor = $connected ? '#008a20' : '#a00';
$statusText = $connected ? 'Connected' : 'Not connected';
$statusExtra = ($connected && $accountEmail) ? ' as ' . $this->wire('sanitizer')->entities($accountEmail) : '';
$resetBtn = $connected ? '<button type="button" id="asyntai-reset" class="ui-button ui-state-default" style="margin-left:8px;">Reset</button>' : '';
$html = '<div id="asyntai-settings-wrap">';
$html .= '<p id="asyntai-status">Status: <span style="color:' . $statusColor . ';">' . $statusText . '</span>' . $statusExtra . $resetBtn . '</p>';
$html .= '<div id="asyntai-alert" class="NoticeMessage" style="display:none;margin:10px 0;"></div>';
// Connected box
$html .= '<div id="asyntai-connected-box" style="display:' . ($connected ? 'block' : 'none') . ';">';
$html .= '<div style="max-width:820px;margin:20px auto;padding:20px;border:1px solid #ddd;border-radius:8px;background:#fff;text-align:center;">';
$html .= '<div style="font-size:20px;font-weight:700;margin-bottom:8px;">Asyntai is now enabled</div>';
$html .= '<div style="font-size:16px;margin-bottom:16px;">Set up your AI chatbot, review chat logs and more:</div>';
$html .= '<a class="ui-button ui-state-default ui-priority-primary" style="padding:8px 16px;text-decoration:none;" href="https://asyntai.com/dashboard" target="_blank" rel="noopener">Open Asyntai Panel</a>';
$html .= '<div style="margin-top:16px;font-size:14px;color:#666;">';
$html .= '<strong>Tip:</strong> If you want to change how the AI answers, please <a href="https://asyntai.com/dashboard#setup" target="_blank" rel="noopener" style="color:#3182ce;text-decoration:underline;">go here</a>.';
$html .= '</div>';
$html .= '<div id="asyntai-share-box" style="margin-top:18px;padding-top:14px;border-top:1px solid #eee;text-align:left;">';
$html .= '<label style="display:flex;align-items:flex-start;gap:8px;"><input type="checkbox" id="asyntai-share-toggle"' . ($feedOn ? ' checked' : '') . ' style="margin-top:4px;">';
$html .= '<span><strong>Share my published pages with the chatbot</strong><br><small style="color:#666;">Asyntai reads the published pages that any visitor can already see, and checks them again for changes. Nothing on your site is changed.</small></span></label>';
$html .= '<div id="asyntai-share-status" style="margin-top:8px;color:#555;"></div>';
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
// Connect popup UI
$html .= '<div id="asyntai-popup-wrap" style="display:' . ($connected ? 'none' : 'block') . ';">';
$html .= '<div style="max-width:960px;margin:20px auto;padding:24px;border:1px solid #ddd;border-radius:8px;background:#fff;text-align:center;">';
$html .= '<div style="font-size:18px;margin-bottom:12px;">Create a free Asyntai account or sign in to enable the chatbot</div>';
$html .= '<label style="display:inline-flex;align-items:flex-start;gap:8px;text-align:left;max-width:560px;margin:4px auto 16px;"><input type="checkbox" id="asyntai-share" checked style="margin-top:4px;">';
$html .= '<span>Let the chatbot read my published pages directly, so its answers stay up to date.<br><small style="color:#666;">Only published pages that any visitor can already see. Nothing on your site is changed.</small></span></label>';
$html .= '<div><button type="button" id="asyntai-connect-btn" class="ui-button ui-state-default ui-priority-primary" style="padding:8px 16px;">Get started</button></div>';
$html .= '<div style="margin-top:12px;color:#666;">If it doesn\'t work, <a href="#" id="asyntai-fallback-link" target="_blank" rel="noopener">open the connect window</a>.</div>';
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
// JavaScript for connection flow
$csrf = $this->wire('session')->CSRF;
$ajaxUrl = $this->wire('config')->urls->admin . 'module/edit?name=Asyntai';
$html .= '<script>' . strtr(self::ADMIN_JS, array(
'__AJAX__' => json_encode($ajaxUrl),
'__ORIGIN__' => json_encode($this->origin()),
'__CSRF_NAME__' => json_encode($csrf->getTokenName()),
'__CSRF_VALUE__' => json_encode($csrf->getTokenValue()),
'__SITE_ID__' => json_encode($siteId),
)) . '</script>';
$markup->value = $html;
$inputfields->add($markup);
return $inputfields;
}
/**
* Settings screen script. Placeholders are replaced with JSON values.
*
* The sign-in window opens at once, inside the click, so a popup blocker
* lets it through; it is pointed at the sign-in page as soon as the feed
* is parked. If parking fails, connecting works exactly as before, only
* without page sharing.
*/
const ADMIN_JS = <<<'JS'
(function(){
var AJAX=__AJAX__,ORIGIN=__ORIGIN__,CSRF_NAME=__CSRF_NAME__,CSRF_VALUE=__CSRF_VALUE__,SITE_ID=__SITE_ID__;
var AUTH=ORIGIN+"/wp-auth?platform=processwire";
var currentState=null;
function $(id){return document.getElementById(id);}
function showAlert(msg,ok){var el=$("asyntai-alert");if(!el)return;el.style.display="block";el.className=ok?"NoticeMessage":"NoticeError";el.textContent=msg;}
function generateState(){return "pw_"+Math.random().toString(36).substr(2,9)+Math.random().toString(36).substr(2,9);}
function call(action,fields){var fd=new FormData();fd.append("asyntai_action",action);fd.append(CSRF_NAME,CSRF_VALUE);for(var k in (fields||{})){fd.append(k,fields[k]);}
return fetch(AJAX,{method:"POST",credentials:"same-origin",headers:{"X-Requested-With":"XMLHttpRequest"},body:fd}).then(function(r){return r.json().catch(function(){return {success:false,error:"HTTP "+r.status};});});}
function updateFallbackLink(){var a=$("asyntai-fallback-link");if(a&¤tState){a.href=AUTH+"&state="+encodeURIComponent(currentState);}}
function openWindow(){var w=800,h=720;var y=window.top.outerHeight/2+window.top.screenY-(h/2);var x=window.top.outerWidth/2+window.top.screenX-(w/2);
return window.open("","asyntai_connect","toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width="+w+",height="+h+",top="+y+",left="+x);}
function startConnect(share){
var pop=openWindow();
if(!pop){showAlert("Popup blocked. Please allow popups or use the link below.",false);return;}
var go=function(state){currentState=state;updateFallbackLink();try{pop.location.href=AUTH+"&state="+encodeURIComponent(state);}catch(e){}pollForConnection(state);};
call("prepare",{share:share?"1":"0"}).then(function(res){go(res&&res.success&&res.state?res.state:generateState());}).catch(function(){go(generateState());});
}
function pollForConnection(state){var attempts=0;function check(){if(attempts++>240)return;var script=document.createElement("script");var cb="asyntai_cb_"+Date.now();
script.src=ORIGIN+"/connect-status.js?state="+encodeURIComponent(state)+"&cb="+cb;
window[cb]=function(data){try{delete window[cb];}catch(e){} if(data&&data.site_id){saveConnection(data);return;} setTimeout(check,500);};
script.onerror=function(){setTimeout(check,1000);};document.head.appendChild(script);}setTimeout(check,800);}
function saveConnection(data){showAlert("Asyntai connected. Saving…",true);
call("save",{site_id:data.site_id||"",script_url:data.script_url||"",account_email:data.account_email||""}).then(function(json){
if(!json||!json.success)throw new Error(json&&json.error||"Save failed");
showAlert("Asyntai connected. Chatbot enabled on all pages.",true);
var status=$("asyntai-status");if(status){status.innerHTML="Status: <span style=\"color:#008a20;\">Connected</span>";
if(data.account_email){status.appendChild(document.createTextNode(" as "+data.account_email));}
var b=document.createElement("button");b.type="button";b.id="asyntai-reset";b.className="ui-button ui-state-default";b.style.marginLeft="8px";b.textContent="Reset";status.appendChild(b);}
var box=$("asyntai-connected-box");if(box)box.style.display="block";var wrap=$("asyntai-popup-wrap");if(wrap)wrap.style.display="none";
SITE_ID=data.site_id;var t=$("asyntai-share-toggle");if(t)t.checked=!!json.feed_enabled;refreshStatus(0);
}).catch(function(err){showAlert("Could not save settings: "+(err&&err.message||err),false);});}
function resetConnection(){if(!confirm("Are you sure you want to disconnect Asyntai?"))return;
call("reset").then(function(res){if(!res||!res.success)throw new Error(res&&res.error||"Reset failed");window.location.reload();})
.catch(function(err){showAlert("Reset failed: "+(err&&err.message||err),false);});}
function refreshStatus(tries){var box=$("asyntai-share-status"),t=$("asyntai-share-toggle");if(!box||!t)return;if(!t.checked||!SITE_ID){box.textContent="";return;}
call("status").then(function(res){if(!res||!res.success){box.textContent="";return;}var s=res.sync;
if(!s){box.textContent="Asyntai has not read your pages yet.";return;}
if(s.status==="syncing"){box.textContent="Reading your pages…";if(tries<20)setTimeout(function(){refreshStatus(tries+1);},5000);return;}
if(s.status==="failed"){box.textContent="The last read failed: "+(s.error||"unknown error");return;}
box.textContent="Pages shared: "+(s.count||0)+" items. Asyntai checks them again for changes.";}).catch(function(){box.textContent="";});}
function onToggle(t){var on=!!t.checked;
call("share",{enabled:on?"1":"0"}).then(function(res){if(!res||!res.success){t.checked=!on;
if(res&&res.needs_connect){showAlert("Sign in to Asyntai once more to share your pages.",true);startConnect(true);return;}
showAlert((res&&res.error)||"Could not save.",false);return;}
showAlert(on?"Page sharing is on.":"Page sharing is off. Asyntai can no longer read your pages.",true);refreshStatus(0);
}).catch(function(){t.checked=!on;showAlert("Could not save.",false);});}
currentState=generateState();updateFallbackLink();
document.addEventListener("click",function(ev){var t=ev.target;
if(t&&t.id==="asyntai-connect-btn"){ev.preventDefault();var s=$("asyntai-share");startConnect(s?!!s.checked:false);}
if(t&&t.id==="asyntai-reset"){ev.preventDefault();resetConnection();}
if(t&&t.id==="asyntai-fallback-link"){currentState=generateState();updateFallbackLink();setTimeout(function(){pollForConnection(currentState);},1000);}
});
document.addEventListener("change",function(ev){var t=ev.target;if(t&&t.id==="asyntai-share-toggle"){onToggle(t);}});
refreshStatus(0);
})();
JS;
}