Plugin Directory

Changeset 3833468


Ignore:
Timestamp:
11/29/2026 06:13:52 PM (less than one hour ago)
Author:
palwp
Message:

Release 2.0.0: a complete rewrite. Listing banner, icons and 19 screenshots.

Location:
chathearth
Files:
450 added
40 deleted
68 edited
1 copied

Legend:

Unmodified
Added
Removed
  • chathearth/tags/2.0.0/assets/css/admin.css

    r3663506 r3833468  
    1 .chathearth-settings .form-table th {
    2         width: 220px;
     1/*
     2 * ChatHearth settings page styles.
     3 *
     4 * One hand-written stylesheet, scoped under .chathearth-settings, with logical
     5 * properties only so that right-to-left pages mirror without extra rules.
     6 * The accent follows the WordPress admin colour scheme.
     7 *
     8 * Contents:
     9 *   1. Tokens and base
     10 *   2. Header and notices
     11 *   3. Layout and tab navigation
     12 *   4. Cards and fields
     13 *   5. Controls (toggle, segmented, number, colour, secret, checkgrid)
     14 *   6. Small components (pill, badge, callout, stats, progress, toast, ...)
     15 *   7. Protection sub-tabs and rate-limit groups
     16 *   8. Appearance: live preview, launcher, product cards
     17 *   9. Knowledge Base index
     18 *  10. Advanced: system status
     19 */
     20
     21/* 1. Tokens and base
     22   ========================================================================== */
     23
     24.chathearth-settings {
     25        --chathearth-accent: var(--wp-admin-theme-color, #2271b1);
     26        --chathearth-accent-strong: var(--wp-admin-theme-color-darker-10, #135e96);
     27        --chathearth-text: #1d2327;
     28        --chathearth-text-muted: #50575e;
     29        --chathearth-border: #dcdcde;
     30        --chathearth-control-border: #8c8f94;
     31        --chathearth-surface: #fff;
     32        --chathearth-surface-alt: #f6f7f7;
     33        --chathearth-page: #f0f0f1;
     34
     35        --chathearth-success: #00a32a;
     36        --chathearth-success-bg: #edfaef;
     37        --chathearth-success-text: #0a6b20;
     38        --chathearth-warning: #996800;
     39        --chathearth-warning-bg: #fcf9e8;
     40        --chathearth-warning-text: #7a5200;
     41        --chathearth-error: #d63638;
     42        --chathearth-error-bg: #fcf0f1;
     43        --chathearth-error-text: #b32d2e;
     44        --chathearth-info: #72aee6;
     45        --chathearth-info-bg: #f0f6fc;
     46
     47        --chathearth-radius-card: 8px;
     48        --chathearth-radius-control: 4px;
     49        --chathearth-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
     50
     51        --chathearth-space-1: 4px;
     52        --chathearth-space-2: 8px;
     53        --chathearth-space-3: 12px;
     54        --chathearth-space-4: 16px;
     55        --chathearth-space-5: 24px;
     56        --chathearth-space-6: 32px;
     57        --chathearth-space-7: 48px;
     58
     59        --chathearth-motion: 150ms ease-out;
     60        --chathearth-label-width: 220px;
     61        --chathearth-sticky-top: calc(var(--wp-admin--admin-bar--height, 32px) + 16px);
     62
     63        color: var(--chathearth-text);
     64        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
     65        font-size: 13px;
     66        line-height: 1.5;
     67        min-inline-size: 0;
     68}
     69
     70.chathearth-settings *,
     71.chathearth-settings *::before,
     72.chathearth-settings *::after {
     73        box-sizing: border-box;
     74}
     75
     76.chathearth-settings [hidden] {
     77        display: none !important;
     78}
     79
     80.chathearth-icon {
     81        display: inline-block;
     82        inline-size: 18px;
     83        block-size: 18px;
     84        flex: none;
     85        fill: none;
     86        stroke: currentcolor;
     87        stroke-width: 1.8;
     88        stroke-linecap: round;
     89        stroke-linejoin: round;
     90        vertical-align: middle;
     91}
     92
     93/* Accessible focus ring for all interactive elements */
     94.chathearth-settings :focus-visible {
     95        outline: 2px solid transparent;
     96        box-shadow: 0 0 0 2px var(--chathearth-surface), 0 0 0 4px var(--chathearth-accent) !important;
     97}
     98
     99/* 2. Header and notices
     100   ========================================================================== */
     101
     102.chathearth-settings .chathearth-header {
     103        display: flex;
     104        flex-wrap: wrap;
     105        align-items: center;
     106        justify-content: space-between;
     107        gap: var(--chathearth-space-4);
     108        padding-block: var(--chathearth-space-5) var(--chathearth-space-4);
     109}
     110
     111.chathearth-settings .chathearth-header__brand {
     112        display: flex;
     113        align-items: center;
     114        gap: var(--chathearth-space-3);
     115        min-inline-size: 0;
     116}
     117
     118.chathearth-settings .chathearth-logo {
     119        display: grid;
     120        place-items: center;
     121        inline-size: 40px;
     122        block-size: 40px;
     123        border-radius: var(--chathearth-radius-card);
     124        background: var(--chathearth-accent);
     125        color: #fff;
     126}
     127
     128.chathearth-settings .chathearth-logo .chathearth-icon {
     129        inline-size: 24px;
     130        block-size: 24px;
     131}
     132
     133.chathearth-settings .chathearth-header__title {
     134        margin: 0;
     135        color: var(--chathearth-text);
     136        font-size: 23px;
     137        font-weight: 400;
     138        line-height: 1.2;
     139}
     140
     141.chathearth-settings .chathearth-header__title span {
     142        color: var(--chathearth-text-muted);
     143        font-size: 15px;
     144        font-weight: 400;
     145}
     146
     147.chathearth-settings .chathearth-header__tagline {
     148        margin: 2px 0 0;
     149        color: var(--chathearth-text-muted);
     150        font-size: 12px;
     151}
     152
     153.chathearth-settings .chathearth-header__actions {
     154        display: flex;
     155        align-items: center;
     156        gap: var(--chathearth-space-3);
     157}
     158
     159.chathearth-settings .chathearth-header__actions a {
     160        display: inline-flex;
     161        align-items: center;
     162        color: var(--chathearth-text-muted);
     163        font-size: 12px;
     164        text-decoration: none;
     165}
     166
     167.chathearth-settings .chathearth-header__actions a:hover {
     168        color: var(--chathearth-accent);
     169        text-decoration: underline;
     170}
     171
     172.chathearth-settings .chathearth-notices {
     173        margin-block-end: var(--chathearth-space-4);
     174}
     175
     176.chathearth-settings .chathearth-notices .notice {
     177        margin-block: 0 var(--chathearth-space-3);
     178}
     179
     180/* 3. Layout and tab navigation
     181   ========================================================================== */
     182
     183.chathearth-settings .chathearth-layout {
     184        display: grid;
     185        grid-template-columns: minmax(180px, 200px) minmax(0, 1fr);
     186        gap: var(--chathearth-space-5);
     187        align-items: start;
    3188}
    4189
    5190.chathearth-settings .chathearth-tabs {
    6         margin: 16px 0 0;
    7 }
    8 
    9 .chathearth-settings .chathearth-tab-panel {
    10         margin-top: 8px;
     191        position: sticky;
     192        inset-block-start: var(--chathearth-sticky-top);
     193        z-index: 10;
     194}
     195
     196.chathearth-settings .chathearth-tabs [role="tablist"] {
     197        display: flex;
     198        flex-direction: column;
     199        gap: 2px;
     200}
     201
     202.chathearth-settings .chathearth-tabs__tab {
     203        display: flex;
     204        align-items: center;
     205        gap: var(--chathearth-space-3);
     206        padding-block: 10px;
     207        padding-inline: 14px;
     208        border-radius: var(--chathearth-radius-control);
     209        color: var(--chathearth-text);
     210        font-size: 13px;
     211        font-weight: 500;
     212        text-decoration: none;
     213        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     214        cursor: pointer;
     215        user-select: none;
     216}
     217
     218.chathearth-settings .chathearth-tabs__tab:hover {
     219        background: var(--chathearth-surface);
     220        color: var(--chathearth-accent);
     221}
     222
     223.chathearth-settings .chathearth-tabs__tab.is-active {
     224        background: var(--chathearth-accent);
     225        color: #fff;
     226        font-weight: 600;
     227}
     228
     229.chathearth-settings .chathearth-tabs__tab .chathearth-icon {
     230        inline-size: 18px;
     231        block-size: 18px;
     232}
     233
     234.chathearth-settings .chathearth-tabs__dirty {
     235        display: inline-block;
     236        inline-size: 7px;
     237        block-size: 7px;
     238        margin-inline-start: auto;
     239        border-radius: 50%;
     240        background: var(--chathearth-warning);
     241}
     242
     243.chathearth-settings .chathearth-tabs__dirty[hidden] {
     244        display: none;
     245}
     246
     247.chathearth-settings .chathearth-subtabs__tab .chathearth-tabs__dirty {
     248        margin-inline-start: 6px;
     249}
     250
     251.chathearth-settings .chathearth-tabs__tab.is-active .chathearth-tabs__dirty,
     252.chathearth-settings .chathearth-subtabs__tab.is-active .chathearth-tabs__dirty {
    11253        background: #fff;
    12         border: 1px solid #c3c4c7;
    13         border-top: none;
    14         padding: 8px 16px 16px;
    15 }
    16 
    17 .chathearth-settings .chathearth-tab-panel[hidden] {
    18         display: none !important;
    19 }
    20 
    21 .chathearth-settings .nav-tab-wrapper {
    22         border-bottom: 1px solid #c3c4c7;
    23 }
    24 
    25 .chathearth-settings .chathearth-recaptcha-status {
    26         margin: 0 0 8px;
    27         border-left-color: #00a32a;
    28 }
    29 
    30 .chathearth-settings .chathearth-check-row {
     254}
     255
     256.chathearth-settings .chathearth-main {
     257        min-inline-size: 0;
     258}
     259
     260.chathearth-settings .chathearth-panel {
     261        max-inline-size: 880px;
     262}
     263
     264.chathearth-settings #chathearth-panel-appearance {
     265        max-inline-size: 1240px;
     266}
     267
     268/* 4. Cards and fields
     269   ========================================================================== */
     270
     271.chathearth-settings .chathearth-card {
     272        margin-block-end: var(--chathearth-space-5);
     273        border: 1px solid var(--chathearth-border);
     274        border-radius: var(--chathearth-radius-card);
     275        background: var(--chathearth-surface);
     276        box-shadow: var(--chathearth-shadow);
     277}
     278
     279.chathearth-settings .chathearth-card__header {
     280        display: flex;
     281        flex-wrap: wrap;
     282        align-items: center;
     283        justify-content: space-between;
     284        gap: var(--chathearth-space-3);
     285        padding: var(--chathearth-space-4) var(--chathearth-space-5);
     286        border-block-end: 1px solid var(--chathearth-border);
     287        background: var(--chathearth-surface-alt);
     288        border-start-start-radius: var(--chathearth-radius-card);
     289        border-start-end-radius: var(--chathearth-radius-card);
     290}
     291
     292.chathearth-settings .chathearth-card__title {
     293        margin: 0;
     294        color: var(--chathearth-text);
     295        font-size: 15px;
     296        font-weight: 600;
     297        line-height: 1.3;
     298}
     299
     300.chathearth-settings .chathearth-card__desc {
     301        margin: 3px 0 0;
     302        color: var(--chathearth-text-muted);
     303        font-size: 12px;
     304}
     305
     306.chathearth-settings .chathearth-card__body {
     307        padding: var(--chathearth-space-4) var(--chathearth-space-5);
     308}
     309
     310/* Field row: label column + control column (flex layout) */
     311.chathearth-settings .chathearth-field {
     312        display: flex;
     313        align-items: flex-start;
     314        gap: var(--chathearth-space-4);
     315        margin-block-end: var(--chathearth-space-4);
     316        padding-block-end: var(--chathearth-space-4);
     317        border-block-end: 1px solid var(--chathearth-surface-alt);
     318}
     319
     320.chathearth-settings .chathearth-field:last-child {
     321        margin-block-end: 0;
     322        padding-block-end: 0;
     323        border-block-end: none;
     324}
     325
     326.chathearth-settings .chathearth-field__label,
     327.chathearth-settings legend.chathearth-field__label {
    31328        display: block;
    32         margin: 0 0 6px;
    33 }
    34 
    35 .chathearth-settings .chathearth-inline-label {
    36         margin-left: 16px;
    37 }
     329        flex: 0 0 var(--chathearth-label-width);
     330        inline-size: var(--chathearth-label-width);
     331        max-inline-size: var(--chathearth-label-width);
     332        box-sizing: border-box;
     333        padding-block-start: 4px;
     334        color: var(--chathearth-text);
     335        font-size: 13px;
     336        font-weight: 600;
     337        line-height: 1.4;
     338        word-break: break-word;
     339}
     340
     341.chathearth-settings .chathearth-field__label label {
     342        display: inline-block;
     343        color: inherit;
     344        font-weight: inherit;
     345        cursor: pointer;
     346}
     347
     348.chathearth-settings .chathearth-field__control {
     349        flex: 1 1 0%;
     350        min-inline-size: 0;
     351}
     352
     353.chathearth-settings .chathearth-field__control :is(input, select, textarea) {
     354        max-inline-size: 100%;
     355}
     356
     357/* Field groups: a legend is laid out outside flex, so the group is a block */
     358.chathearth-settings fieldset.chathearth-field {
     359        display: block;
     360        margin: 0;
     361        margin-block-end: var(--chathearth-space-4);
     362        padding: 0;
     363        padding-block-end: var(--chathearth-space-4);
     364        border: 0;
     365        border-block-end: 1px solid var(--chathearth-surface-alt);
     366}
     367
     368.chathearth-settings fieldset.chathearth-field:last-child {
     369        margin-block-end: 0;
     370        padding-block-end: 0;
     371        border-block-end: none;
     372}
     373
     374.chathearth-settings fieldset.chathearth-field::after {
     375        content: "";
     376        display: table;
     377        clear: both;
     378}
     379
     380.chathearth-settings fieldset.chathearth-field > legend.chathearth-field__label {
     381        float: inline-start;
     382        inline-size: var(--chathearth-label-width);
     383        max-inline-size: var(--chathearth-label-width);
     384        margin: 0;
     385        padding: 0;
     386        padding-block-start: 4px;
     387}
     388
     389.chathearth-settings fieldset.chathearth-field > .chathearth-field__control {
     390        margin-inline-start: calc(var(--chathearth-label-width) + var(--chathearth-space-4));
     391}
     392
     393.chathearth-settings .chathearth-error {
     394        margin-block: 6px 0;
     395        margin-inline: 0;
     396        color: var(--chathearth-error-text);
     397        font-size: 12px;
     398        font-weight: 500;
     399}
     400
     401.chathearth-settings .chathearth-field--error input,
     402.chathearth-settings .chathearth-field--error select,
     403.chathearth-settings .chathearth-field--error textarea {
     404        border-color: var(--chathearth-error);
     405}
     406
     407/* 5. Controls
     408   ========================================================================== */
     409
     410/* Toggle Switch (checkbox with role="switch") */
     411.chathearth-settings .chathearth-switch {
     412        display: inline-flex;
     413        align-items: center;
     414        gap: var(--chathearth-space-2);
     415        min-block-size: 28px;
     416}
     417
     418.chathearth-settings .chathearth-toggle {
     419        -webkit-appearance: none;
     420        appearance: none;
     421        position: relative;
     422        flex: none;
     423        inline-size: 36px;
     424        min-inline-size: 36px;
     425        block-size: 20px;
     426        margin: 0;
     427        padding: 0;
     428        border: 0;
     429        border-radius: 10px;
     430        background: var(--chathearth-control-border);
     431        box-shadow: none;
     432        line-height: 1;
     433        cursor: pointer;
     434        transition: background-color var(--chathearth-motion);
     435}
     436
     437.chathearth-settings .chathearth-toggle::before,
     438.chathearth-settings .chathearth-toggle:checked::before {
     439        content: "";
     440        position: absolute;
     441        inset-block-start: 2px;
     442        inset-inline-start: 2px;
     443        inline-size: 16px;
     444        block-size: 16px;
     445        margin: 0;
     446        border-radius: 50%;
     447        background: #fff;
     448        line-height: 1;
     449        transition: inset-inline-start var(--chathearth-motion);
     450}
     451
     452.chathearth-settings .chathearth-toggle:checked {
     453        background: var(--chathearth-accent);
     454}
     455
     456.chathearth-settings .chathearth-toggle:checked::before {
     457        inset-inline-start: 18px;
     458}
     459
     460.chathearth-settings .chathearth-toggle:disabled {
     461        opacity: 0.5;
     462        cursor: not-allowed;
     463}
     464
     465.chathearth-settings .chathearth-switch__state {
     466        color: var(--chathearth-text-muted);
     467        font-size: 13px;
     468        user-select: none;
     469}
     470
     471/* Segmented Control */
     472.chathearth-settings .chathearth-segmented {
     473        position: relative;
     474        display: inline-flex;
     475        flex-wrap: wrap;
     476        max-inline-size: 100%;
     477}
     478
     479.chathearth-settings .chathearth-segmented input[type="radio"] {
     480        position: absolute;
     481        inline-size: 1px;
     482        block-size: 1px;
     483        margin: 0;
     484        opacity: 0;
     485        pointer-events: none;
     486}
     487
     488.chathearth-settings .chathearth-segmented label {
     489        display: inline-flex;
     490        align-items: center;
     491        gap: 6px;
     492        min-block-size: 32px;
     493        margin-inline-end: -1px;
     494        padding-block: 4px;
     495        padding-inline: 12px;
     496        border: 1px solid var(--chathearth-control-border);
     497        background: var(--chathearth-surface);
     498        color: var(--chathearth-text);
     499        font-size: 13px;
     500        cursor: pointer;
     501        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     502        user-select: none;
     503}
     504
     505.chathearth-settings .chathearth-checkgrid label {
     506        display: inline-flex;
     507        align-items: center;
     508        gap: var(--chathearth-space-2);
     509        color: var(--chathearth-text);
     510        font-size: 13px;
     511        cursor: pointer;
     512}
     513
     514.chathearth-settings .chathearth-segmented label:first-of-type {
     515        border-start-start-radius: var(--chathearth-radius-control);
     516        border-end-start-radius: var(--chathearth-radius-control);
     517}
     518
     519.chathearth-settings .chathearth-segmented label:last-of-type {
     520        margin-inline-end: 0;
     521        border-start-end-radius: var(--chathearth-radius-control);
     522        border-end-end-radius: var(--chathearth-radius-control);
     523}
     524
     525.chathearth-settings .chathearth-segmented input[type="radio"]:checked + label {
     526        z-index: 1;
     527        border-color: var(--chathearth-accent);
     528        background: var(--chathearth-accent);
     529        color: #fff;
     530        font-weight: 600;
     531}
     532
     533.chathearth-settings .chathearth-segmented input[type="radio"]:focus-visible + label {
     534        z-index: 2;
     535        box-shadow: 0 0 0 2px var(--chathearth-surface), 0 0 0 4px var(--chathearth-accent);
     536}
     537
     538/* Number + Unit and Range Sliders */
     539.chathearth-settings .chathearth-input-group {
     540        display: flex;
     541        flex-wrap: wrap;
     542        align-items: center;
     543        gap: var(--chathearth-space-2) var(--chathearth-space-3);
     544}
     545
     546.chathearth-settings .chathearth-input-group .small-text {
     547        inline-size: 6em;
     548}
     549
     550.chathearth-settings .chathearth-input-group input[type="range"] {
     551        flex: 0 1 150px;
     552        inline-size: 150px;
     553        min-inline-size: 90px;
     554        margin: 0;
     555        accent-color: var(--chathearth-accent);
     556}
     557
     558.chathearth-settings .chathearth-input-group__unit {
     559        color: var(--chathearth-text-muted);
     560        font-size: 13px;
     561}
     562
     563/* Colour Field */
     564.chathearth-settings .chathearth-color {
     565        display: inline-flex;
     566        align-items: center;
     567        gap: var(--chathearth-space-2);
     568}
     569
     570.chathearth-settings .chathearth-color input[type="color"] {
     571        inline-size: 32px;
     572        block-size: 32px;
     573        padding: 2px;
     574        border: 1px solid var(--chathearth-control-border);
     575        border-radius: var(--chathearth-radius-control);
     576        background: #fff;
     577        cursor: pointer;
     578}
     579
     580.chathearth-settings .chathearth-color__hex {
     581        inline-size: 9em;
     582        font-family: Consolas, Monaco, monospace;
     583        direction: ltr;
     584        text-align: start;
     585}
     586
     587/* Secret Field */
     588.chathearth-settings .chathearth-secret {
     589        display: flex;
     590        flex-direction: column;
     591        gap: var(--chathearth-space-2);
     592}
     593
     594.chathearth-settings .chathearth-secret__saved {
     595        display: flex;
     596        align-items: center;
     597        gap: var(--chathearth-space-3);
     598        color: var(--chathearth-text-muted);
     599        font-size: 13px;
     600}
     601
     602/* Checkbox Grid */
     603.chathearth-settings .chathearth-checkgrid {
     604        display: grid;
     605        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
     606        gap: var(--chathearth-space-2) var(--chathearth-space-4);
     607        margin: 0;
     608        padding: 0;
     609        border: 0;
     610}
     611
     612.chathearth-settings .chathearth-count {
     613        color: var(--chathearth-text-muted);
     614        font-size: 12px;
     615}
     616
     617.chathearth-settings .chathearth-code-input {
     618        font-family: Consolas, Monaco, monospace;
     619        font-size: 12px;
     620        direction: ltr;
     621        text-align: start;
     622}
     623
     624/* 6. Small components
     625   ========================================================================== */
     626
     627/* Status Pill */
     628.chathearth-settings .chathearth-pill {
     629        display: inline-flex;
     630        align-items: center;
     631        gap: 6px;
     632        padding-block: 2px;
     633        padding-inline: 8px;
     634        border-radius: 9999px;
     635        background: var(--chathearth-surface-alt);
     636        color: var(--chathearth-text);
     637        font-size: 11px;
     638        font-weight: 600;
     639        line-height: 1.4;
     640        white-space: nowrap;
     641}
     642
     643.chathearth-settings .chathearth-pill::before {
     644        content: "";
     645        inline-size: 6px;
     646        block-size: 6px;
     647        border-radius: 50%;
     648        background: currentcolor;
     649}
     650
     651.chathearth-settings .chathearth-pill--success {
     652        background: var(--chathearth-success-bg);
     653        color: var(--chathearth-success-text);
     654}
     655
     656.chathearth-settings .chathearth-pill--warning {
     657        background: var(--chathearth-warning-bg);
     658        color: var(--chathearth-warning-text);
     659}
     660
     661.chathearth-settings .chathearth-pill--error {
     662        background: var(--chathearth-error-bg);
     663        color: var(--chathearth-error-text);
     664}
     665
     666.chathearth-settings .chathearth-pill--neutral {
     667        background: var(--chathearth-surface-alt);
     668        color: var(--chathearth-text-muted);
     669}
     670
     671/* Badges */
     672.chathearth-settings .chathearth-badge {
     673        display: inline-block;
     674        padding-block: 2px;
     675        padding-inline: 6px;
     676        border: 1px solid var(--chathearth-border);
     677        border-radius: 3px;
     678        background: var(--chathearth-surface-alt);
     679        color: var(--chathearth-text-muted);
     680        font-size: 11px;
     681        font-weight: 500;
     682        line-height: 1.2;
     683}
     684
     685/* Callout Box */
     686.chathearth-settings .chathearth-callout {
     687        display: flex;
     688        align-items: flex-start;
     689        gap: var(--chathearth-space-3);
     690        margin-block: var(--chathearth-space-4);
     691        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     692        border: 1px solid var(--chathearth-info);
     693        border-inline-start-width: 4px;
     694        border-radius: var(--chathearth-radius-control);
     695        background: var(--chathearth-info-bg);
     696        color: var(--chathearth-text);
     697        font-size: 12px;
     698}
     699
     700.chathearth-settings .chathearth-callout .chathearth-icon {
     701        color: var(--chathearth-accent);
     702}
     703
     704/* Starter Suggestion Chips */
     705.chathearth-settings .chathearth-chips {
     706        display: flex;
     707        flex-wrap: wrap;
     708        gap: var(--chathearth-space-2);
     709        margin: var(--chathearth-space-2) 0 0;
     710        padding: 0;
     711        list-style: none;
     712}
     713
     714.chathearth-settings .chathearth-chip {
     715        padding-block: 3px;
     716        padding-inline: 10px;
     717        border: 1px solid var(--chathearth-border);
     718        border-radius: 9999px;
     719        background: var(--chathearth-surface-alt);
     720        color: var(--chathearth-text);
     721        font-size: 12px;
     722}
     723
     724/* Stat Tiles */
     725.chathearth-settings .chathearth-stats {
     726        display: grid;
     727        grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
     728        gap: var(--chathearth-space-3);
     729        margin-block-end: var(--chathearth-space-4);
     730}
     731
     732.chathearth-settings .chathearth-stat {
     733        padding: var(--chathearth-space-3);
     734        border: 1px solid var(--chathearth-border);
     735        border-radius: var(--chathearth-radius-control);
     736        background: var(--chathearth-surface-alt);
     737        text-align: center;
     738}
     739
     740.chathearth-settings .chathearth-stat__value {
     741        display: block;
     742        font-size: 20px;
     743        font-weight: 600;
     744        line-height: 1.2;
     745}
     746
     747.chathearth-settings .chathearth-stat__label {
     748        display: block;
     749        margin-block-start: 2px;
     750        color: var(--chathearth-text-muted);
     751        font-size: 11px;
     752}
     753
     754/* Progress Bar */
     755.chathearth-settings .chathearth-progress {
     756        inline-size: 100%;
     757        block-size: 8px;
     758        overflow: hidden;
     759        border-radius: 4px;
     760        background: var(--chathearth-border);
     761}
     762
     763.chathearth-settings .chathearth-progress__bar {
     764        block-size: 100%;
     765        background: var(--chathearth-accent);
     766        transition: inline-size 300ms ease;
     767}
     768
     769/* Empty State */
     770.chathearth-settings .chathearth-empty {
     771        padding-block: var(--chathearth-space-6);
     772        padding-inline: var(--chathearth-space-4);
     773        text-align: center;
     774}
     775
     776.chathearth-settings .chathearth-empty .chathearth-icon {
     777        inline-size: 40px;
     778        block-size: 40px;
     779        margin-block-end: var(--chathearth-space-3);
     780        color: var(--chathearth-text-muted);
     781}
     782
     783/* Toast Messages */
     784.chathearth-toasts {
     785        position: fixed;
     786        inset-block-end: 64px;
     787        inset-inline-end: 24px;
     788        z-index: 100;
     789        display: flex;
     790        flex-direction: column-reverse;
     791        gap: var(--chathearth-space-2);
     792        pointer-events: none;
     793}
     794
     795.chathearth-toast {
     796        display: flex;
     797        align-items: center;
     798        justify-content: space-between;
     799        gap: var(--chathearth-space-3);
     800        min-inline-size: 260px;
     801        max-inline-size: 380px;
     802        padding: 10px 14px;
     803        border-radius: var(--chathearth-radius-control);
     804        background: #1d2327;
     805        color: #fff;
     806        font-size: 13px;
     807        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
     808        pointer-events: auto;
     809        animation: chathearth-toast-in var(--chathearth-motion);
     810}
     811
     812@keyframes chathearth-toast-in {
     813
     814        from {
     815                opacity: 0;
     816                transform: translateY(8px);
     817        }
     818
     819        to {
     820                opacity: 1;
     821                transform: translateY(0);
     822        }
     823}
     824
     825.chathearth-toast__close {
     826        display: grid;
     827        place-items: center;
     828        padding: 0;
     829        border: 0;
     830        background: none;
     831        color: #c3c4c7;
     832        cursor: pointer;
     833}
     834
     835.chathearth-toast__close:hover {
     836        color: #fff;
     837}
     838
     839/* Native Dialog */
     840.chathearth-dialog {
     841        max-inline-size: 420px;
     842        padding: var(--chathearth-space-5);
     843        border: 0;
     844        border-radius: var(--chathearth-radius-card);
     845        background: var(--chathearth-surface);
     846        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
     847}
     848
     849.chathearth-dialog::backdrop {
     850        background: rgba(0, 0, 0, 0.4);
     851        backdrop-filter: blur(2px);
     852}
     853
     854.chathearth-dialog h2 {
     855        margin-block-start: 0;
     856        margin-block-end: var(--chathearth-space-2);
     857        font-size: 17px;
     858}
     859
     860.chathearth-dialog p {
     861        margin-block-start: 0;
     862        margin-block-end: var(--chathearth-space-5);
     863        color: var(--chathearth-text-muted);
     864        font-size: 13px;
     865}
     866
     867.chathearth-dialog__actions {
     868        display: flex;
     869        justify-content: flex-end;
     870        gap: var(--chathearth-space-3);
     871}
     872
     873.chathearth-button--danger {
     874        border-color: var(--chathearth-error) !important;
     875        background: var(--chathearth-error) !important;
     876        color: #fff !important;
     877}
     878
     879.chathearth-button--danger:hover {
     880        border-color: #b32d2e !important;
     881        background: #b32d2e !important;
     882}
     883
     884/* Disclosure (Built-in rules) */
     885.chathearth-disclosure {
     886        margin-block-start: var(--chathearth-space-4);
     887        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     888        border: 1px solid var(--chathearth-border);
     889        border-radius: var(--chathearth-radius-control);
     890        background: var(--chathearth-surface-alt);
     891}
     892
     893.chathearth-disclosure summary {
     894        color: var(--chathearth-accent);
     895        font-size: 13px;
     896        font-weight: 500;
     897        cursor: pointer;
     898        user-select: none;
     899}
     900
     901.chathearth-disclosure ol {
     902        margin-block: var(--chathearth-space-3) 0;
     903        margin-inline: 0;
     904        padding-inline-start: 20px;
     905        color: var(--chathearth-text);
     906        font-size: 12px;
     907        line-height: 1.6;
     908}
     909
     910/* 7. Protection sub-tabs and rate-limit groups
     911   ========================================================================== */
     912
     913.chathearth-subtabs {
     914        margin-block-end: var(--chathearth-space-4);
     915}
     916
     917.chathearth-settings .chathearth-subtabs > [role="tablist"] {
     918        display: flex;
     919        flex-wrap: wrap;
     920        gap: var(--chathearth-space-2);
     921}
     922
     923.chathearth-subtabs__tab {
     924        display: inline-flex;
     925        align-items: center;
     926        line-height: 1.4;
     927        padding-block: 6px;
     928        padding-inline: 12px;
     929        border: 1px solid var(--chathearth-border);
     930        border-radius: 9999px;
     931        background: var(--chathearth-surface);
     932        color: var(--chathearth-text);
     933        font-size: 12px;
     934        font-weight: 500;
     935        text-decoration: none;
     936        cursor: pointer;
     937        user-select: none;
     938        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     939}
     940
     941.chathearth-subtabs__tab:hover {
     942        border-color: var(--chathearth-accent);
     943        color: var(--chathearth-accent);
     944}
     945
     946.chathearth-subtabs__tab.is-active {
     947        border-color: var(--chathearth-accent);
     948        background: var(--chathearth-accent);
     949        color: #fff;
     950        font-weight: 600;
     951}
     952
     953.chathearth-subgroup-title {
     954        margin-block: var(--chathearth-space-4) var(--chathearth-space-2);
     955        color: var(--chathearth-text);
     956        font-size: 13px;
     957        font-weight: 600;
     958}
     959
     960/* Allowances Table */
     961.chathearth-allowances {
     962        inline-size: 100%;
     963        max-inline-size: 440px;
     964        border-collapse: collapse;
     965}
     966
     967.chathearth-allowances th,
     968.chathearth-allowances td {
     969        padding-block: 6px;
     970        padding-inline: 8px;
     971        border-block-end: 1px solid var(--chathearth-border);
     972}
     973
     974.chathearth-allowances th {
     975        text-align: start;
     976        font-weight: 400;
     977}
     978
     979.chathearth-allowances td {
     980        text-align: end;
     981}
     982
     983/* 8. Appearance: live preview, launcher, product cards
     984   ========================================================================== */
     985
     986.chathearth-settings .chathearth-appearance {
     987        display: grid;
     988        grid-template-columns: minmax(0, 1fr);
     989        gap: var(--chathearth-space-5);
     990        align-items: start;
     991}
     992
     993.chathearth-settings .chathearth-appearance__reset {
     994        margin-block-end: var(--chathearth-space-4);
     995}
     996
     997@media (min-width: 1100px) {
     998
     999        .chathearth-settings .chathearth-appearance {
     1000                grid-template-columns: minmax(0, 1fr) 360px;
     1001        }
     1002}
     1003
     1004/* Live widget preview aside */
     1005.chathearth-settings .chathearth-preview {
     1006        --chathearth-icon-bg: #0f172a;
     1007        --chathearth-icon-border: #1e293b;
     1008        --chathearth-icon-color: #fff;
     1009        --chathearth-icon-size: 56px;
     1010        --chathearth-user-bubble: #0f172a;
     1011        --chathearth-user-text: #fff;
     1012        --chathearth-assistant-bubble: #e2e8f0;
     1013        --chathearth-assistant-text: #1d2327;
     1014        --chathearth-product-card-bg: #fff;
     1015        --chathearth-product-card-border: #dcdcde;
     1016        --chathearth-product-card-text: #1d2327;
     1017        --chathearth-product-button-bg: #0f172a;
     1018        --chathearth-product-button-text: #fff;
     1019        --chathearth-product-button-radius: 2px;
     1020        --chathearth-product-card-radius: 4px;
     1021        --chathearth-product-card-width: 140px;
     1022
     1023        position: sticky;
     1024        inset-block-start: var(--chathearth-sticky-top);
     1025        display: flex;
     1026        flex-direction: column;
     1027        min-inline-size: 0;
     1028        max-block-size: calc(100vh - 120px);
     1029        padding: var(--chathearth-space-4);
     1030        border: 1px solid var(--chathearth-border);
     1031        border-radius: var(--chathearth-radius-card);
     1032        background: #e7eaed;
     1033}
     1034
     1035.chathearth-settings .chathearth-preview__caption {
     1036        display: flex;
     1037        justify-content: space-between;
     1038        gap: var(--chathearth-space-2);
     1039        color: var(--chathearth-text-muted);
     1040        font-size: 11px;
     1041        font-weight: 600;
     1042        text-transform: uppercase;
     1043        letter-spacing: 0.5px;
     1044}
     1045
     1046.chathearth-settings .chathearth-preview__window {
     1047        display: flex;
     1048        flex: 1 1 auto;
     1049        flex-direction: column;
     1050        min-block-size: 0;
     1051        margin-block-start: var(--chathearth-space-3);
     1052        overflow: hidden;
     1053        border-radius: 10px;
     1054        background: var(--chathearth-surface);
     1055        box-shadow: 0 8px 24px rgba(29, 35, 39, 0.12);
     1056}
     1057
     1058.chathearth-settings .chathearth-preview__header {
     1059        flex: none;
     1060        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     1061        background: var(--chathearth-icon-bg);
     1062        color: var(--chathearth-icon-color);
     1063        font-weight: 600;
     1064        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     1065}
     1066
     1067.chathearth-settings .chathearth-preview__conversation {
     1068        display: flex;
     1069        flex: 1 1 auto;
     1070        flex-direction: column;
     1071        gap: var(--chathearth-space-3);
     1072        min-block-size: 0;
     1073        padding: var(--chathearth-space-4);
     1074        overflow-y: auto;
     1075        overscroll-behavior: contain;
     1076}
     1077
     1078.chathearth-settings .chathearth-preview[data-size="small"] .chathearth-preview__conversation {
     1079        min-block-size: 200px;
     1080}
     1081
     1082.chathearth-settings .chathearth-preview[data-size="medium"] .chathearth-preview__conversation {
     1083        min-block-size: 260px;
     1084}
     1085
     1086.chathearth-settings .chathearth-preview[data-size="large"] .chathearth-preview__conversation {
     1087        min-block-size: 340px;
     1088}
     1089
     1090.chathearth-settings .chathearth-preview__bubble {
     1091        max-inline-size: 90%;
     1092        margin: 0;
     1093        padding: 9px 13px;
     1094        border-radius: 12px;
     1095        background: var(--chathearth-assistant-bubble);
     1096        color: var(--chathearth-assistant-text);
     1097        font-size: 13px;
     1098        line-height: 1.4;
     1099        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     1100}
     1101
     1102.chathearth-settings .chathearth-preview__bubble--user {
     1103        align-self: flex-end;
     1104        background: var(--chathearth-user-bubble);
     1105        color: var(--chathearth-user-text);
     1106}
     1107
     1108.chathearth-settings .chathearth-preview__sources {
     1109        display: flex;
     1110        align-items: center;
     1111        gap: var(--chathearth-space-2);
     1112        margin-block-end: var(--chathearth-space-2);
     1113        color: var(--chathearth-text-muted);
     1114        font-size: 11px;
     1115}
     1116
     1117.chathearth-settings .chathearth-product-list {
     1118        display: flex;
     1119        gap: var(--chathearth-space-3);
     1120        overflow-x: auto;
     1121        padding-block-end: 6px;
     1122}
     1123
     1124.chathearth-settings .chathearth-product {
     1125        flex: none;
     1126        display: flex;
     1127        flex-direction: column;
     1128        inline-size: var(--chathearth-product-card-width);
     1129        border: 1px solid var(--chathearth-product-card-border);
     1130        border-radius: var(--chathearth-product-card-radius);
     1131        background: var(--chathearth-product-card-bg);
     1132        color: var(--chathearth-product-card-text);
     1133        overflow: hidden;
     1134        font-size: 12px;
     1135}
     1136
     1137.chathearth-settings .chathearth-product__image {
     1138        inline-size: 100%;
     1139        block-size: auto;
     1140        display: block;
     1141}
     1142
     1143.chathearth-settings .chathearth-product__details {
     1144        display: flex;
     1145        flex-direction: column;
     1146        gap: 4px;
     1147        padding: 8px;
     1148}
     1149
     1150.chathearth-settings .chathearth-product__button {
     1151        margin-block-start: 4px;
     1152        padding-block: 4px;
     1153        padding-inline: 8px;
     1154        border: 0;
     1155        border-radius: var(--chathearth-product-button-radius);
     1156        background: var(--chathearth-product-button-bg);
     1157        color: var(--chathearth-product-button-text);
     1158        font-size: 11px;
     1159        font-weight: 500;
     1160        cursor: pointer;
     1161}
     1162
     1163.chathearth-settings .chathearth-product-compare {
     1164        margin-block-start: var(--chathearth-space-2);
     1165        font-size: 11px;
     1166}
     1167
     1168.chathearth-settings .chathearth-preview__input {
     1169        flex: none;
     1170        display: flex;
     1171        justify-content: space-between;
     1172        align-items: center;
     1173        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     1174        border-block-start: 1px solid var(--chathearth-page);
     1175        color: var(--chathearth-text-muted);
     1176        font-size: 12px;
     1177}
     1178
     1179.chathearth-settings .chathearth-preview__input-icon {
     1180        inline-size: 16px;
     1181        block-size: 16px;
     1182        color: var(--chathearth-text-muted);
     1183}
     1184
     1185/* The dock forces LTR so "Bottom right" always means physical right corner */
     1186.chathearth-settings .chathearth-preview__dock {
     1187        display: flex;
     1188        flex: none;
     1189        direction: ltr;
     1190        justify-content: flex-end;
     1191        margin-block-start: var(--chathearth-space-4);
     1192}
     1193
     1194.chathearth-settings .chathearth-preview[data-position="bottom-left"] .chathearth-preview__dock {
     1195        justify-content: flex-start;
     1196}
     1197
     1198.chathearth-settings .chathearth-preview[data-position="bottom-center"] .chathearth-preview__dock {
     1199        justify-content: center;
     1200}
     1201
     1202.chathearth-settings .chathearth-preview__launcher {
     1203        position: relative;
     1204        isolation: isolate;
     1205        display: grid;
     1206        place-items: center;
     1207        inline-size: var(--chathearth-icon-size);
     1208        block-size: var(--chathearth-icon-size);
     1209        max-inline-size: 100%;
     1210        margin: 0;
     1211        padding: 0;
     1212        border: 1px solid var(--chathearth-icon-border);
     1213        border-radius: 50%;
     1214        background: var(--chathearth-icon-bg);
     1215        color: var(--chathearth-icon-color);
     1216        font: inherit;
     1217        cursor: pointer;
     1218        transition: transform var(--chathearth-motion);
     1219}
     1220
     1221[dir="rtl"] .chathearth-settings .chathearth-preview__launcher {
     1222        direction: rtl;
     1223}
     1224
     1225.chathearth-settings .chathearth-preview[data-shape="square"] .chathearth-preview__launcher {
     1226        border-radius: 8px;
     1227}
     1228
     1229.chathearth-settings .chathearth-preview__launcher-inner {
     1230        position: relative;
     1231        z-index: 2;
     1232        display: flex;
     1233        align-items: center;
     1234        justify-content: center;
     1235        min-inline-size: 0;
     1236}
     1237
     1238.chathearth-settings .chathearth-preview__launcher-icon {
     1239        display: grid;
     1240        flex: none;
     1241        place-items: center;
     1242        line-height: 0;
     1243}
     1244
     1245.chathearth-settings .chathearth-preview__launcher-sparkle {
     1246        inline-size: 24px;
     1247        block-size: 24px;
     1248        fill: currentcolor;
     1249}
     1250
     1251.chathearth-settings .chathearth-preview__beam-track,
     1252.chathearth-settings .chathearth-preview__launcher-label {
     1253        display: none;
     1254}
     1255
     1256/* Pill Launcher ("Icon and text") */
     1257.chathearth-settings .chathearth-preview__launcher[data-style="pill"] {
     1258        display: block;
     1259        inline-size: auto;
     1260        block-size: auto;
     1261        border: 2px solid rgba(36, 36, 36, 0.2);
     1262        border-radius: 9999px;
     1263        background: transparent;
     1264        box-shadow: 0 2px 20px rgba(0, 0, 0, 0.25), 0 0 1px rgba(0, 0, 0, 0.25);
     1265        color: #242424;
     1266}
     1267
     1268.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-inner {
     1269        flex-direction: row-reverse;
     1270        gap: var(--chathearth-space-4);
     1271        max-inline-size: 100%;
     1272        padding: var(--chathearth-space-2);
     1273        border-radius: 9999px;
     1274        background: #fff;
     1275}
     1276
     1277[dir="rtl"] .chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-inner {
     1278        flex-direction: row;
     1279}
     1280
     1281.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-icon {
     1282        inline-size: calc(var(--chathearth-icon-size) - 12px);
     1283        block-size: calc(var(--chathearth-icon-size) - 12px);
     1284        border-radius: 50%;
     1285        background-color: var(--chathearth-icon-bg);
     1286        background-image: linear-gradient(135deg, color-mix(in srgb, var(--chathearth-icon-bg) 60%, #3d4555), var(--chathearth-icon-bg) 30%, color-mix(in srgb, var(--chathearth-icon-bg) 70%, #fff) 50%, var(--chathearth-icon-bg) 70%, color-mix(in srgb, var(--chathearth-icon-bg) 60%, #3d4555));
     1287        background-position: 0% 50%;
     1288        background-size: 400% 400%;
     1289        color: var(--chathearth-icon-color);
     1290}
     1291
     1292.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-label {
     1293        display: grid;
     1294        grid-template-columns: 1fr;
     1295        min-inline-size: 0;
     1296        overflow: hidden;
     1297}
     1298
     1299.chathearth-settings .chathearth-preview__launcher-text {
     1300        min-inline-size: 0;
     1301        padding-block-end: 2px;
     1302        padding-inline-end: var(--chathearth-space-2);
     1303        overflow: hidden;
     1304        color: #242424;
     1305        font-size: 15px;
     1306        font-weight: 500;
     1307        line-height: 22px;
     1308        text-overflow: ellipsis;
     1309        white-space: nowrap;
     1310}
     1311
     1312.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__beam-track {
     1313        position: absolute;
     1314        inset: -3px;
     1315        z-index: 1;
     1316        display: block;
     1317        overflow: hidden;
     1318        border-radius: 9999px;
     1319        pointer-events: none;
     1320}
     1321
     1322.chathearth-settings .chathearth-preview__beam {
     1323        position: absolute;
     1324        inset-block-start: 0;
     1325        inset-inline-start: 0;
     1326        inline-size: 80px;
     1327        block-size: 80px;
     1328        background: radial-gradient(closest-side, #242424, transparent);
     1329        offset-anchor: center center;
     1330        offset-path: inset(0 round 9999px);
     1331        offset-rotate: 0deg;
     1332        opacity: 0;
     1333}
     1334
     1335/* Pill launcher animations */
     1336.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-entering {
     1337        animation: chathearth-pill-enter 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) both;
     1338}
     1339
     1340.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-entering .chathearth-preview__launcher-label {
     1341        animation: chathearth-pill-label-enter 0.3s ease-out both;
     1342}
     1343
     1344.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__launcher-icon {
     1345        animation: chathearth-pill-gradient 8s forwards;
     1346}
     1347
     1348.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__launcher-sparkle {
     1349        animation: chathearth-pill-sparkle 12s ease-in-out forwards;
     1350}
     1351
     1352.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__beam {
     1353        animation: chathearth-pill-beam 4s linear forwards;
     1354}
     1355
     1356@supports ((background-clip: text) or (-webkit-background-clip: text)) {
     1357
     1358        .chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__launcher-text {
     1359                background: linear-gradient(90deg, #242424 0%, #242424 30%, #707070 45%, #bdbdbd 50%, #707070 55%, #242424 70%, #242424 100%);
     1360                background-size: 300% 100%;
     1361                -webkit-background-clip: text;
     1362                background-clip: text;
     1363                color: transparent;
     1364                animation: chathearth-pill-shimmer 2s ease-in-out forwards;
     1365        }
     1366}
     1367
     1368@keyframes chathearth-pill-enter {
     1369
     1370        from {
     1371                opacity: 0;
     1372                transform: scale(0.625);
     1373        }
     1374
     1375        to {
     1376                opacity: 1;
     1377                transform: scale(1);
     1378        }
     1379}
     1380
     1381@keyframes chathearth-pill-label-enter {
     1382
     1383        from {
     1384                opacity: 0;
     1385                transform: scaleX(0.8);
     1386        }
     1387
     1388        to {
     1389                opacity: 1;
     1390                transform: scaleX(1);
     1391        }
     1392}
     1393
     1394@keyframes chathearth-pill-beam {
     1395
     1396        0% {
     1397                offset-distance: 0%;
     1398                opacity: 1;
     1399        }
     1400
     1401        100% {
     1402                offset-distance: 100%;
     1403                opacity: 1;
     1404        }
     1405}
     1406
     1407@keyframes chathearth-pill-gradient {
     1408
     1409        0% {
     1410                background-position: 0% 50%;
     1411        }
     1412
     1413        50% {
     1414                background-position: 100% 50%;
     1415        }
     1416
     1417        100% {
     1418                background-position: 0% 50%;
     1419        }
     1420}
     1421
     1422@keyframes chathearth-pill-sparkle {
     1423
     1424        0%,
     1425        100% {
     1426                transform: scale(1) rotate(0deg);
     1427        }
     1428
     1429        15% {
     1430                transform: scale(1.15) rotate(12deg);
     1431        }
     1432
     1433        30% {
     1434                transform: scale(0.95) rotate(-8deg);
     1435        }
     1436
     1437        45% {
     1438                transform: scale(1.08) rotate(4deg);
     1439        }
     1440
     1441        60% {
     1442                transform: scale(1) rotate(0deg);
     1443        }
     1444}
     1445
     1446@keyframes chathearth-pill-shimmer {
     1447
     1448        0% {
     1449                background-position: 100% 0%;
     1450        }
     1451
     1452        100% {
     1453                background-position: -100% 0%;
     1454        }
     1455}
     1456
     1457/* Contrast notice */
     1458.chathearth-contrast {
     1459        margin-block: 4px 0;
     1460        margin-inline: 0;
     1461        color: var(--chathearth-warning-text);
     1462        font-size: 12px;
     1463        font-weight: 500;
     1464}
     1465
     1466/* 9. Knowledge Base index
     1467   ========================================================================== */
    381468
    391469.chathearth-settings .chathearth-kb-toolbar {
    401470        display: flex;
    41         align-items: center;
    42         gap: 8px;
    43         margin: 12px 0;
    44 }
    45 
    46 .chathearth-settings .chathearth-kb-status {
    47         font-style: italic;
    48 }
    49 
    50 .chathearth-settings .chathearth-kb-entries-wrap {
    51         margin-top: 16px;
    52 }
    53 
    54 .chathearth-settings .chathearth-kb-pager {
    55         margin-top: 8px;
    56 }
     1471        flex-wrap: wrap;
     1472        align-items: center;
     1473        justify-content: space-between;
     1474        gap: var(--chathearth-space-3);
     1475        margin-block-end: var(--chathearth-space-4);
     1476}
     1477
     1478.chathearth-settings .chathearth-kb-filters {
     1479        display: flex;
     1480        flex-wrap: wrap;
     1481        align-items: center;
     1482        gap: var(--chathearth-space-2);
     1483}
     1484
     1485.chathearth-settings .chathearth-table-wrap {
     1486        overflow-x: auto;
     1487        border: 1px solid var(--chathearth-border);
     1488        border-radius: var(--chathearth-radius-control);
     1489}
     1490
     1491.chathearth-settings .chathearth-table {
     1492        inline-size: 100%;
     1493        border-collapse: collapse;
     1494        text-align: start;
     1495}
     1496
     1497.chathearth-settings .chathearth-table th,
     1498.chathearth-settings .chathearth-table td {
     1499        padding: 10px 12px;
     1500        border-block-end: 1px solid var(--chathearth-border);
     1501        vertical-align: middle;
     1502}
     1503
     1504.chathearth-settings .chathearth-table th {
     1505        background: var(--chathearth-surface-alt);
     1506        color: var(--chathearth-text-muted);
     1507        font-size: 12px;
     1508        font-weight: 600;
     1509}
     1510
     1511.chathearth-settings .chathearth-table tbody tr:last-child td {
     1512        border-block-end: 0;
     1513}
     1514
     1515.chathearth-settings .chathearth-table tbody tr:hover {
     1516        background: #fbfbfc;
     1517}
     1518
     1519.chathearth-settings .chathearth-table__error {
     1520        display: flex;
     1521        align-items: center;
     1522        gap: 6px;
     1523        margin-block: 4px 0;
     1524        margin-inline: 0;
     1525        color: var(--chathearth-error-text);
     1526        font-size: 12px;
     1527}
     1528
     1529.chathearth-settings .chathearth-table__error .chathearth-icon {
     1530        inline-size: 14px;
     1531        block-size: 14px;
     1532}
     1533
     1534.chathearth-settings .chathearth-kb-pagination {
     1535        display: flex;
     1536        align-items: center;
     1537        justify-content: flex-end;
     1538        gap: var(--chathearth-space-3);
     1539        margin-block-start: var(--chathearth-space-4);
     1540        font-size: 12px;
     1541        color: var(--chathearth-text-muted);
     1542}
     1543
     1544/* Index card: actions, busy buttons, sync progress, notices (feature 012) */
     1545
     1546.chathearth-settings .chathearth-card__actions {
     1547        display: flex;
     1548        flex-wrap: wrap;
     1549        gap: var(--chathearth-space-2);
     1550}
     1551
     1552.chathearth-settings .chathearth-card__actions .button,
     1553.chathearth-settings #chathearth-kb-empty .button {
     1554        display: inline-flex;
     1555        align-items: center;
     1556        gap: var(--chathearth-space-2);
     1557}
     1558
     1559.chathearth-settings .button .spinner {
     1560        display: none;
     1561        float: none;
     1562        margin: 0;
     1563}
     1564
     1565.chathearth-settings .button .spinner.is-active {
     1566        display: inline-block;
     1567        visibility: visible;
     1568}
     1569
     1570.chathearth-settings .button.is-busy {
     1571        cursor: progress;
     1572}
     1573
     1574.chathearth-settings #chathearth-sync-progress {
     1575        margin-block-end: var(--chathearth-space-4);
     1576}
     1577
     1578.chathearth-settings .chathearth-progress__text {
     1579        display: flex;
     1580        flex-wrap: wrap;
     1581        justify-content: space-between;
     1582        gap: var(--chathearth-space-2);
     1583        margin-block: var(--chathearth-space-1) 0;
     1584}
     1585
     1586.chathearth-settings .chathearth-progress.is-indeterminate {
     1587        position: relative;
     1588}
     1589
     1590.chathearth-settings .is-indeterminate .chathearth-progress__bar {
     1591        position: absolute;
     1592        inset-block: 0;
     1593        inset-inline-start: 0;
     1594        inline-size: 35%;
     1595        animation: chathearth-progress-sweep 1.4s ease-in-out infinite;
     1596}
     1597
     1598/* Reduced motion: the global rule stops the sweep after one pass. */
     1599@keyframes chathearth-progress-sweep {
     1600
     1601        from {
     1602                inset-inline-start: -35%;
     1603        }
     1604
     1605        to {
     1606                inset-inline-start: 100%;
     1607        }
     1608}
     1609
     1610.chathearth-settings #chathearth-kb-notice,
     1611.chathearth-settings #chathearth-kb-alert {
     1612        display: flex;
     1613        flex-wrap: wrap;
     1614        align-items: center;
     1615        gap: var(--chathearth-space-3);
     1616        margin-block: 0 var(--chathearth-space-4);
     1617        margin-inline: 0;
     1618}
     1619
     1620.chathearth-settings #chathearth-kb-notice p,
     1621.chathearth-settings #chathearth-kb-alert p {
     1622        margin: 0;
     1623}
     1624
     1625.chathearth-settings #chathearth-kb-sync-hint {
     1626        margin-block: 0 var(--chathearth-space-3);
     1627}
     1628
     1629/* Index card: list rows, the Included switch, narrow screens (feature 012) */
     1630
     1631.chathearth-settings .chathearth-table__title {
     1632        max-inline-size: 360px;
     1633        overflow: hidden;
     1634        text-overflow: ellipsis;
     1635        white-space: nowrap;
     1636}
     1637
     1638.chathearth-settings .chathearth-table__col-type,
     1639.chathearth-settings .chathearth-table__col-status,
     1640.chathearth-settings .chathearth-table__col-updated {
     1641        inline-size: 130px;
     1642}
     1643
     1644.chathearth-settings .chathearth-table__col-included {
     1645        inline-size: 90px;
     1646}
     1647
     1648.chathearth-settings .chathearth-table td .chathearth-table__error {
     1649        max-inline-size: 260px;
     1650        white-space: normal;
     1651}
     1652
     1653.chathearth-settings .chathearth-switch-button {
     1654        position: relative;
     1655        display: inline-block;
     1656        flex: none;
     1657        inline-size: 36px;
     1658        min-inline-size: 36px;
     1659        block-size: 20px;
     1660        margin: 0;
     1661        padding: 0;
     1662        border: 0;
     1663        border-radius: 10px;
     1664        background: var(--chathearth-control-border);
     1665        cursor: pointer;
     1666        transition: background-color var(--chathearth-motion);
     1667}
     1668
     1669.chathearth-settings .chathearth-switch-button::before {
     1670        content: "";
     1671        position: absolute;
     1672        inset-block-start: 2px;
     1673        inset-inline-start: 2px;
     1674        inline-size: 16px;
     1675        block-size: 16px;
     1676        border-radius: 50%;
     1677        background: #fff;
     1678        transition: inset-inline-start var(--chathearth-motion);
     1679}
     1680
     1681.chathearth-settings .chathearth-switch-button[aria-checked="true"] {
     1682        background: var(--chathearth-accent);
     1683}
     1684
     1685.chathearth-settings .chathearth-switch-button[aria-checked="true"]::before {
     1686        inset-inline-start: 18px;
     1687}
     1688
     1689.chathearth-settings .chathearth-switch-button:disabled {
     1690        opacity: 0.5;
     1691        cursor: progress;
     1692}
     1693
     1694.chathearth-settings #chathearth-kb-nomatch {
     1695        padding-block: var(--chathearth-space-5);
     1696}
     1697
     1698.chathearth-settings .chathearth-kb-pagination .button[disabled] {
     1699        cursor: not-allowed;
     1700}
     1701
     1702@media (max-width: 782px) {
     1703
     1704        .chathearth-settings .chathearth-table {
     1705                min-inline-size: 640px;
     1706        }
     1707
     1708        .chathearth-settings .chathearth-kb-toolbar,
     1709        .chathearth-settings .chathearth-kb-filters {
     1710                inline-size: 100%;
     1711        }
     1712
     1713        .chathearth-settings #chathearth-kb-search {
     1714                inline-size: 100%;
     1715                max-inline-size: none;
     1716        }
     1717}
     1718
     1719/* 10. Advanced: system status
     1720   ========================================================================== */
     1721
     1722.chathearth-settings .chathearth-status-list {
     1723        display: flex;
     1724        flex-direction: column;
     1725        gap: 0;
     1726        border: 1px solid var(--chathearth-border);
     1727        border-radius: var(--chathearth-radius-control);
     1728        overflow: hidden;
     1729        margin-block-end: var(--chathearth-space-4);
     1730}
     1731
     1732.chathearth-settings .chathearth-status {
     1733        display: flex;
     1734        flex-wrap: wrap;
     1735        align-items: center;
     1736        justify-content: space-between;
     1737        gap: var(--chathearth-space-3);
     1738        padding: 10px 14px;
     1739        border-block-end: 1px solid var(--chathearth-border);
     1740        background: var(--chathearth-surface);
     1741}
     1742
     1743.chathearth-settings .chathearth-status:last-child {
     1744        border-block-end: 0;
     1745}
     1746
     1747.chathearth-settings .chathearth-status__meta {
     1748        display: flex;
     1749        align-items: center;
     1750        gap: var(--chathearth-space-3);
     1751}
     1752
     1753.chathearth-settings .chathearth-status__label {
     1754        font-weight: 500;
     1755}
     1756
     1757.chathearth-settings .chathearth-status__result {
     1758        display: flex;
     1759        align-items: center;
     1760        gap: var(--chathearth-space-3);
     1761}
     1762
     1763.chathearth-settings .chathearth-status__fix {
     1764        font-size: 12px;
     1765}
     1766
     1767/* 11. Sticky save bar
     1768   ========================================================================== */
     1769
     1770.chathearth-settings .chathearth-savebar {
     1771        position: sticky;
     1772        inset-block-end: 0;
     1773        z-index: 30;
     1774        display: flex;
     1775        flex-wrap: wrap;
     1776        align-items: center;
     1777        justify-content: space-between;
     1778        gap: var(--chathearth-space-3);
     1779        margin-block-start: var(--chathearth-space-6);
     1780        padding: var(--chathearth-space-4) var(--chathearth-space-5);
     1781        border: 1px solid var(--chathearth-border);
     1782        border-radius: var(--chathearth-radius-card);
     1783        background: var(--chathearth-surface);
     1784        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
     1785}
     1786
     1787.chathearth-settings .chathearth-savebar__status {
     1788        display: flex;
     1789        align-items: center;
     1790        gap: var(--chathearth-space-2);
     1791        color: var(--chathearth-text-muted);
     1792        font-size: 13px;
     1793}
     1794
     1795.chathearth-settings #chathearth-dirty {
     1796        color: var(--chathearth-warning-text);
     1797        font-weight: 600;
     1798}
     1799
     1800.chathearth-settings #chathearth-dirty::before {
     1801        content: "";
     1802        display: inline-block;
     1803        inline-size: 8px;
     1804        block-size: 8px;
     1805        margin-inline-end: 6px;
     1806        border-radius: 50%;
     1807        background: var(--chathearth-warning);
     1808}
     1809
     1810.chathearth-settings .chathearth-savebar__actions {
     1811        display: flex;
     1812        align-items: center;
     1813        gap: var(--chathearth-space-3);
     1814}
     1815
     1816/* 12. Responsive breakpoints
     1817   ========================================================================== */
     1818
     1819@media (max-width: 782px) {
     1820
     1821        .chathearth-settings .chathearth-layout {
     1822                grid-template-columns: minmax(0, 1fr);
     1823        }
     1824
     1825        .chathearth-settings .chathearth-tabs {
     1826                position: static;
     1827                overflow-x: auto;
     1828                padding-block-end: 6px;
     1829        }
     1830
     1831        .chathearth-settings .chathearth-tabs [role="tablist"] {
     1832                flex-direction: row;
     1833                inline-size: max-content;
     1834        }
     1835
     1836        .chathearth-settings .chathearth-field {
     1837                flex-direction: column;
     1838                align-items: stretch;
     1839                gap: var(--chathearth-space-2);
     1840        }
     1841
     1842        .chathearth-settings .chathearth-field__label {
     1843                flex: none;
     1844                inline-size: auto;
     1845                max-inline-size: none;
     1846                padding-block-start: 0;
     1847        }
     1848
     1849        .chathearth-settings fieldset.chathearth-field > legend.chathearth-field__label {
     1850                float: none;
     1851                inline-size: auto;
     1852                max-inline-size: none;
     1853                padding-block-start: 0;
     1854                margin-block-end: var(--chathearth-space-2);
     1855        }
     1856
     1857        .chathearth-settings fieldset.chathearth-field > .chathearth-field__control {
     1858                margin-inline-start: 0;
     1859        }
     1860
     1861        .chathearth-settings .chathearth-savebar {
     1862                position: fixed;
     1863                inset-block-end: 0;
     1864                inset-inline: 0;
     1865                margin: 0;
     1866                border-radius: 0;
     1867                border-inline: 0;
     1868                border-block-end: 0;
     1869                box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
     1870        }
     1871}
     1872
     1873@media (max-width: 480px) {
     1874
     1875        .chathearth-settings .chathearth-header {
     1876                flex-direction: column;
     1877                align-items: flex-start;
     1878        }
     1879
     1880        .chathearth-settings .chathearth-savebar {
     1881                flex-direction: column;
     1882                align-items: stretch;
     1883                text-align: center;
     1884        }
     1885
     1886        .chathearth-settings .chathearth-savebar__actions {
     1887                justify-content: flex-end;
     1888        }
     1889}
     1890
     1891/* 13. Reduced motion
     1892   ========================================================================== */
     1893
     1894@media (prefers-reduced-motion: reduce) {
     1895
     1896        .chathearth-settings *,
     1897        .chathearth-settings *::before,
     1898        .chathearth-settings *::after {
     1899                animation-duration: 0.01ms !important;
     1900                animation-iteration-count: 1 !important;
     1901                transition-duration: 0.01ms !important;
     1902        }
     1903}
     1904
     1905/* Connection card */
     1906.chathearth-settings .chathearth-connection {
     1907        display: flex;
     1908        flex-wrap: wrap;
     1909        align-items: center;
     1910        gap: var(--chathearth-space-4);
     1911        padding-block: var(--chathearth-space-2);
     1912}
     1913
     1914.chathearth-settings .chathearth-connection > div {
     1915        flex: 1 1 260px;
     1916}
     1917
     1918.chathearth-settings .chathearth-connection .description {
     1919        margin-block: 4px 0;
     1920}
     1921
     1922/* Text buttons keep enough contrast on every admin colour scheme */
     1923.chathearth-settings .button-link {
     1924        color: color-mix(in srgb, var(--chathearth-accent) 65%, #000);
     1925        text-decoration: underline;
     1926}
     1927
     1928.chathearth-settings .button-link:hover,
     1929.chathearth-settings .button-link:focus {
     1930        color: color-mix(in srgb, var(--chathearth-accent) 50%, #000);
     1931}
  • chathearth/tags/2.0.0/assets/css/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/assets/images/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/assets/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/assets/js/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/chathearth.php

    r3673790 r3833468  
    22/**
    33 * Plugin Name:       ChatHearth - AI Chatbot
    4  * Description:       Site-wide AI chatbot powered by WordPress Connectors (OpenAI in v1).
    5  * Version:           1.4.9
     4 * Description:       Site-wide AI chatbot for WordPress, powered by the AI Provider for OpenAI plugin.
     5 * Version:           2.0.0
    66 * Requires at least: 7.0
    77 * Requires PHP:      7.4
    88 * Requires Plugins:  ai-provider-for-openai
     9 * WC requires at least: 11.3
     10 * WC tested up to:  11.3
    911 * Author:            PalWP
    1012 * Author URI:        https://palwp.com/
    … …  
    1416 * Domain Path:       /languages
    1517 *
     18 * Until the version gate below, this file only uses syntax that PHP 5.6 can parse, so a site on an old
     19 * PHP sees the unsupported-version notice instead of a fatal error.
     20 *
    1621 * @package ChatHearth
    1722 */
    18 
    19 declare(strict_types=1);
    2023
    2124if ( ! defined( 'ABSPATH' ) ) {
    … …  
    2326}
    2427
    25 define( 'CHATHEARTH_VERSION', '1.4.9' );
     28define( 'CHATHEARTH_VERSION', '2.0.0' );
    2629define( 'CHATHEARTH_FILE', __FILE__ );
    2730define( 'CHATHEARTH_PATH', plugin_dir_path( __FILE__ ) );
    … …  
    2932define( 'CHATHEARTH_BASENAME', plugin_basename( __FILE__ ) );
    3033
    31 /** Fixed default OpenAI model for v1 (not exposed in settings). */
    32 define( 'CHATHEARTH_DEFAULT_MODEL', 'gpt-4.1' );
     34// The model used when the site has not chosen one; a site may define it first in wp-config.php.
     35if ( ! defined( 'CHATHEARTH_DEFAULT_MODEL' ) ) {
     36        define( 'CHATHEARTH_DEFAULT_MODEL', 'gpt-6.1-terra' );
     37}
     38
     39/**
     40 * Prints the notice for a site that runs an unsupported WordPress or PHP version (FR-001).
     41 *
     42 * Kept here, in plain PHP, so it works on any PHP version: nothing else of the plugin is loaded then.
     43 *
     44 * @param array<string, array{required: string, current: string}> $unmet Requirement name => versions, from ChatHearth\Requirements.
     45 * @return void
     46 */
     47function chathearth_render_unsupported_notice( $unmet ) {
     48        if ( ! current_user_can( 'manage_options' ) ) {
     49                return;
     50        }
     51
     52        $labels = array(
     53                'wordpress' => 'WordPress',
     54                'php'       => 'PHP',
     55        );
     56        $parts  = array();
     57        foreach ( $unmet as $name => $versions ) {
     58                $parts[] = sprintf(
     59                        /* translators: 1: software name (WordPress or PHP), 2: required version, 3: installed version. */
     60                        __( '%1$s %2$s or newer (this site runs %3$s)', 'chathearth' ),
     61                        isset( $labels[ $name ] ) ? $labels[ $name ] : $name,
     62                        $versions['required'],
     63                        $versions['current']
     64                );
     65        }
     66
     67        echo '<div class="notice notice-error"><p>';
     68        echo esc_html(
     69                sprintf(
     70                        /* translators: %s: the unmet requirements, for example "PHP 7.4 or newer (this site runs 7.3.33)". */
     71                        __( 'ChatHearth - AI Chatbot needs %s. The plugin stays inactive until the site is updated.', 'chathearth' ),
     72                        implode( ', ', $parts )
     73                )
     74        );
     75        echo '</p></div>';
     76}
     77
     78require_once CHATHEARTH_PATH . 'includes/class-requirements.php';
     79
     80$chathearth_unmet = ChatHearth\Requirements::unmet(
     81        isset( $GLOBALS['wp_version'] ) ? $GLOBALS['wp_version'] : '0',
     82        PHP_VERSION
     83);
     84
     85if ( ! empty( $chathearth_unmet ) ) {
     86        add_action(
     87                'admin_notices',
     88                function () use ( $chathearth_unmet ) {
     89                        chathearth_render_unsupported_notice( $chathearth_unmet );
     90                }
     91        );
     92        return;
     93}
    3394
    3495require_once CHATHEARTH_PATH . 'includes/class-autoloader.php';
    3596ChatHearth\Autoloader::register();
    3697
    37 register_activation_hook( __FILE__, array( 'ChatHearth\\Plugin', 'activate' ) );
     98register_activation_hook( __FILE__, array( 'ChatHearth\Lifecycle\Activator', 'activate' ) );
     99register_deactivation_hook( __FILE__, array( 'ChatHearth\Lifecycle\Deactivator', 'deactivate' ) );
    38100
    39101add_action(
    40102        'plugins_loaded',
    41         static function () {
    42                 ChatHearth\Plugin::instance()->init();
     103        function () {
     104                ChatHearth\Plugin::instance()->boot();
     105        },
     106        5
     107);
     108
     109// WooCommerce: this plugin reads no order and uses only the cart, so it works with the custom order tables (HPOS) and with
     110// the cart and checkout blocks. Without this declaration WooCommerce lists it as incompatible on a shop that uses them.
     111add_action(
     112        'before_woocommerce_init',
     113        function () {
     114                if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     115                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', CHATHEARTH_FILE, true );
     116                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', CHATHEARTH_FILE, true );
     117                }
    43118        }
    44119);
  • chathearth/tags/2.0.0/includes/Admin/class-admin-notices.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Admin notices (dependencies + abuse escalation).
     3 * Admin notices: readiness (FR-004) and, from the upgrade runner, upgrade failure (FR-016).
     4 *
     5 * The unsupported-version notice lives in chathearth.php, because this class cannot be loaded on a PHP
     6 * version below the plugin's minimum (research R11, R12).
    47 *
    58 * @package ChatHearth
    … …  
    1417}
    1518
    16 use ChatHearth\Plugin;
    17 use ChatHearth\Security\Rate_Limiter;
     19use ChatHearth\Migrations\Migration_Runner;
     20use ChatHearth\Admin\Settings\Abuse_Alert_Actions;
     21use ChatHearth\Admin\Settings\Settings_Page;
     22use ChatHearth\Readiness\Readiness_Checker;
    1823
    1924/**
    20  * Shows admin notices when OpenAI / Connectors are not ready, or abuse escalation fired.
     25 * Shows notices to administrators. Every string is translatable and escaped.
    2126 */
    2227final class Admin_Notices {
    2328
    2429        /**
     30         * @var Readiness_Checker
     31         */
     32        private $checker;
     33
     34        /**
     35         * @param Readiness_Checker $checker Readiness checker.
     36         */
     37        public function __construct( Readiness_Checker $checker ) {
     38                $this->checker = $checker;
     39        }
     40
     41        /**
    2542         * Register hooks.
    2643         */
    2744        public function register(): void {
    2845                add_action( 'admin_notices', array( $this, 'render' ) );
    29                 add_action( 'admin_post_chathearth_dismiss_abuse_alert', array( $this, 'dismiss_abuse_alert' ) );
    30         }
    31 
    32         /**
    33          * Render notices.
     46        }
     47
     48        /**
     49         * Render the notices for the current screen.
    3450         */
    3551        public function render(): void {
    … …  
    3854                }
    3955
     56                $this->render_upgrade_failure();
     57                $this->render_readiness();
    4058                $this->render_abuse_alert();
    41                 $this->render_dependency_notice();
    42         }
    43 
    44         /**
    45          * Notice when OpenAI / Connectors are missing.
    46          */
    47         private function render_dependency_notice(): void {
    48                 if ( Plugin::is_openai_ready() ) {
    49                         return;
    50                 }
    51 
    52                 $connectors_url = admin_url( 'options-connectors.php' );
    53 
    54                 echo '<div class="notice notice-warning"><p>';
    55                 echo esc_html__(
    56                         'ChatHearth - AI Chatbot needs WordPress AI support, the “AI Provider for OpenAI” plugin, and an OpenAI API key under Connectors. The chat icon stays hidden on the site until OpenAI is ready.',
    57                         'chathearth'
     59                $this->render_reenable_outcome();
     60                $this->render_cleared_notice();
     61        }
     62
     63        /** Confirm a counter reset on the plugin's settings screen. The flag only selects this fixed text. */
     64        private function render_cleared_notice(): void {
     65                $screen = get_current_screen();
     66                if ( null === $screen || Settings_Page::HOOK_SUFFIX !== $screen->id || is_network_admin() ) {
     67                        return;
     68                }
     69
     70                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The flag only selects fixed notice text.
     71                $flag = isset( $_GET['chathearth_cleared'] ) && is_string( $_GET['chathearth_cleared'] ) ? sanitize_key( wp_unslash( $_GET['chathearth_cleared'] ) ) : '';
     72                if ( '1' !== $flag ) {
     73                        return;
     74                }
     75
     76                echo '<div class="notice notice-success"><p>' . esc_html__( 'Rate-limit counters cleared.', 'chathearth' ) . '</p></div>';
     77        }
     78
     79        /** Display a fixed recovery message on the plugin's settings screen. */
     80        private function render_reenable_outcome(): void {
     81                $screen = get_current_screen();
     82                if ( null === $screen || Settings_Page::HOOK_SUFFIX !== $screen->id || is_network_admin() ) {
     83                        return;
     84                }
     85
     86                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The flag only selects fixed notice text.
     87                $flag = isset( $_GET['chathearth_reenable'] ) && is_string( $_GET['chathearth_reenable'] ) ? sanitize_key( wp_unslash( $_GET['chathearth_reenable'] ) ) : '';
     88                switch ( $flag ) {
     89                        case 'done':
     90                                $type    = 'success';
     91                                $message = __( 'The chat is switched back on.', 'chathearth' );
     92                                break;
     93                        case 'already':
     94                                $type    = 'info';
     95                                $message = __( 'The chat is already on.', 'chathearth' );
     96                                break;
     97                        case 'invalid':
     98                                $type    = 'warning';
     99                                $message = __( 'This link has expired or was already used. Switch the chat on in the Protection settings.', 'chathearth' );
     100                                break;
     101                        default:
     102                                return;
     103                }
     104
     105                echo '<div class="notice notice-' . esc_attr( $type ) . '"><p>' . esc_html( $message ) . '</p></div>';
     106        }
     107
     108        /**
     109         * Tell administrators that the settings upgrade could not finish (FR-016). The site keeps working.
     110         */
     111        private function render_upgrade_failure(): void {
     112                if ( ! is_array( get_option( Migration_Runner::ERROR_OPTION, false ) ) ) {
     113                        return;
     114                }
     115
     116                echo '<div class="notice notice-error"><p>' . esc_html__( 'ChatHearth - AI Chatbot could not finish updating its settings. Your site keeps working with your current settings, and the update will be tried again automatically.', 'chathearth' ) . '</p></div>';
     117        }
     118
     119        /**
     120         * Warn when ChatHearth is not ready, naming the missing item. Not shown on network-admin screens.
     121         */
     122        private function render_readiness(): void {
     123                if ( is_network_admin() ) {
     124                        return;
     125                }
     126
     127                $status = $this->checker->status();
     128                if ( $status->is_ready() || array() === $status->missing() ) {
     129                        return;
     130                }
     131
     132                $missing = $status->missing()[0];
     133                $link    = null;
     134                switch ( $missing ) {
     135                        case 'ai_support':
     136                                $message = __( 'ChatHearth - AI Chatbot needs WordPress AI support, which is turned off or unavailable on this site. The chat icon stays hidden until it is available.', 'chathearth' );
     137                                break;
     138                        case 'provider_plugin':
     139                                $message = __( 'ChatHearth - AI Chatbot needs the “AI Provider for OpenAI” plugin to be installed and active. The chat icon stays hidden until it is.', 'chathearth' );
     140                                $link    = array( admin_url( 'plugins.php' ), __( 'Open Plugins', 'chathearth' ) );
     141                                break;
     142                        case 'connector':
     143                                $message = __( 'ChatHearth - AI Chatbot cannot find the OpenAI connector. The chat icon stays hidden until it is available.', 'chathearth' );
     144                                $link    = array( admin_url( 'options-connectors.php' ), __( 'Open Connectors settings', 'chathearth' ) );
     145                                break;
     146                        default:
     147                                $message = __( 'ChatHearth - AI Chatbot needs an OpenAI API key under Connectors. The chat icon stays hidden until one is added.', 'chathearth' );
     148                                $link    = array( admin_url( 'options-connectors.php' ), __( 'Open Connectors settings', 'chathearth' ) );
     149                }
     150
     151                echo '<div class="notice notice-warning"><p>' . esc_html( $message );
     152                if ( null !== $link ) {
     153                        echo ' <a href="' . esc_url( $link[0] ) . '">' . esc_html( $link[1] ) . '</a>';
     154                }
     155                echo '</p></div>';
     156        }
     157
     158        /**
     159         * The abuse alert written by the rate limiter (the 1.4.9 option): hits and, when the chat was switched off
     160         * automatically, a link to switch it back on. A missing or `time`-less alert shows nothing; values are cast and
     161         * escaped, so a hostile alert can only produce plain text. Not shown on network-admin screens.
     162         */
     163        private function render_abuse_alert(): void {
     164                if ( is_network_admin() ) {
     165                        return;
     166                }
     167                $alert = get_option( Settings_Page::ABUSE_ALERT, false );
     168                if ( ! is_array( $alert ) || ! isset( $alert['time'] ) ) {
     169                        return;
     170                }
     171
     172                $hits = isset( $alert['incidents'] ) && is_numeric( $alert['incidents'] ) ? max( 0, (int) $alert['incidents'] ) : 0;
     173                $auto = ! empty( $alert['auto_disabled'] );
     174
     175                $review  = add_query_arg(
     176                        array(
     177                                'page'    => Settings_Page::SLUG,
     178                                'tab'     => 'protection',
     179                                'section' => 'escalation',
     180                        ),
     181                        admin_url( 'options-general.php' )
    58182                );
    59                 echo ' <a href="' . esc_url( $connectors_url ) . '">' . esc_html__( 'Open Connectors settings', 'chathearth' ) . '</a>';
    60                 echo '</p></div>';
    61         }
    62 
    63         /**
    64          * Notice after global rate-limit escalation.
    65          */
    66         private function render_abuse_alert(): void {
    67                 $alert = get_option( Rate_Limiter::ABUSE_ALERT_OPTION, null );
    68                 if ( ! is_array( $alert ) || empty( $alert['time'] ) ) {
    69                         return;
    70                 }
    71 
    72                 $settings_url = admin_url( 'options-general.php?page=chathearth&tab=protection' );
    73                 $dismiss_url  = wp_nonce_url(
    74                         admin_url( 'admin-post.php?action=chathearth_dismiss_abuse_alert' ),
    75                         'chathearth_dismiss_abuse_alert'
    76                 );
    77 
    78                 $incidents = isset( $alert['incidents'] ) ? (int) $alert['incidents'] : 0;
    79 
    80                 echo '<div class="notice notice-error"><p>';
    81                 echo esc_html__(
    82                         'ChatHearth - AI Chatbot: global rate limits were hit repeatedly (possible multi-IP abuse).',
    83                         'chathearth'
    84                 );
    85                 if ( $incidents > 0 ) {
    86                         echo ' ';
    87                         echo esc_html(
    88                                 sprintf(
    89                                         /* translators: %d: number of hits */
    90                                         __( 'Recorded hits in the window: %d.', 'chathearth' ),
    91                                         $incidents
    92                                 )
    93                         );
    94                 }
    95                 if ( ! empty( $alert['auto_disabled'] ) ) {
    96                         echo ' ';
    97                         echo esc_html__( 'The chatbot was automatically disabled.', 'chathearth' );
    98                 }
    99                 echo ' <a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Open Protection settings', 'chathearth' ) . '</a>';
    100                 echo ' | <a href="' . esc_url( $dismiss_url ) . '">' . esc_html__( 'Dismiss', 'chathearth' ) . '</a>';
    101                 echo '</p></div>';
    102         }
    103 
    104         /**
    105          * Dismiss the abuse alert notice.
    106          */
    107         public function dismiss_abuse_alert(): void {
    108                 if ( ! current_user_can( 'manage_options' ) ) {
    109                         wp_die( esc_html__( 'Sorry, you are not allowed to do that.', 'chathearth' ) );
    110                 }
    111 
    112                 check_admin_referer( 'chathearth_dismiss_abuse_alert' );
    113                 delete_option( Rate_Limiter::ABUSE_ALERT_OPTION );
    114 
    115                 $redirect = wp_get_referer();
    116                 if ( ! is_string( $redirect ) || '' === $redirect ) {
    117                         $redirect = admin_url( 'options-general.php?page=chathearth&tab=protection' );
    118                 }
    119 
    120                 wp_safe_redirect( $redirect );
    121                 exit;
     183                $action  = static function ( string $name ): string {
     184                        return wp_nonce_url( admin_url( 'admin-post.php?action=' . $name ), $name );
     185                };
     186                $message = esc_html__( 'Site-wide rate limits were hit repeatedly (possible abuse).', 'chathearth' ) . ' '
     187                        /* translators: %s: number of recorded rate-limit hits. */
     188                        . esc_html( sprintf( _n( 'Recorded hit: %s.', 'Recorded hits: %s.', $hits, 'chathearth' ), number_format_i18n( $hits ) ) );
     189                if ( $auto ) {
     190                        $message .= ' ' . esc_html__( 'The chat was switched off automatically.', 'chathearth' );
     191                }
     192
     193                $links = array();
     194                if ( $auto ) {
     195                        $links[] = '<a href="' . esc_url( $action( Abuse_Alert_Actions::ENABLE ) ) . '">' . esc_html__( 'Switch chat back on', 'chathearth' ) . '</a>';
     196                }
     197                $links[] = '<a href="' . esc_url( $review ) . '">' . esc_html__( 'Review protection settings', 'chathearth' ) . '</a>';
     198                $links[] = '<a href="' . esc_url( $action( Abuse_Alert_Actions::DISMISS ) ) . '">' . esc_html__( 'Dismiss', 'chathearth' ) . '</a>';
     199
     200                echo '<div class="notice notice-error"><p>' . $message . '</p><p>' . implode( ' · ', $links ) . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Every part is escaped above.
    122201        }
    123202}
  • chathearth/tags/2.0.0/includes/Admin/class-privacy.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Privacy Policy suggested content.
     3 * Suggested text for Settings → Privacy Policy (interface layer; research R12, FR-033).
     4 *
     5 * Ported from 1.4.9 and extended for the 2.0 data flows. Every item starts by saying when it applies.
    46 *
    57 * @package ChatHearth
    … …  
    1517
    1618/**
    17  * Registers suggested text for Settings → Privacy Policy.
     19 * Registers the suggested privacy-policy text.
    1820 */
    1921final class Privacy {
    2022
    2123        /**
    22          * Register hooks.
     24         * Hooks the registration to `admin_init`, where WordPress expects it.
    2325         */
    2426        public function register(): void {
    … …  
    2729
    2830        /**
    29          * Suggest privacy policy text describing chatbot data flows.
     31         * The suggested items, one per data flow.
     32         *
     33         * @return string[]
     34         */
     35        private function items(): array {
     36                $items = array(
     37                        __( 'Always, when a visitor sends a message: the message and the recent conversation history of that chat are sent to OpenAI, through the AI provider set up in WordPress (Connectors), so a reply can be generated.', 'chathearth' ),
     38                        __( 'Always, when a visitor sends a message: a short summary of this site’s public pages (and, with WooCommerce, the store and its product categories) and the public content of the page the visitor is on are sent to the AI provider together with the instructions, so the answer is about this site. Drafts, private and password-protected content are never sent, and the page is read as a guest sees it.', 'chathearth' ),
     39                        __( 'Always: the conversation history of the chat is kept in the visitor’s browser (local storage) and removed after 24 hours without a new message, or sooner when the visitor clears the chat. The plugin does not store chat transcripts in the WordPress database.', 'chathearth' ),
     40                        __( 'Always: the visitor’s IP address is used for a short time for rate limits, for blocking the addresses you list and for abuse protection. IPv6 visitors are counted per network block. Visitors behind a proxy share a limit until trusted proxies are set up. The counters are short-lived and are not a chat log.', 'chathearth' ),
     41                        __( 'When you list blocked addresses: the addresses and ranges you enter are stored in the plugin’s settings and compared with each visitor’s address. Visitors’ addresses are not stored.', 'chathearth' ),
     42                        __( 'When “Separate limits for logged-in users” is on: the visitor’s WordPress user account is used to count their messages, so the limits follow the person and not their network.', 'chathearth' ),
     43                        __( 'When the bot trap is on: an invisible form field is added to the chat. Only automated programs fill it in, and the result is used to refuse their requests. Visitors never see it.', 'chathearth' ),
     44                        __( 'When content moderation uses OpenAI: the new message and up to two earlier visitor messages of the same chat (never the assistant’s replies) are also sent to OpenAI’s moderation service before a reply is generated, so harmful or disallowed content can be blocked. Only texts not checked in the last 24 hours are sent. The result is remembered for 24 hours as a salted hash, never as text.', 'chathearth' ),
     45                        __( 'When both Google reCAPTCHA v3 keys are set: Google is contacted only after the visitor presses Continue. Google processes a score-based check and related technical data such as the IP address, under Google’s privacy policy. The HTTP-only chathearth_human cookie lasts at most 60 minutes and is used only to skip repeated checks.', 'chathearth' ),
     46                        __( 'When the Knowledge Base is on and OpenAI is connected: the public content selected in the Knowledge Base settings is sent to the OpenAI embeddings service when it is indexed and when it changes, and each visitor question is sent to the OpenAI embeddings service to find matching passages. ChatHearth does not store the question for this. The index holds only this public site content and its numeric representations (embeddings), stored in the WordPress database of this site, with no visitor or account data, so there is nothing in it to export or erase for a person. Markdown copies of the selected content can be kept in the uploads folder of this site.', 'chathearth' ),
     47                        __( 'Always: ChatHearth does not track visitors. It sets no tracking cookies and sends no analytics.', 'chathearth' ),
     48                        __( 'Always: ChatHearth does not store the AI provider key. That credential is managed by WordPress Connectors or the server environment.', 'chathearth' ),
     49                        __( 'Always: the summary of this site’s public pages that goes with a message is kept on this site for up to 12 hours, so the next messages do not rebuild it.', 'chathearth' ),
     50                        __( 'Always: the rate-limit counters of a visitor’s network or account are kept only for the length of the limit window and are not a chat log.', 'chathearth' ),
     51                        __( 'When the Knowledge Base is on: the index stays in the WordPress database of this site until you delete an item, turn the Knowledge Base off or delete the plugin, and the markdown copies in the uploads folder are removed when you turn the setting off or delete the plugin.', 'chathearth' ),
     52                        __( 'When site-wide rate limits are hit repeatedly: the plugin keeps an abuse alert in this site’s options, with the number of hits and whether the chat was switched off, and shows it to administrators until you dismiss it. It holds no visitor data.', 'chathearth' ),
     53                        __( 'When WP_DEBUG_LOG is already on in your site’s configuration: the plugin writes short failure codes to the PHP error log, and never message text, addresses or keys.', 'chathearth' ),
     54                        __( 'Always: the plugin sets no tracking or analytics cookie, sends no analytics or telemetry request and keeps no visitor identifier beyond the stores described here.', 'chathearth' ),
     55                );
     56
     57                // The shop item only appears on a site that has a shop (feature 013, FR-025): the Add to cart sentence of feature 009
     58                // and the one about the product facts that go to the AI provider with the question.
     59                if ( class_exists( 'WooCommerce' ) ) {
     60                        array_splice(
     61                                $items,
     62                                10,
     63                                0,
     64                                array(
     65                                        __( 'When WooCommerce is active and the assistant shows product cards: the Add to cart button of a product card in the chat uses the WooCommerce cart on this site. Payment still happens at the store checkout.', 'chathearth' ) . ' ' .
     66                                        __( 'The facts of the products named in a message or found in the knowledge base (name, price, stock, categories, attributes and short description) are sent to the AI provider with the question.', 'chathearth' ),
     67                                )
     68                        );
     69                }
     70
     71                return $items;
     72        }
     73
     74        /**
     75         * Suggests the privacy-policy text.
    3076         */
    3177        public function add_privacy_policy_content(): void {
    … …  
    3480                }
    3581
    36                 $content = '<p>' . esc_html__(
    37                         'ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this site. When someone uses the chatbot, the following may apply:',
    38                         'chathearth'
    39                 ) . '</p>';
     82                $content = '<p>' . esc_html__( 'ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this site. Depending on how the chatbot is set up, the following may apply:', 'chathearth' ) . '</p><ul>';
     83                foreach ( $this->items() as $item ) {
     84                        $content .= '<li>' . esc_html( $item ) . '</li>';
     85                }
     86                $content .= '</ul><p>' . esc_html__( 'Site owners should read the privacy policy of their AI provider (and of Google, if reCAPTCHA is used) and make sure this section matches how the chatbot is set up on their site.', 'chathearth' ) . '</p>';
    4087
    41                 $content .= '<ul>';
    42                 $content .= '<li>' . esc_html__(
    43                         'Message text and recent conversation history from the chat session are sent to a third-party AI provider (OpenAI in the current version) through WordPress Connectors / the site’s configured AI provider, so a reply can be generated.',
    44                         'chathearth'
    45                 ) . '</li>';
    46                 $content .= '<li>' . esc_html__(
    47                         'Conversation history for the widget is stored in the visitor’s browser (local storage). The plugin does not store chat transcripts in the WordPress database in the current version.',
    48                         'chathearth'
    49                 ) . '</li>';
    50                 $content .= '<li>' . esc_html__(
    51                         'The visitor’s IP address may be used temporarily for rate limiting and abuse protection. Related counters are short-lived and are not kept as a chat log.',
    52                         'chathearth'
    53                 ) . '</li>';
    54                 $content .= '<li>' . esc_html__(
    55                         'If content moderation is enabled, message text (and prior user turns from the chat session) may also be sent to OpenAI’s Moderations API before a chat reply is generated, so harmful or disallowed content can be blocked.',
    56                         'chathearth'
    57                 ) . '</li>';
    58                 $content .= '<li>' . esc_html__(
    59                         'If Google reCAPTCHA v3 is enabled in the chatbot settings, Google may process a score-based challenge (and related technical data such as IP address) according to Google’s privacy policy. Visitors see a verification overlay on the chat window until Google accepts the request.',
    60                         'chathearth'
    61                 ) . '</li>';
    62                 $content .= '<li>' . esc_html__(
    63                         'If knowledge retrieval (RAG) is enabled, visitor questions are embedded and compared to indexed website content. Generated markdown copies of selected pages, posts, products, and taxonomies are stored on this site. Embeddings are stored in the WordPress database. The OpenAI Embeddings API may be used (via the Connectors key) to create those vectors.',
    64                         'chathearth'
    65                 ) . '</li>';
    66                 $content .= '<li>' . esc_html__(
    67                         'If a visitor adds a product to the cart from the chat widget, that action uses the WooCommerce cart on this site. Payment still happens on the store checkout.',
    68                         'chathearth'
    69                 ) . '</li>';
    70                 $content .= '<li>' . esc_html__(
    71                         'This plugin does not store the AI provider API key; that credential is managed through WordPress Connectors or the server environment.',
    72                         'chathearth'
    73                 ) . '</li>';
    74                 $content .= '</ul>';
    75 
    76                 $content .= '<p>' . esc_html__(
    77                         'Site owners should review the privacy policy of their chosen AI provider (and Google, if reCAPTCHA is used) and ensure this section matches how the chatbot is configured on their site.',
    78                         'chathearth'
    79                 ) . '</p>';
    80 
    81                 wp_add_privacy_policy_content(
    82                         __( 'ChatHearth - AI Chatbot', 'chathearth' ),
    83                         wp_kses_post( $content )
    84                 );
     88                wp_add_privacy_policy_content( __( 'ChatHearth - AI Chatbot', 'chathearth' ), wp_kses_post( $content ) );
    8589        }
    8690}
  • chathearth/tags/2.0.0/includes/Admin/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/includes/Ai/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/includes/Commerce/class-cart-service.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Add WooCommerce products to the visitor cart from chat.
     3 * Adds a product to the shop's cart for the chat (feature 013, research R7, R8; FR-013 to FR-017).
     4 *
     5 * It keeps the 1.4.9 error codes and texts and closes the 1.4.9 gaps: only published, public products count, an option
     6 * must belong to its product and be one the chat offers, and a refused attempt leaves the cart and the shop's notices as
     7 * they were. The shop's session starts only after a successful add. Nothing is logged but the class of an exception: never a
     8 * product name, a cart key or an address.
    49 *
    510 * @package ChatHearth
    … …  
    1419}
    1520
    16 use WP_Error;
     21use ChatHearth\Logger;
    1722
    1823/**
    19  * Thin wrapper around WC()->cart.
     24 * Checks and adds. It holds services only, never request state.
    2025 */
    2126final class Cart_Service {
    2227
    2328        /**
    24          * Whether cart operations can run.
    25          */
    26         public static function is_available(): bool {
    27                 return class_exists( 'WooCommerce' ) && function_exists( 'WC' ) && function_exists( 'wc_get_product' );
    28         }
    29 
    30         /**
    31          * Cart URL when WooCommerce is active.
    32          */
    33         public static function cart_url(): string {
    34                 if ( function_exists( 'wc_get_cart_url' ) ) {
    35                         return (string) wc_get_cart_url();
    36                 }
    37 
    38                 return home_url( '/' );
    39         }
    40 
    41         /**
    42          * Checkout URL when WooCommerce is active.
    43          */
    44         public static function checkout_url(): string {
    45                 if ( function_exists( 'wc_get_checkout_url' ) ) {
    46                         return (string) wc_get_checkout_url();
    47                 }
    48 
    49                 return home_url( '/' );
    50         }
    51 
    52         /**
    53          * Add a product to the current visitor cart.
     29         * Most units of a product one request adds.
     30         */
     31        public const MAX_QUANTITY = 99;
     32
     33        /**
     34         * @var Product_Catalog
     35         */
     36        private $catalog;
     37
     38        /**
     39         * @var Product_Card
     40         */
     41        private $card;
     42
     43        /**
     44         * @param Product_Catalog $catalog Says whether WooCommerce is active.
     45         * @param Product_Card    $card    The card the reply carries, and the options the chat offers.
     46         */
     47        public function __construct( Product_Catalog $catalog, Product_Card $card ) {
     48                $this->catalog = $catalog;
     49                $this->card    = $card;
     50        }
     51
     52        /**
     53         * Whether WooCommerce is active and its cart could be loaded for this request. Loading the cart starts no shop session
     54         * cookie for a guest.
     55         */
     56        public function load(): bool {
     57                if ( ! $this->catalog->is_available() || ! function_exists( 'wc_load_cart' ) ) {
     58                        return false;
     59                }
     60
     61                try {
     62                        wc_load_cart();
     63                } catch ( \Throwable $e ) {
     64                        Logger::warning( 'cart_unavailable', array( 'exception' => get_class( $e ) ) );
     65
     66                        return false;
     67                }
     68
     69                if ( ! function_exists( 'WC' ) || ! is_object( WC()->cart ) ) {
     70                        return false;
     71                }
     72
     73                // A REST request runs after the shop has loaded carts from sessions, so the saved cart is read here: without this the
     74                // cart is empty in memory and an add would replace what the guest already had.
     75                WC()->cart->get_cart();
     76
     77                return true;
     78        }
     79
     80        /**
     81         * Add one product, or one option of a variable product.
    5482         *
    5583         * @param int $product_id   Product id.
    56          * @param int $quantity     Quantity.
    57          * @param int $variation_id Optional variation.
    58          * @return array<string, mixed>|WP_Error
    59          */
    60         public function add( int $product_id, int $quantity = 1, int $variation_id = 0 ) {
    61                 if ( ! self::is_available() ) {
    62                         return new WP_Error(
    63                                 'chathearth_cart_unavailable',
    64                                 __( 'The store cart is not available.', 'chathearth' ),
    65                                 array( 'status' => 400 )
    66                         );
    67                 }
    68 
    69                 $quantity = max( 1, min( 99, $quantity ) );
    70                 $product  = wc_get_product( $variation_id > 0 ? $variation_id : $product_id );
    71                 if ( ! is_object( $product ) || ! method_exists( $product, 'is_purchasable' ) ) {
    72                         return new WP_Error(
    73                                 'chathearth_cart_product',
    74                                 __( 'That product is not available.', 'chathearth' ),
    75                                 array( 'status' => 404 )
    76                         );
    77                 }
    78 
    79                 if ( ! $product->is_purchasable() || ( method_exists( $product, 'is_in_stock' ) && ! $product->is_in_stock() ) ) {
    80                         return new WP_Error(
    81                                 'chathearth_cart_product',
    82                                 __( 'That product cannot be added to the cart.', 'chathearth' ),
    83                                 array( 'status' => 400 )
    84                         );
    85                 }
    86 
    87                 if ( function_exists( 'wc_load_cart' ) ) {
    88                         wc_load_cart();
    89                 }
    90 
    91                 if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
    92                         return new WP_Error(
    93                                 'chathearth_cart_unavailable',
    94                                 __( 'The store cart is not available.', 'chathearth' ),
    95                                 array( 'status' => 400 )
    96                         );
    97                 }
    98 
    99                 $added = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id );
    100                 if ( ! $added ) {
    101                         return new WP_Error(
     84         * @param int $quantity     Units; kept between 1 and 99.
     85         * @param int $variation_id Option id, or 0.
     86         * @return array<string, mixed>|\WP_Error The 1.4.9 reply, or the refusal.
     87         */
     88        public function add( int $product_id, int $quantity, int $variation_id ) {
     89                $quantity = max( 1, min( self::MAX_QUANTITY, $quantity ) );
     90
     91                $post = get_post( $product_id );
     92                if ( ! $post instanceof \WP_Post || 'product' !== $post->post_type || 'publish' !== $post->post_status || '' !== $post->post_password ) {
     93                        return $this->not_available();
     94                }
     95                $card = $this->card->for_product( $product_id, true );
     96                if ( null === $card ) {
     97                        return $this->not_available();
     98                }
     99                if ( $variation_id > 0 && ! $this->is_option_of( $variation_id, $product_id ) ) {
     100                        return $this->not_available();
     101                }
     102
     103                if ( empty( $card['purchasable'] ) || ! $this->is_offered( $card, $variation_id ) ) {
     104                        return $this->cannot_add();
     105                }
     106
     107                $attributes = $variation_id > 0 ? wc_get_product_variation_attributes( $variation_id ) : array();
     108                $key        = $this->shop_add( $product_id, $quantity, $variation_id, $attributes );
     109                if ( '' === $key ) {
     110                        if ( function_exists( 'wc_clear_notices' ) ) {
     111                                wc_clear_notices();
     112                        }
     113
     114                        return new \WP_Error(
    102115                                'chathearth_cart_failed',
    103116                                __( 'Could not add that product to the cart.', 'chathearth' ),
    … …  
    106119                }
    107120
     121                $this->start_guest_session();
     122
    108123                return array(
    109124                        'added'        => true,
    110                         'key'          => (string) $added,
     125                        'key'          => $key,
    111126                        'cart_count'   => (int) WC()->cart->get_cart_contents_count(),
    112                         'cart_url'     => self::cart_url(),
    113                         'checkout_url' => self::checkout_url(),
     127                        'cart_url'     => (string) wc_get_cart_url(),
     128                        'checkout_url' => (string) wc_get_checkout_url(),
    114129                        'product_id'   => $product_id,
    115130                        'variation_id' => $variation_id,
    116131                        'quantity'     => $quantity,
     132                        'product'      => $card,
    117133                );
    118134        }
     135
     136        /**
     137         * Whether an option is a published option of the product.
     138         *
     139         * @param int $variation_id Option id.
     140         * @param int $product_id   Product id.
     141         */
     142        private function is_option_of( int $variation_id, int $product_id ): bool {
     143                $variation = wc_get_product( $variation_id );
     144
     145                return is_object( $variation )
     146                        && 'variation' === $variation->get_type()
     147                        && (int) $variation->get_parent_id() === $product_id
     148                        && 'publish' === get_post_status( $variation_id );
     149        }
     150
     151        /**
     152         * Whether the chat offers what was asked: a simple product as it is, a variable product only through an option it
     153         * lists that is in stock.
     154         *
     155         * @param array<string, mixed> $card         The product's card.
     156         * @param int                  $variation_id Option id, or 0.
     157         */
     158        private function is_offered( array $card, int $variation_id ): bool {
     159                if ( 'variable' !== ( $card['type'] ?? '' ) ) {
     160                        return 0 === $variation_id;
     161                }
     162
     163                foreach ( (array) ( $card['variations'] ?? array() ) as $option ) {
     164                        if ( (int) $option['id'] === $variation_id ) {
     165                                return ! empty( $option['is_in_stock'] );
     166                        }
     167                }
     168
     169                return false;
     170        }
     171
     172        /**
     173         * The shop's own add. Any exception, and any refusal, gives an empty key.
     174         *
     175         * @param int                  $product_id   Product id.
     176         * @param int                  $quantity     Units.
     177         * @param int                  $variation_id Option id, or 0.
     178         * @param array<string,string> $attributes   Attributes of the option.
     179         * @return string The cart key, or an empty string.
     180         */
     181        private function shop_add( int $product_id, int $quantity, int $variation_id, array $attributes ): string {
     182                try {
     183                        // The shop's own validation hook, as its add-to-cart form runs it, so a store's rules (minimum quantity, one per
     184                        // customer and so on) apply here too. WooCommerce's cart does not run it by itself.
     185                        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- A WooCommerce hook.
     186                        if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $attributes ) ) {
     187                                Logger::warning( 'cart_failed' );
     188
     189                                return '';
     190                        }
     191
     192                        $key = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $attributes );
     193                } catch ( \Throwable $e ) {
     194                        Logger::warning( 'cart_failed', array( 'exception' => get_class( $e ) ) );
     195
     196                        return '';
     197                }
     198                if ( ! is_string( $key ) || '' === $key ) {
     199                        Logger::warning( 'cart_failed' );
     200
     201                        return '';
     202                }
     203
     204                return $key;
     205        }
     206
     207        /**
     208         * Gives the guest a shop session, in this request. The shop sets its cookies on `wp` or at shutdown, which is too late
     209         * for a REST reply, so a guest's first add would be lost.
     210         */
     211        private function start_guest_session(): void {
     212                if ( is_object( WC()->session ) && method_exists( WC()->session, 'set_customer_session_cookie' ) ) {
     213                        WC()->session->set_customer_session_cookie( true );
     214                }
     215                WC()->cart->maybe_set_cart_cookies();
     216        }
     217
     218        /**
     219         * The 1.4.9 404.
     220         */
     221        private function not_available(): \WP_Error {
     222                return new \WP_Error(
     223                        'chathearth_cart_product',
     224                        __( 'That product is not available.', 'chathearth' ),
     225                        array( 'status' => 404 )
     226                );
     227        }
     228
     229        /**
     230         * The 1.4.9 400 for a product that exists but cannot be added.
     231         */
     232        private function cannot_add(): \WP_Error {
     233                return new \WP_Error(
     234                        'chathearth_cart_product',
     235                        __( 'That product cannot be added to the cart.', 'chathearth' ),
     236                        array( 'status' => 400 )
     237                );
     238        }
    119239}
  • chathearth/tags/2.0.0/includes/Commerce/class-product-catalog.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Public product payload for chat cards and cart.
     3 * What the chat knows about shop products (feature 013, research R1, R3, R6).
     4 *
     5 * It keeps nothing between calls (Constitution V): the stage calls `cards_for()` once per message and keeps the cards on the
     6 * `Catalog_Result` of the request. Every WooCommerce call in the feature sits behind `is_available()`.
    47 *
    58 * @package ChatHearth
    … …  
    1417}
    1518
     19use ChatHearth\Rag\Retrieval_Result;
     20
    1621/**
    17  * Read-only product helper (WooCommerce when present).
     22 * Product cards, retrieved product ids and catalogue facts.
    1823 */
    1924final class Product_Catalog {
    2025
    2126        /**
    22          * Whether WooCommerce product APIs are available.
    23          */
    24         public static function is_available(): bool {
    25                 return class_exists( 'WooCommerce' ) && function_exists( 'wc_get_product' );
    26         }
    27 
    28         /**
    29          * Public catalog card, or null.
    30          *
    31          * @param int $product_id Product id.
    32          * @return array<string, mixed>|null
    33          */
    34         public function get_public_product( int $product_id ): ?array {
    35                 if ( $product_id <= 0 || ! self::is_available() ) {
    36                         return null;
    37                 }
    38 
    39                 $product = wc_get_product( $product_id );
    40                 if ( ! is_object( $product ) || ! method_exists( $product, 'get_id' ) ) {
    41                         return null;
    42                 }
    43 
    44                 $status = get_post_status( $product_id );
    45                 if ( 'publish' !== $status ) {
    46                         return null;
    47                 }
    48 
    49                 $name        = method_exists( $product, 'get_name' ) ? (string) $product->get_name() : get_the_title( $product_id );
    50                 $url         = (string) get_permalink( $product_id );
    51                 $price       = $this->format_amount( method_exists( $product, 'get_price' ) ? $product->get_price() : '' );
    52                 $regular     = $this->regular_price_if_on_sale( $product );
    53                 $media       = $this->public_image( $product_id, $product );
    54                 $purchasable = method_exists( $product, 'is_purchasable' ) && method_exists( $product, 'is_in_stock' )
    55                         ? ( $product->is_purchasable() && $product->is_in_stock() )
    56                         : false;
    57 
    58                 $variations = array();
    59                 if ( method_exists( $product, 'is_type' ) && $product->is_type( 'variable' ) && method_exists( $product, 'get_available_variations' ) ) {
    60                         $raw = $product->get_available_variations();
    61                         if ( is_array( $raw ) ) {
    62                                 foreach ( array_slice( $raw, 0, 30 ) as $row ) {
    63                                         if ( ! is_array( $row ) ) {
    64                                                 continue;
    65                                         }
    66                                         $variations[] = array(
    67                                                 'id'          => isset( $row['variation_id'] ) ? (int) $row['variation_id'] : 0,
    68                                                 'price'       => isset( $row['display_price'] ) ? (string) $row['display_price'] : '',
    69                                                 'is_in_stock' => ! empty( $row['is_in_stock'] ),
    70                                                 'attributes'  => isset( $row['attributes'] ) && is_array( $row['attributes'] ) ? $row['attributes'] : array(),
    71                                         );
     27         * Longest short description kept for the assistant.
     28         */
     29        public const MAX_DESCRIPTION = 300;
     30
     31        /**
     32         * @var Product_Card
     33         */
     34        private $card;
     35
     36        /**
     37         * @param Product_Card $card The card builder.
     38         */
     39        public function __construct( Product_Card $card ) {
     40                $this->card = $card;
     41        }
     42
     43        /**
     44         * Whether WooCommerce is active and usable.
     45         */
     46        public function is_available(): bool {
     47                return class_exists( 'WooCommerce' ) && function_exists( 'WC' ) && function_exists( 'wc_get_product' );
     48        }
     49
     50        /**
     51         * The cards of products, in the order given. A product that is not published and public, or cannot be loaded, has no
     52         * card and is left out.
     53         *
     54         * @param int[] $ids Product ids.
     55         * @return array<int, array<string, mixed>>
     56         */
     57        public function cards_for( array $ids ): array {
     58                if ( ! $this->is_available() ) {
     59                        return array();
     60                }
     61
     62                $cards = array();
     63                foreach ( $ids as $id ) {
     64                        $card = $this->card->for_product( (int) $id );
     65                        if ( null !== $card ) {
     66                                $cards[] = $card;
     67                        }
     68                }
     69
     70                return $cards;
     71        }
     72
     73        /**
     74         * The published, password-free products among the retrieved passages, in rank order.
     75         *
     76         * @param Retrieval_Result $result What the search found.
     77         * @return int[]
     78         */
     79        public function retrieved_ids( Retrieval_Result $result ): array {
     80                if ( ! $this->is_available() ) {
     81                        return array();
     82                }
     83
     84                $ids = array();
     85                foreach ( $result->product_ids() as $id ) {
     86                        $post = get_post( $id );
     87                        if ( $post instanceof \WP_Post && 'product' === $post->post_type && 'publish' === $post->post_status && '' === $post->post_password ) {
     88                                $ids[] = (int) $id;
     89                        }
     90                }
     91
     92                return $ids;
     93        }
     94
     95        /**
     96         * The facts of a published product that the catalogue block adds to its card: category names, visible attributes
     97         * (`Name: value, value`) and the short description as plain text. Nothing for a product that is not published.
     98         *
     99         * @param int $id Product id.
     100         * @return array{categories: string[], attributes: string[], short_description: string}
     101         */
     102        public function facts( int $id ): array {
     103                $none = array(
     104                        'categories'        => array(),
     105                        'attributes'        => array(),
     106                        'short_description' => '',
     107                );
     108                if ( ! $this->is_available() ) {
     109                        return $none;
     110                }
     111
     112                $post = get_post( $id );
     113                if ( ! $post instanceof \WP_Post || 'product' !== $post->post_type || 'publish' !== $post->post_status || '' !== $post->post_password ) {
     114                        return $none;
     115                }
     116                $product = function_exists( 'wc_get_product' ) ? wc_get_product( $id ) : null;
     117                if ( ! is_object( $product ) ) {
     118                        return $none;
     119                }
     120
     121                return array(
     122                        'categories'        => $this->categories( $id ),
     123                        'attributes'        => $this->attributes( $product ),
     124                        'short_description' => $this->description( $product ),
     125                );
     126        }
     127
     128        /**
     129         * Category names of a product.
     130         *
     131         * @param int $id Product id.
     132         * @return string[]
     133         */
     134        private function categories( int $id ): array {
     135                $terms = get_the_terms( $id, 'product_cat' );
     136                if ( ! is_array( $terms ) ) {
     137                        return array();
     138                }
     139
     140                $names = array();
     141                foreach ( $terms as $term ) {
     142                        $names[] = html_entity_decode( $term->name, ENT_QUOTES, 'UTF-8' );
     143                }
     144
     145                return $names;
     146        }
     147
     148        /**
     149         * The attributes that are visible on the product page, as `Name: value, value`.
     150         *
     151         * @param object $product WooCommerce product.
     152         * @return string[]
     153         */
     154        private function attributes( $product ): array {
     155                if ( ! method_exists( $product, 'get_attributes' ) ) {
     156                        return array();
     157                }
     158
     159                $lines = array();
     160                foreach ( (array) $product->get_attributes() as $attribute ) {
     161                        if ( ! is_object( $attribute ) || ! method_exists( $attribute, 'get_visible' ) || ! $attribute->get_visible() ) {
     162                                continue;
     163                        }
     164
     165                        $name = (string) $attribute->get_name();
     166                        if ( $attribute->is_taxonomy() ) {
     167                                $values = function_exists( 'wc_get_product_terms' ) ? wc_get_product_terms( (int) $product->get_id(), $name, array( 'fields' => 'names' ) ) : array();
     168                        } else {
     169                                $values = $attribute->get_options();
     170                        }
     171                        $values = array_filter(
     172                                array_map( 'strval', (array) $values ),
     173                                static function ( string $value ): bool {
     174                                        return '' !== $value;
    72175                                }
    73                         }
    74                 }
    75 
    76                 return array(
    77                         'id'            => (int) $product->get_id(),
    78                         'name'          => $name,
    79                         'url'           => $url,
    80                         'image'         => $media['url'],
    81                         'image_alt'     => $media['alt'],
    82                         'price'         => $price,
    83                         'regular_price' => $regular,
    84                         'on_sale'       => '' !== $regular,
    85                         'purchasable'   => $purchasable,
    86                         'in_stock'      => method_exists( $product, 'is_in_stock' ) ? (bool) $product->is_in_stock() : false,
    87                         'type'          => method_exists( $product, 'get_type' ) ? (string) $product->get_type() : 'simple',
    88                         'variations'    => $variations,
    89                 );
    90         }
    91 
    92         /**
    93          * Previous (regular) price when the product is on sale.
     176                        );
     177                        if ( array() === $values ) {
     178                                continue;
     179                        }
     180
     181                        $label   = function_exists( 'wc_attribute_label' ) ? (string) wc_attribute_label( $name, $product ) : $name;
     182                        $lines[] = html_entity_decode( $label, ENT_QUOTES, 'UTF-8' ) . ': ' . html_entity_decode( implode( ', ', $values ), ENT_QUOTES, 'UTF-8' );
     183                }
     184
     185                return $lines;
     186        }
     187
     188        /**
     189         * The short description as plain text on one line, cut to 300 characters.
    94190         *
    95191         * @param object $product WooCommerce product.
    96192         */
    97         private function regular_price_if_on_sale( $product ): string {
    98                 if ( ! method_exists( $product, 'is_on_sale' ) || ! $product->is_on_sale() ) {
     193        private function description( $product ): string {
     194                if ( ! method_exists( $product, 'get_short_description' ) ) {
    99195                        return '';
    100196                }
    101                 if ( ! method_exists( $product, 'get_regular_price' ) ) {
    102                         return '';
    103                 }
    104 
    105                 $regular = $product->get_regular_price();
    106                 $current = method_exists( $product, 'get_price' ) ? $product->get_price() : '';
    107                 if ( '' === (string) $regular || (string) $regular === (string) $current ) {
    108                         return '';
    109                 }
    110 
    111                 return $this->format_amount( $regular );
    112         }
    113 
    114         /**
    115          * Catalog image URL and alt text.
    116          *
    117          * @param int    $product_id Product id.
    118          * @param object $product    WooCommerce product.
    119          * @return array{url:string,alt:string}
    120          */
    121         private function public_image( int $product_id, $product ): array {
    122                 $url = get_the_post_thumbnail_url( $product_id, 'woocommerce_thumbnail' );
    123                 if ( ! is_string( $url ) || '' === $url ) {
    124                         $url = get_the_post_thumbnail_url( $product_id, 'medium' );
    125                 }
    126                 if ( ( ! is_string( $url ) || '' === $url ) && method_exists( $product, 'get_image_id' ) ) {
    127                         $image_id = (int) $product->get_image_id();
    128                         if ( $image_id > 0 ) {
    129                                 $maybe = wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' );
    130                                 $url   = is_string( $maybe ) ? $maybe : '';
    131                         }
    132                 }
    133                 if ( ( ! is_string( $url ) || '' === $url ) && function_exists( 'wc_placeholder_img_src' ) ) {
    134                         $url = (string) wc_placeholder_img_src( 'woocommerce_thumbnail' );
    135                 }
    136 
    137                 $alt      = '';
    138                 $thumb_id = get_post_thumbnail_id( $product_id );
    139                 if ( $thumb_id ) {
    140                         $alt = (string) get_post_meta( (int) $thumb_id, '_wp_attachment_image_alt', true );
    141                 }
    142                 if ( '' === $alt ) {
    143                         $alt = method_exists( $product, 'get_name' ) ? (string) $product->get_name() : '';
    144                 }
    145 
    146                 return array(
    147                         'url' => is_string( $url ) ? $url : '',
    148                         'alt' => $alt,
    149                 );
    150         }
    151 
    152         /**
    153          * Plain-text money for chat cards.
    154          *
    155          * @param mixed $amount Raw amount.
    156          */
    157         private function format_amount( $amount ): string {
    158                 if ( ! is_scalar( $amount ) || '' === (string) $amount ) {
    159                         return '';
    160                 }
    161 
    162                 if ( function_exists( 'wc_price' ) ) {
    163                         $html      = (string) wc_price( $amount );
    164                         $plain     = html_entity_decode( wp_strip_all_tags( $html ), ENT_QUOTES, 'UTF-8' );
    165                         $collapsed = preg_replace( '/\s+/', ' ', $plain );
    166                         if ( ! is_string( $collapsed ) ) {
    167                                 $collapsed = $plain;
    168                         }
    169 
    170                         return trim( $collapsed );
    171                 }
    172 
    173                 return (string) $amount;
    174         }
    175 
    176         /**
    177          * Public products whose names appear in a visitor message.
    178          *
    179          * Used so comparison and add-to-cart cards can appear even when RAG is off
    180          * or retrieval did not return product chunks.
    181          *
    182          * @param string $message Visitor message.
    183          * @param int    $limit   Max products.
    184          * @return list<array<string, mixed>>
    185          */
    186         public function find_mentioned( string $message, int $limit = 6 ): array {
    187                 if ( ! self::is_available() || ! function_exists( 'wc_get_products' ) ) {
    188                         return array();
    189                 }
    190 
    191                 $message = trim( $message );
    192                 if ( '' === $message ) {
    193                         return array();
    194                 }
    195 
    196                 $limit = max( 1, min( 12, $limit ) );
    197                 $ids   = wc_get_products(
    198                         array(
    199                                 'status' => 'publish',
    200                                 'limit'  => 80,
    201                                 'return' => 'ids',
    202                         )
    203                 );
    204 
    205                 $found = array();
    206                 foreach ( $ids as $id ) {
    207                         $card = $this->get_public_product( (int) $id );
    208                         if ( ! is_array( $card ) ) {
    209                                 continue;
    210                         }
    211                         $name = isset( $card['name'] ) ? (string) $card['name'] : '';
    212                         if ( ! self::message_mentions_name( $message, $name ) ) {
    213                                 continue;
    214                         }
    215                         $found[ (int) $id ] = $card;
    216                         if ( count( $found ) >= $limit ) {
    217                                 break;
    218                         }
    219                 }
    220 
    221                 return array_values( $found );
    222         }
    223 
    224         /**
    225          * Whether a product name appears as a whole token in the message.
    226          *
    227          * @param string $message Visitor message.
    228          * @param string $name    Product name.
    229          */
    230         public static function message_mentions_name( string $message, string $name ): bool {
    231                 $name = trim( $name );
    232                 if ( mb_strlen( $name, 'UTF-8' ) < 3 ) {
    233                         return false;
    234                 }
    235 
    236                 $pattern = '/(?<!\p{L})' . preg_quote( $name, '/' ) . '(?!\p{L})/iu';
    237                 return (bool) preg_match( $pattern, $message );
     197
     198                $text = html_entity_decode( wp_strip_all_tags( strip_shortcodes( (string) $product->get_short_description() ) ), ENT_QUOTES, 'UTF-8' );
     199                $text = trim( (string) preg_replace( '/\s+/u', ' ', $text ) );
     200
     201                return mb_substr( $text, 0, self::MAX_DESCRIPTION, 'UTF-8' );
    238202        }
    239203}
  • chathearth/tags/2.0.0/includes/Commerce/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/includes/Frontend/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/includes/Rag/class-builtin-vector-store.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * In-WordPress cosine-similarity vector store.
     3 * The built-in vector store: the passages table of feature 010, searched in two stages (feature 011, research R3-R5,
     4 * R20; FR-004, FR-005, FR-010, FR-011, FR-021).
     5 *
     6 * 1. Coarse: the first 256 numbers of every vector are read in batches of 2,000 rows and scored; the best 256 are kept
     7 *    in a bounded heap. This only runs for the OpenAI `text-embedding-3` models, whose leading numbers form a smaller
     8 *    embedding of the same text, and for vectors of at least 512 numbers.
     9 * 2. Exact: the full vectors of those candidates are read by id and scored by full cosine.
     10 * Any other model gets the exact scan in batches: correct and bounded in memory, only slower. Every search, in
     11 * either way, stops reading new batches after 2 seconds, uses the best passages found so far and logs `scan_budget`.
     12 * Passages of 1.4.9 that still hold their vector as JSON are scored exactly in a pass of their own.
     13 *
     14 * Database rules: every statement goes through `$wpdb->prepare()`, and each table is the `%i` identifier placeholder with
     15 * the raw name from `Schema` as its value. The question's vector never reaches SQL. The batch queries name the primary key as their index
     16 * (`FORCE INDEX (PRIMARY)`): with the table's statistics known, the optimizer otherwise starts from the entries and sorts
     17 * a temporary table, about seven times slower at 10,000 passages (measured 2026-11-23). Each direct query is annotated with its reason: it
     18 * reads this plugin's own table live, and WordPress never caches it.
    419 *
    520 * @package ChatHearth
    … …  
    1429}
    1530
     31use ChatHearth\Ai\Openai_Embedding_Client;
     32use ChatHearth\Kb\Passage_Repository;
     33use ChatHearth\Logger;
     34
    1635/**
    17  * Uses chunk rows already written by the indexer.
     36 * Searches this plugin's own passages.
    1837 */
    1938final class Builtin_Vector_Store implements Vector_Store_Interface {
    2039
    2140        /**
    22          * Repository.
    23          *
    24          * @var Kb_Repository
    25          */
    26         private $repository;
    27 
    28         /**
    29          * Constructor.
    30          *
    31          * @param Kb_Repository|null $repository Repository.
    32          */
    33         public function __construct( ?Kb_Repository $repository = null ) {
    34                 $this->repository = $repository instanceof Kb_Repository ? $repository : new Kb_Repository();
    35         }
    36 
    37         /**
    38          * Insert or replace records.
    39          *
    40          * @param array $records Records.
     41         * Numbers of each vector read in the coarse stage.
     42         */
     43        public const COARSE_DIMS = 256;
     44
     45        /**
     46         * Passages kept after the coarse stage.
     47         */
     48        public const CANDIDATES = 256;
     49
     50        /**
     51         * Rows of one coarse batch.
     52         */
     53        public const BATCH = 2000;
     54
     55        /**
     56         * Most passages a search returns (as 1.4.9).
     57         */
     58        public const MAX_LIMIT = 20;
     59
     60        /**
     61         * Rows of one batch of the exact scan and of the 1.4.9 JSON pass (their rows are read in full).
     62         */
     63        private const EXACT_BATCH = 500;
     64
     65        /**
     66         * Seconds after which the exact scan stops reading new batches.
     67         */
     68        private const SCAN_BUDGET = 2.0;
     69
     70        /**
     71         * The shortest vector and the model family for which the coarse stage is used.
     72         */
     73        private const COARSE_MIN_DIMS = 512;
     74        private const COARSE_MODELS   = 'text-embedding-3-';
     75
     76        /**
     77         * Returns the time in seconds (replaced in tests).
     78         *
     79         * @var callable
     80         */
     81        private $clock;
     82
     83        /**
     84         * @param callable|null $clock Returns the time in seconds as a float; default: `microtime( true )`.
     85         */
     86        public function __construct( ?callable $clock = null ) {
     87                $this->clock = $clock ?? static function (): float {
     88                        return microtime( true );
     89                };
     90        }
     91
     92        /**
     93         * The sync writes the tables itself (as in 1.4.9), so there is nothing to do.
     94         *
     95         * @param list<array{id:string,embedding:list<float>,content:string,meta:array<string,mixed>}> $records Records.
    4196         */
    4297        public function upsert( array $records ): bool {
    4398                unset( $records );
    44                 // Chunks + embeddings are persisted by the indexer via Kb_Repository::replace_chunks().
     99
    45100                return true;
    46101        }
    47102
    48103        /**
    49          * Delete records by id.
    50          *
    51          * @param array $ids Vector ids.
     104         * The sync writes the tables itself (as in 1.4.9), so there is nothing to do.
     105         *
     106         * @param array<int, string> $ids Ids.
    52107         */
    53108        public function delete( array $ids ): bool {
    54109                unset( $ids );
     110
    55111                return true;
    56112        }
    57113
    58114        /**
    59          * Nearest neighbours.
    60          *
    61          * @param array $embedding Query vector.
    62          * @param int   $limit     Max hits.
    63          * @return array
     115         * Whether the tables are at the current version (FR-021).
     116         */
     117        public function ping(): bool {
     118                return Schema::is_current();
     119        }
     120
     121        /**
     122         * The passages nearest to a question, best first.
     123         *
     124         * @param array<int, float> $embedding The question's vector.
     125         * @param int               $limit     Most passages; 1 to 20.
     126         * @return list<array{id:string,score:float,content:string,meta:array<string,mixed>}>
     127         * @throws \RuntimeException With the message `db_error` when the database fails.
    64128         */
    65129        public function query( array $embedding, int $limit = 5 ): array {
    66                 $limit  = max( 1, min( 20, $limit ) );
    67                 $rows   = $this->repository->all_chunk_embeddings();
    68                 $scored = array();
    69 
     130                $limit = max( 1, min( self::MAX_LIMIT, $limit ) );
     131                $dims  = count( $embedding );
     132                if ( 0 === $dims ) {
     133                        return array();
     134                }
     135
     136                // The question as a list that starts at 1, like the result of unpack().
     137                $question = array();
     138                $norm     = 0.0;
     139                $position = 0;
     140                foreach ( $embedding as $number ) {
     141                        $value = (float) $number;
     142                        if ( ! is_finite( $value ) ) {
     143                                return array();
     144                        }
     145                        $question[ ++$position ] = $value;
     146                        $norm                   += $value * $value;
     147                }
     148                $norm = sqrt( $norm );
     149                if ( $norm <= 0.0 ) {
     150                        return array();
     151                }
     152
     153                $model  = Openai_Embedding_Client::resolve_model();
     154                $legacy = Openai_Embedding_Client::DEFAULT_MODEL === $model;
     155                $final  = new Top_K_Heap( $limit );
     156
     157                if ( $dims >= self::COARSE_MIN_DIMS && 0 === strpos( $model, self::COARSE_MODELS ) ) {
     158                        $candidates = $this->coarse_candidates( $question, $dims, $model, $legacy );
     159                        $this->score_exact( $this->vectors_of( $candidates ), $question, $norm, $dims, $final );
     160                } else {
     161                        $this->scan( $question, $norm, $dims, $model, $legacy, $final );
     162                }
     163
     164                if ( $legacy ) {
     165                        $this->score_json_rows( $question, $norm, $dims, $final );
     166                }
     167
     168                return $this->hits( $final->best_first() );
     169        }
     170
     171        /**
     172         * The coarse stage: ids of the best 256 passages by the first 256 numbers.
     173         *
     174         * @param array<int, float> $question The question, indexed from 1.
     175         * @param int               $dims     Vector length.
     176         * @param string            $model    Current model.
     177         * @param bool              $legacy   Whether rows without a model (1.4.9) count.
     178         * @return int[]
     179         */
     180        private function coarse_candidates( array $question, int $dims, string $model, bool $legacy ): array {
     181                $head      = array_slice( $question, 0, self::COARSE_DIMS, true );
     182                $head_norm = 0.0;
     183                foreach ( $head as $number ) {
     184                        $head_norm += $number * $number;
     185                }
     186                $head_norm = sqrt( $head_norm );
     187                $heap      = new Top_K_Heap( self::CANDIDATES );
     188                if ( $head_norm <= 0.0 ) {
     189                        // The question has no weight in the leading numbers: the coarse scores would all be zero.
     190                        return array();
     191                }
     192
     193                $after   = 0;
     194                $cached  = wp_using_ext_object_cache();
     195                $version = $cached ? Passage_Repository::index_version() : 0;
     196                $started = (float) call_user_func( $this->clock );
     197
     198                do {
     199                        $key  = 'heads:' . $version . ':' . $model . ':' . $dims . ':' . $after;
     200                        $rows = $cached ? wp_cache_get( $key, Passage_Repository::CACHE_GROUP ) : false;
     201                        if ( is_array( $rows ) ) {
     202                                $count = count( $rows );
     203                                $this->score_heads( $rows, $head, $head_norm, $heap, $after );
     204                                unset( $rows );
     205                                if ( $this->budget_is_used( $count, self::BATCH, $started ) ) {
     206                                        break;
     207                                }
     208                                continue;
     209                        }
     210
     211                        $rows = $this->read(
     212                                static function ( $db ) use ( $legacy, $dims, $model, $after ) {
     213                                        if ( $legacy ) {
     214                                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     215                                                        $db->prepare(
     216                                                                "SELECT c.id, SUBSTRING(c.embedding_bin, 1, 1024) FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model IN (%s, '') AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     217                                                                Schema::chunks_table(),
     218                                                                Schema::entries_table(),
     219                                                                $dims,
     220                                                                $model,
     221                                                                $after,
     222                                                                self::BATCH
     223                                                        ),
     224                                                        ARRAY_N
     225                                                );
     226                                        }
     227
     228                                        return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     229                                                $db->prepare(
     230                                                        "SELECT c.id, SUBSTRING(c.embedding_bin, 1, 1024) FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model = %s AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     231                                                        Schema::chunks_table(),
     232                                                        Schema::entries_table(),
     233                                                        $dims,
     234                                                        $model,
     235                                                        $after,
     236                                                        self::BATCH
     237                                                ),
     238                                                ARRAY_N
     239                                        );
     240                                }
     241                        );
     242                        if ( $cached ) {
     243                                // One hour; the version in the key makes it unused as soon as the index changes.
     244                                wp_cache_set( $key, $rows, Passage_Repository::CACHE_GROUP, HOUR_IN_SECONDS );
     245                        }
     246                        $count = count( $rows );
     247                        $this->score_heads( $rows, $head, $head_norm, $heap, $after );
     248                        unset( $rows );
     249                        if ( $this->budget_is_used( $count, self::BATCH, $started ) ) {
     250                                break;
     251                        }
     252                } while ( self::BATCH === $count );
     253
     254                return array_map(
     255                        static function ( array $entry ): int {
     256                                return $entry[1];
     257                        },
     258                        $heap->best_first()
     259                );
     260        }
     261
     262        /**
     263         * Whether the 2 second budget of a search is used up while rows are left to read. The search then stops reading new
     264         * batches and works with the best passages found so far (lower ids first); one log line holds only the code.
     265         *
     266         * @param int   $count   Rows of the batch just read.
     267         * @param int   $size    Rows a full batch holds (a short batch is the last one).
     268         * @param float $started Start of the search.
     269         */
     270        private function budget_is_used( int $count, int $size, float $started ): bool {
     271                if ( $size !== $count || (float) call_user_func( $this->clock ) - $started < self::SCAN_BUDGET ) {
     272                        return false;
     273                }
     274                Logger::warning( 'knowledge base search failed', array( 'code' => 'scan_budget' ) );
     275
     276                return true;
     277        }
     278
     279        /**
     280         * Score one coarse batch against the question's first 256 numbers and offer the scores to the heap.
     281         *
     282         * @param array<int, array<int, mixed>> $rows      Rows of row id and the first 1,024 bytes of the vector.
     283         * @param array<int, float>             $head      The question's first 256 numbers, indexed from 1.
     284         * @param float                         $head_norm Length of that part.
     285         * @param Top_K_Heap                    $heap      Receives the scores.
     286         * @param int                           $after     Set to the last row id of the batch.
     287         */
     288        private function score_heads( array $rows, array $head, float $head_norm, Top_K_Heap $heap, int &$after ): void {
    70289                foreach ( $rows as $row ) {
    71                         $stored = isset( $row['embedding'] ) ? json_decode( (string) $row['embedding'], true ) : null;
    72                         if ( ! is_array( $stored ) || empty( $stored ) ) {
     290                        $id     = (int) $row[0];
     291                        $after  = $id;
     292                        $values = unpack( 'g' . self::COARSE_DIMS, (string) $row[1] );
     293                        if ( ! is_array( $values ) || count( $values ) !== self::COARSE_DIMS ) {
    73294                                continue;
    74295                        }
    75                         $vector   = array_map( 'floatval', $stored );
    76                         $score    = self::cosine( $embedding, $vector );
    77                         $scored[] = array(
    78                                 'id'      => (string) $row['chunk_id'],
    79                                 'score'   => $score,
    80                                 'content' => (string) $row['content'],
     296                        $dot  = 0.0;
     297                        $size = 0.0;
     298                        foreach ( $values as $i => $number ) {
     299                                $dot  += $number * $head[ $i ];
     300                                $size += $number * $number;
     301                        }
     302                        $heap->offer( $size > 0.0 ? $dot / ( sqrt( $size ) * $head_norm ) : 0.0, $id );
     303                }
     304        }
     305
     306        /**
     307         * The full vectors of passages, by row id.
     308         *
     309         * @param int[] $ids Row ids (at most 256).
     310         * @return array<int, array{0: int, 1: string, 2: float}> Id, binary vector and stored norm.
     311         */
     312        private function vectors_of( array $ids ): array {
     313                if ( array() === $ids ) {
     314                        return array();
     315                }
     316
     317                $rows = $this->read(
     318                        static function ( $db ) use ( $ids ) {
     319                                // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- One placeholder per id, counted by the `array_fill()` call.
     320                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     321                                        $db->prepare(
     322                                                "SELECT c.id, c.embedding_bin, c.norm FROM %i c INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.id IN ( " . implode( ', ', array_fill( 0, count( $ids ), '%d' ) ) . ' )',
     323                                                array_merge( array( Schema::chunks_table(), Schema::entries_table() ), $ids )
     324                                        ),
     325                                        ARRAY_N
     326                                );
     327                                // phpcs:enable
     328                        }
     329                );
     330
     331                $vectors = array();
     332                foreach ( $rows as $row ) {
     333                        $vectors[] = array( (int) $row[0], (string) $row[1], (float) $row[2] );
     334                }
     335
     336                return $vectors;
     337        }
     338
     339        /**
     340         * Score full vectors by cosine and offer them to the heap.
     341         *
     342         * @param array<int, array{0: int, 1: string, 2: float}> $vectors  Id, binary vector and stored norm.
     343         * @param array<int, float>                              $question The question, indexed from 1.
     344         * @param float                                          $norm     Length of the question.
     345         * @param int                                            $dims     Vector length.
     346         * @param Top_K_Heap                                     $heap     Receives the scores.
     347         */
     348        private function score_exact( array $vectors, array $question, float $norm, int $dims, Top_K_Heap $heap ): void {
     349                foreach ( $vectors as $vector ) {
     350                        if ( $vector[2] <= 0.0 || strlen( $vector[1] ) !== $dims * 4 ) {
     351                                continue;
     352                        }
     353                        $values = unpack( 'g' . $dims, $vector[1] );
     354                        if ( ! is_array( $values ) ) {
     355                                continue;
     356                        }
     357                        $dot = 0.0;
     358                        foreach ( $values as $i => $number ) {
     359                                $dot += $number * $question[ $i ];
     360                        }
     361                        $heap->offer( $dot / ( $norm * $vector[2] ), $vector[0] );
     362                }
     363        }
     364
     365        /**
     366         * The exact scan in batches (models outside the `text-embedding-3` family, and short vectors). It stops reading new
     367         * batches after two seconds and logs `scan_budget`.
     368         *
     369         * @param array<int, float> $question The question, indexed from 1.
     370         * @param float             $norm     Length of the question.
     371         * @param int               $dims     Vector length.
     372         * @param string            $model    Current model.
     373         * @param bool              $legacy   Whether rows without a model (1.4.9) count.
     374         * @param Top_K_Heap        $heap     Receives the scores.
     375         */
     376        private function scan( array $question, float $norm, int $dims, string $model, bool $legacy, Top_K_Heap $heap ): void {
     377                $started = (float) call_user_func( $this->clock );
     378                $after   = 0;
     379
     380                do {
     381                        $rows    = $this->read(
     382                                static function ( $db ) use ( $legacy, $dims, $model, $after ) {
     383                                        if ( $legacy ) {
     384                                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     385                                                        $db->prepare(
     386                                                                "SELECT c.id, c.embedding_bin, c.norm FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model IN (%s, '') AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     387                                                                Schema::chunks_table(),
     388                                                                Schema::entries_table(),
     389                                                                $dims,
     390                                                                $model,
     391                                                                $after,
     392                                                                self::EXACT_BATCH
     393                                                        ),
     394                                                        ARRAY_N
     395                                                );
     396                                        }
     397
     398                                        return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     399                                                $db->prepare(
     400                                                        "SELECT c.id, c.embedding_bin, c.norm FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model = %s AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     401                                                        Schema::chunks_table(),
     402                                                        Schema::entries_table(),
     403                                                        $dims,
     404                                                        $model,
     405                                                        $after,
     406                                                        self::EXACT_BATCH
     407                                                ),
     408                                                ARRAY_N
     409                                        );
     410                                }
     411                        );
     412                        $vectors = array();
     413                        foreach ( $rows as $row ) {
     414                                $vectors[] = array( (int) $row[0], (string) $row[1], (float) $row[2] );
     415                                $after     = (int) $row[0];
     416                        }
     417                        $count = count( $rows );
     418                        unset( $rows );
     419                        $this->score_exact( $vectors, $question, $norm, $dims, $heap );
     420                        unset( $vectors );
     421
     422                        if ( $this->budget_is_used( $count, self::EXACT_BATCH, $started ) ) {
     423                                break;
     424                        }
     425                } while ( self::EXACT_BATCH === $count );
     426        }
     427
     428        /**
     429         * Passages of 1.4.9 that still hold their vector as JSON text, scored exactly. Once the conversion of feature 010
     430         * has finished there are none.
     431         *
     432         * @param array<int, float> $question The question, indexed from 1.
     433         * @param float             $norm     Length of the question.
     434         * @param int               $dims     Vector length.
     435         * @param Top_K_Heap        $heap     Receives the scores.
     436         */
     437        private function score_json_rows( array $question, float $norm, int $dims, Top_K_Heap $heap ): void {
     438                $after = 0;
     439
     440                do {
     441                        $rows = $this->read(
     442                                static function ( $db ) use ( $after ) {
     443                                        return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     444                                                $db->prepare(
     445                                                        "SELECT c.id, c.embedding FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NULL AND c.embedding IS NOT NULL AND c.model = '' AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     446                                                        Schema::chunks_table(),
     447                                                        Schema::entries_table(),
     448                                                        $after,
     449                                                        self::EXACT_BATCH
     450                                                ),
     451                                                ARRAY_N
     452                                        );
     453                                }
     454                        );
     455                        foreach ( $rows as $row ) {
     456                                $after  = (int) $row[0];
     457                                $vector = Vector_Codec::read_row( array( 'embedding' => (string) $row[1] ) );
     458                                if ( null === $vector || count( $vector ) !== $dims ) {
     459                                        continue;
     460                                }
     461                                $length = Vector_Codec::norm( $vector );
     462                                if ( $length <= 0.0 ) {
     463                                        continue;
     464                                }
     465                                $dot = 0.0;
     466                                foreach ( $vector as $i => $number ) {
     467                                        $dot += $number * $question[ $i + 1 ];
     468                                }
     469                                $heap->offer( $dot / ( $norm * $length ), $after );
     470                        }
     471                        $count = count( $rows );
     472                        unset( $rows );
     473                } while ( self::EXACT_BATCH === $count );
     474        }
     475
     476        /**
     477         * The 1.4.9 hits of the winning passages.
     478         *
     479         * @param array<int, array{0: float, 1: int}> $best Score and row id, best first.
     480         * @return list<array{id:string,score:float,content:string,meta:array<string,mixed>}>
     481         */
     482        private function hits( array $best ): array {
     483                if ( array() === $best ) {
     484                        return array();
     485                }
     486
     487                $ids   = array_column( $best, 1 );
     488                $rows  = $this->read(
     489                        static function ( $db ) use ( $ids ) {
     490                                // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- One placeholder per id, counted by the `array_fill()` call.
     491                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     492                                        $db->prepare(
     493                                                'SELECT c.id, c.chunk_id, c.entry_id, e.source_id FROM %i c INNER JOIN %i e ON e.id = c.entry_id WHERE c.id IN ( ' . implode( ', ', array_fill( 0, count( $ids ), '%d' ) ) . ' )',
     494                                                array_merge( array( Schema::chunks_table(), Schema::entries_table() ), $ids )
     495                                        ),
     496                                        ARRAY_N
     497                                );
     498                                // phpcs:enable
     499                        }
     500                );
     501                $by_id = array();
     502                foreach ( $rows as $row ) {
     503                        $by_id[ (int) $row[0] ] = $row;
     504                }
     505
     506                $hits = array();
     507                foreach ( $best as $entry ) {
     508                        if ( ! isset( $by_id[ $entry[1] ] ) ) {
     509                                continue;
     510                        }
     511                        $row    = $by_id[ $entry[1] ];
     512                        $hits[] = array(
     513                                'id'      => (string) $row[1],
     514                                'score'   => $entry[0],
     515                                'content' => '',
    81516                                'meta'    => array(
    82                                         'source_id'   => (string) $row['source_id'],
    83                                         'title'       => (string) $row['title'],
    84                                         'url'         => (string) $row['url'],
    85                                         'post_type'   => (string) $row['post_type'],
    86                                         'object_type' => (string) $row['object_type'],
    87                                         'object_id'   => (int) $row['object_id'],
     517                                        'entry_id'  => (int) $row[2],
     518                                        'source_id' => (string) $row[3],
    88519                                ),
    89520                        );
    90521                }
    91522
    92                 usort(
    93                         $scored,
    94                         static function ( array $a, array $b ): int {
    95                                 if ( $a['score'] === $b['score'] ) {
    96                                         return 0;
    97                                 }
    98                                 return ( $a['score'] < $b['score'] ) ? 1 : -1;
    99                         }
    100                 );
    101 
    102                 return array_slice( $scored, 0, $limit );
    103         }
    104 
    105         /**
    106          * {@inheritdoc}
    107          */
    108         public function ping(): bool {
    109                 return true;
    110         }
    111 
    112         /**
    113          * Cosine similarity.
    114          *
    115          * @param array $a Vector a.
    116          * @param array $b Vector b.
    117          */
    118         public static function cosine( array $a, array $b ): float {
    119                 $n   = min( count( $a ), count( $b ) );
    120                 $dot = 0.0;
    121                 $na  = 0.0;
    122                 $nb  = 0.0;
    123                 for ( $i = 0; $i < $n; $i++ ) {
    124                         $va   = (float) $a[ $i ];
    125                         $vb   = (float) $b[ $i ];
    126                         $dot += $va * $vb;
    127                         $na  += $va * $va;
    128                         $nb  += $vb * $vb;
    129                 }
    130                 $den = sqrt( $na ) * sqrt( $nb );
    131                 if ( $den <= 0.0 ) {
    132                         return 0.0;
    133                 }
    134 
    135                 return $dot / $den;
     523                return $hits;
     524        }
     525
     526        /**
     527         * Run a SELECT and return its rows as lists. A database error never prints: it becomes an exception that the
     528         * retriever turns into "no matching passages".
     529         *
     530         * @param callable $query Receives `$wpdb` and returns the rows of one prepared statement (`ARRAY_N`), or null.
     531         * @return array<int, array<int, mixed>>
     532         * @throws \RuntimeException With the message `db_error`.
     533         */
     534        private function read( callable $query ): array {
     535                global $wpdb;
     536
     537                $previous = $wpdb->suppress_errors( true );
     538                try {
     539                        $rows = $query( $wpdb );
     540                } finally {
     541                        $wpdb->suppress_errors( $previous );
     542                }
     543                if ( ! is_array( $rows ) || '' !== $wpdb->last_error ) {
     544                        throw new \RuntimeException( 'db_error' );
     545                }
     546
     547                return $rows;
    136548        }
    137549}
  • chathearth/tags/2.0.0/includes/Rag/class-retriever.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Retrieve KB chunks and inject them into the system prompt.
     3 * Finds the passages that answer a question (feature 011, research R2, R8, R9, R13, R15; FR-001 to FR-006, FR-016,
     4 * FR-017, FR-019).
     5 *
     6 * It embeds the question once, asks the vector store for the best passages, checks every hit, drops the items that are
     7 * no longer public (the gate) and reads the text of the chosen passages from the local index. It never throws: every
     8 * failure becomes a `Retrieval_Result` with an error code, and the assistant then gets the "no matching passages"
     9 * instruction. The question, the passages and any message of a store are never logged.
    410 *
    511 * @package ChatHearth
    … …  
    1420}
    1521
    16 use ChatHearth\Commerce\Product_Catalog;
    17 use ChatHearth\Options;
     22use ChatHearth\Ai\Embedding_Client;
     23use ChatHearth\Ai\Openai_Embedding_Client;
     24use ChatHearth\Kb\Entry_Repository;
     25use ChatHearth\Kb\Passage_Repository;
     26use ChatHearth\Logger;
    1827
    1928/**
    20  * Query-time RAG.
     29 * Question to passages.
    2130 */
    2231final class Retriever {
    2332
    2433        /**
    25          * Shared instance (so the REST controller can read last hits).
    26          *
    27          * @var self|null
    28          */
    29         private static $instance = null;
    30 
    31         /**
    32          * Last citation list.
    33          *
    34          * @var list<array<string, mixed>>
    35          */
    36         private $last_sources = array();
    37 
    38         /**
    39          * Last matched products.
    40          *
    41          * @var list<array<string, mixed>>
    42          */
    43         private $last_products = array();
    44 
    45         /**
    46          * Instance.
    47          */
    48         public static function instance(): self {
    49                 if ( null === self::$instance ) {
    50                         self::$instance = new self();
    51                 }
    52 
    53                 return self::$instance;
    54         }
    55 
    56         /**
    57          * Register filter.
    58          */
    59         public function register(): void {
    60                 add_filter( 'chathearth_system_prompt', array( $this, 'inject' ), 20, 3 );
    61         }
    62 
    63         /**
    64          * Sources from the last generate call.
    65          *
    66          * @return list<array<string, mixed>>
    67          */
    68         public function last_sources(): array {
    69                 return $this->last_sources;
    70         }
    71 
    72         /**
    73          * Products from the last generate call.
    74          *
    75          * @return list<array<string, mixed>>
    76          */
    77         public function last_products(): array {
    78                 return $this->last_products;
    79         }
    80 
    81         /**
    82          * Inject retrieved context and matching catalog products.
    83          *
    84          * @param string               $prompt  System prompt.
    85          * @param string               $message User message.
    86          * @param array<string, mixed> $history History.
    87          */
    88         public function inject( string $prompt, string $message, array $history ): string {
    89                 unset( $history );
    90                 $catalog             = new Product_Catalog();
    91                 $products            = array();
    92                 $mentioned           = array();
    93                 $this->last_sources  = array();
    94                 $this->last_products = array();
    95 
    96                 foreach ( $catalog->find_mentioned( $message ) as $card ) {
    97                         $mentioned[ (int) $card['id'] ] = $card;
    98                         $products[ (int) $card['id'] ]  = $card;
    99                 }
    100 
    101                 if ( Options::is_rag_enabled() ) {
    102                         $hits = $this->search( $message );
    103                         if ( empty( $hits ) ) {
    104                                 $prompt .= "\n\n## Retrieved knowledge\nNo matching knowledge-base passages were found. Stay within the website context above. If you cannot answer from that context, say so.\n";
    105                         } else {
    106                                 $blocks  = array();
    107                                 $sources = array();
    108 
    109                                 foreach ( $hits as $hit ) {
    110                                         $meta  = $hit['meta'];
    111                                         $title = isset( $meta['title'] ) ? (string) $meta['title'] : '';
    112                                         $url   = isset( $meta['url'] ) ? (string) $meta['url'] : '';
    113                                         $type  = isset( $meta['post_type'] ) && '' !== (string) $meta['post_type'] ? (string) $meta['post_type'] : (string) ( $meta['object_type'] ?? 'content' );
    114 
    115                                         if ( '' !== $url && ! isset( $sources[ $url ] ) ) {
    116                                                 $sources[ $url ] = array(
    117                                                         'title' => $title,
    118                                                         'url'   => $url,
    119                                                         'type'  => $type,
    120                                                 );
    121                                         }
    122 
    123                                         $object_id = isset( $meta['object_id'] ) ? (int) $meta['object_id'] : 0;
    124                                         if ( $object_id > 0 && ( 'product' === $type || ( isset( $meta['post_type'] ) && 'product' === $meta['post_type'] ) ) ) {
    125                                                 $product = $catalog->get_public_product( $object_id );
    126                                                 if ( is_array( $product ) ) {
    127                                                         $products[ $object_id ] = $product;
    128                                                 }
    129                                         }
    130 
    131                                         $blocks[] = '### ' . ( '' !== $title ? $title : 'Source' ) . "\n" . ( '' !== $url ? 'URL: ' . $url . "\n" : '' ) . trim( (string) $hit['content'] );
    132                                 }
    133 
    134                                 $this->last_sources = array_values( $sources );
    135 
    136                                 $joined = implode( "\n\n---\n\n", $blocks );
    137                                 if ( mb_strlen( $joined, 'UTF-8' ) > 12000 ) {
    138                                         $joined = mb_substr( $joined, 0, 12000, 'UTF-8' );
    139                                 }
    140 
    141                                 $prompt .= "\n\n## Retrieved knowledge\nUse the following passages from this website. Cite them with Markdown links. If they are not enough, say you do not have that information.\n\n" . $joined . "\n";
    142                         }
    143                 }
    144 
    145                 if ( count( $mentioned ) >= 2 && $this->looks_like_comparison( $message ) ) {
    146                         $this->last_products = array_values( $mentioned );
    147                 } else {
    148                         $this->last_products = array_slice( array_values( $products ), 0, 6 );
    149                 }
    150                 $prompt .= $this->catalog_prompt( $this->last_products );
    151 
    152                 return $prompt;
    153         }
    154 
    155         /**
    156          * Compact catalog facts for comparison and cart.
    157          *
    158          * @param list<array<string, mixed>> $products Products.
    159          */
    160         private function catalog_prompt( array $products ): string {
    161                 if ( empty( $products ) ) {
    162                         return '';
    163                 }
    164 
    165                 $lines = array(
    166                         "\n\n## Matching catalog products",
    167                         'Use these facts for comparisons and cart actions. Include Markdown links. Do not invent prices or stock.',
    168                 );
    169                 foreach ( $products as $product ) {
    170                         $name    = isset( $product['name'] ) ? (string) $product['name'] : 'Product';
    171                         $url     = isset( $product['url'] ) ? (string) $product['url'] : '';
    172                         $price   = isset( $product['price'] ) ? (string) $product['price'] : '';
    173                         $stock   = ! empty( $product['in_stock'] ) ? 'in stock' : 'out of stock';
    174                         $buy     = ! empty( $product['purchasable'] ) ? 'can be added to cart' : 'cannot be added to cart from chat';
    175                         $label   = '' !== $url ? '[' . $name . '](' . $url . ')' : $name;
    176                         $lines[] = '- ' . $label . ' — ' . $price . ' — ' . $stock . ' — ' . $buy;
    177                 }
    178 
    179                 return implode( "\n", $lines ) . "\n";
    180         }
    181 
    182         /**
    183          * Embed the query and search the configured store.
    184          *
    185          * @param string $message User message.
    186          * @return list<array{id:string,score:float,content:string,meta:array<string, mixed>}>
    187          */
    188         public function search( string $message ): array {
    189                 $embedder = new Embedding_Client();
    190                 $vector   = $embedder->embed( $message );
    191                 if ( is_wp_error( $vector ) ) {
     34         * Most hits of a store that are read (as the 1.4.9 built-in limit).
     35         */
     36        private const MAX_HITS = 20;
     37
     38        /**
     39         * Extra hits asked for, so a few dropped items do not shorten the list.
     40         */
     41        private const SPARE_HITS = 8;
     42
     43        /**
     44         * Most passages ever used.
     45         */
     46        private const MAX_COUNT = 12;
     47
     48        /**
     49         * @var Embedding_Client
     50         */
     51        private $client;
     52
     53        /**
     54         * @var Passage_Repository
     55         */
     56        private $passages;
     57
     58        /**
     59         * @var Entry_Repository
     60         */
     61        private $entries;
     62
     63        /**
     64         * @var Source_Gate
     65         */
     66        private $gate;
     67
     68        /**
     69         * @var Comparison_Detector
     70         */
     71        private $detector;
     72
     73        /**
     74         * @param Embedding_Client    $client   Turns the question into a vector.
     75         * @param Passage_Repository  $passages Local passages.
     76         * @param Entry_Repository    $entries  Local entries (the text of an item).
     77         * @param Source_Gate         $gate     Drops items that stopped being public.
     78         * @param Comparison_Detector $detector Recognises a comparison question.
     79         */
     80        public function __construct( Embedding_Client $client, Passage_Repository $passages, Entry_Repository $entries, Source_Gate $gate, Comparison_Detector $detector ) {
     81                $this->client   = $client;
     82                $this->passages = $passages;
     83                $this->entries  = $entries;
     84                $this->gate     = $gate;
     85                $this->detector = $detector;
     86        }
     87
     88        /**
     89         * Embed, search, check the hits, gate, and read the texts.
     90         *
     91         * @param string $question The visitor's question.
     92         * @param int    $top_k    The setting `rag_top_k`; a comparison asks for twice as many, at most 12.
     93         */
     94        public function retrieve( string $question, int $top_k ): Retrieval_Result {
     95                $top_k = max( 1, min( self::MAX_COUNT, $top_k ) );
     96
     97                try {
     98                        $comparison = $this->detector->is_comparison( $question );
     99                } catch ( \Throwable $e ) {
     100                        $comparison = false;
     101                }
     102                $count = $comparison ? min( self::MAX_COUNT, 2 * $top_k ) : $top_k;
     103
     104                try {
     105                        $vectors = $this->client->embed( array( $question ), Openai_Embedding_Client::resolve_model() );
     106                } catch ( \Throwable $e ) {
     107                        return $this->failed( 'embed_error', $count, $comparison, $e );
     108                }
     109                if ( $vectors instanceof \WP_Error ) {
     110                        return $this->failed( 'embed_' . (string) preg_replace( '/[^a-z0-9_]/', '', strtolower( (string) $vectors->get_error_code() ) ), $count, $comparison );
     111                }
     112                $vector = $this->first_vector( $vectors );
     113                if ( null === $vector ) {
     114                        return $this->failed( 'embed_invalid_vector', $count, $comparison );
     115                }
     116
     117                $store = Vector_Store_Factory::make();
     118                try {
     119                        $hits = $this->as_list( $store->query( $vector, min( self::MAX_HITS, $count + self::SPARE_HITS ) ) );
     120                } catch ( \Throwable $e ) {
     121                        $code = Vector_Store_Factory::is_builtin( $store ) && 'db_error' === $e->getMessage() ? 'db_error' : 'store_error';
     122
     123                        return $this->failed( $code, $count, $comparison, $e );
     124                }
     125                if ( null === $hits ) {
     126                        return $this->failed( 'store_error', $count, $comparison );
     127                }
     128
     129                try {
     130                        return Retrieval_Result::found( $this->choose( $this->valid_hits( $hits ), $count ), $count, $comparison );
     131                } catch ( \Throwable $e ) {
     132                        return $this->failed( 'db_error', $count, $comparison, $e );
     133                }
     134        }
     135
     136        /**
     137         * The vector of the question from an embedding client's answer, or null when there is none.
     138         *
     139         * @param mixed $vectors What the client returned.
     140         * @return array<int, float>|null
     141         */
     142        private function first_vector( $vectors ): ?array {
     143                return is_array( $vectors ) && isset( $vectors[0] ) && is_array( $vectors[0] ) ? $vectors[0] : null;
     144        }
     145
     146        /**
     147         * An answer of a store as a list, or null. The interface promises a list, but a replacement store may answer with
     148         * anything.
     149         *
     150         * @param mixed $answer What the store returned.
     151         * @return array<mixed>|null
     152         */
     153        private function as_list( $answer ): ?array {
     154                return is_array( $answer ) ? $answer : null;
     155        }
     156
     157        /**
     158         * The first 20 hits that have the shape of a 1.4.9 hit, each passage once.
     159         *
     160         * @param array<mixed> $hits What the store answered.
     161         * @return array<int, array{id: string, score: float}>
     162         */
     163        private function valid_hits( array $hits ): array {
     164                $valid = array();
     165                $seen  = array();
     166                foreach ( array_slice( array_values( $hits ), 0, self::MAX_HITS ) as $hit ) {
     167                        if ( ! is_array( $hit ) || ! isset( $hit['id'], $hit['score'], $hit['content'], $hit['meta'] ) ) {
     168                                continue;
     169                        }
     170                        if ( ! is_string( $hit['id'] ) || '' === $hit['id'] || isset( $seen[ $hit['id'] ] ) ) {
     171                                continue;
     172                        }
     173                        if ( ( ! is_int( $hit['score'] ) && ! is_float( $hit['score'] ) ) || ! is_finite( (float) $hit['score'] ) ) {
     174                                continue;
     175                        }
     176                        if ( ! is_string( $hit['content'] ) || ! is_array( $hit['meta'] ) ) {
     177                                continue;
     178                        }
     179                        $seen[ $hit['id'] ] = true;
     180                        $valid[]            = array(
     181                                'id'    => $hit['id'],
     182                                'score' => (float) $hit['score'],
     183                        );
     184                }
     185
     186                return $valid;
     187        }
     188
     189        /**
     190         * The chosen passages: local rows by id, the gate in rank order, and the text of each from the local index.
     191         *
     192         * @param array<int, array{id: string, score: float}> $hits  Checked hits, best first.
     193         * @param int                                         $count Passages wanted.
     194         * @return Retrieved_Passage[]
     195         */
     196        private function choose( array $hits, int $count ): array {
     197                global $wpdb;
     198
     199                if ( array() === $hits ) {
    192200                        return array();
    193201                }
    194202
    195                 $limit = (int) Options::get( 'rag_top_k', 6 );
    196                 $limit = max( 1, min( 12, $limit ) );
    197                 if ( $this->looks_like_comparison( $message ) ) {
    198                         $limit = min( 12, max( $limit, $limit * 2 ) );
    199                 }
    200 
    201                 $hits = Vector_Store_Factory::make()->query( $vector, $limit );
    202                 $repo = new Kb_Repository();
    203 
    204                 foreach ( $hits as $i => $hit ) {
    205                         $local = $repo->get_chunk( (string) $hit['id'] );
    206                         if ( is_array( $local ) && ! empty( $local['content'] ) ) {
    207                                 $hits[ $i ]['content'] = (string) $local['content'];
    208                         }
    209                 }
    210 
    211                 return $hits;
    212         }
    213 
    214         /**
    215          * Whether the user is asking for a comparison.
    216          *
    217          * @param string $message Message.
    218          */
    219         private function looks_like_comparison( string $message ): bool {
    220                 return (bool) preg_match( '/\b(compar(?:e|ison)|vs\.?|versus|difference|better|which (?:one|product))\b/i', $message );
     203                $rows = $this->passages->find_by_chunk_ids( array_column( $hits, 'id' ) );
     204                if ( '' !== (string) $wpdb->last_error ) {
     205                        throw new \RuntimeException( 'db_error' );
     206                }
     207
     208                $allowed   = array();
     209                $markdowns = array();
     210                $chosen    = array();
     211                foreach ( $hits as $hit ) {
     212                        if ( count( $chosen ) >= $count ) {
     213                                break;
     214                        }
     215                        if ( ! isset( $rows[ $hit['id'] ] ) ) {
     216                                continue; // The passage is not in the local index: the hit is stale.
     217                        }
     218                        $row      = $rows[ $hit['id'] ];
     219                        $entry_id = (int) $row['entry_id'];
     220                        if ( ! isset( $allowed[ $entry_id ] ) ) {
     221                                $allowed[ $entry_id ] = $this->gate->allows( $row );
     222                        }
     223                        if ( ! $allowed[ $entry_id ] ) {
     224                                continue;
     225                        }
     226                        if ( ! isset( $markdowns[ $entry_id ] ) ) {
     227                                $markdowns[ $entry_id ] = $this->entries->markdown( $entry_id );
     228                        }
     229                        $text = $this->passages->text( $row, $markdowns[ $entry_id ] );
     230                        if ( '' === trim( $text ) ) {
     231                                continue;
     232                        }
     233
     234                        $object_type = (string) $row['object_type'];
     235                        $post_type   = (string) $row['post_type'];
     236                        $chosen[]    = new Retrieved_Passage(
     237                                (string) $row['chunk_id'],
     238                                (string) $row['source_id'],
     239                                (string) $row['title'],
     240                                (string) $row['url'],
     241                                '' !== $post_type ? $post_type : $object_type,
     242                                $object_type,
     243                                (int) $row['object_id'],
     244                                $post_type,
     245                                $text,
     246                                $hit['score']
     247                        );
     248                }
     249
     250                return $chosen;
     251        }
     252
     253        /**
     254         * A failed search: one log line with the code (and the exception class), never the question or any content.
     255         *
     256         * @param string          $code       Error code.
     257         * @param int             $count      Passages that were asked for.
     258         * @param bool            $comparison Whether the question was a comparison.
     259         * @param \Throwable|null $error      The exception, when there was one.
     260         */
     261        private function failed( string $code, int $count, bool $comparison, ?\Throwable $error = null ): Retrieval_Result {
     262                $context = array( 'code' => $code );
     263                if ( null !== $error ) {
     264                        $context['exception'] = get_class( $error );
     265                }
     266                Logger::warning( 'knowledge base search failed', $context );
     267
     268                return Retrieval_Result::failed( $code, $count, $comparison );
    221269        }
    222270}
  • chathearth/tags/2.0.0/includes/Rag/class-schema.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Knowledge-base table installer.
     3 * Knowledge-base tables (feature 002 ported from 1.4.9; version 2 from feature 010, research R10).
     4 *
     5 * Version 1 is the 1.4.9 structure. Version 2 only adds columns and keys and makes `chunks.content` nullable: no
     6 * column is dropped and no row is rewritten by the upgrade itself (the 1.4.9 vector conversion runs later, in steps).
     7 * An upgrade that does not complete leaves the stored version as it was, and is tried again on the next load.
    48 *
    59 * @package ChatHearth
    … …  
    1418}
    1519
     20use ChatHearth\Logger;
     21
    1622/**
    17  * Creates and upgrades custom tables used by RAG.
     23 * Creates and upgrades the custom tables used by the knowledge base.
    1824 */
    1925final class Schema {
    2026
    21         public const DB_VERSION     = 1;
     27        public const DB_VERSION     = 2;
    2228        public const VERSION_OPTION = 'chathearth_kb_db_version';
    2329
    … …  
    3238
    3339        /**
    34          * Chunks table name.
     40         * Chunks (passages) table name.
    3541         */
    3642        public static function chunks_table(): string {
    … …  
    4147
    4248        /**
    43          * Install or upgrade tables when the schema version changes.
     49         * Whether this site's tables are at the current version. No sync step runs while this is false (FR-024).
     50         */
     51        public static function is_current(): bool {
     52                return (int) get_option( self::VERSION_OPTION, 0 ) >= self::DB_VERSION;
     53        }
     54
     55        /**
     56         * Install or upgrade the tables when this site's stored version is lower. One option read.
    4457         */
    4558        public static function maybe_install(): void {
    46                 $installed = (int) get_option( self::VERSION_OPTION, 0 );
    47                 if ( self::DB_VERSION === $installed ) {
     59                if ( self::is_current() ) {
    4860                        return;
    4961                }
    … …  
    5365
    5466        /**
    55          * Create tables and the markdown upload directory.
     67         * Create or upgrade the tables (dbDelta is safe to repeat) and store the schema version once everything is in
     68         * place. When something is missing afterwards, the stored version stays and the next load tries again.
    5669         */
    5770        public static function install(): void {
    … …  
    8093                        updated_gmt datetime NOT NULL,
    8194                        indexed_gmt datetime NULL,
     95                        needs_export tinyint(1) NOT NULL DEFAULT 0,
     96                        generation int(10) unsigned NOT NULL DEFAULT 0,
     97                        attempts tinyint(3) unsigned NOT NULL DEFAULT 0,
     98                        retry_at datetime NULL,
    8299                        PRIMARY KEY  (id),
    83100                        UNIQUE KEY source_id (source_id),
    84101                        KEY status (status),
    85                         KEY object_lookup (object_type,object_id)
     102                        KEY object_lookup (object_type,object_id),
     103                        KEY pending_work (status,retry_at),
     104                        KEY generation (generation)
    86105                ) {$charset_collate};";
    87106
    … …  
    91110                        chunk_id varchar(191) NOT NULL,
    92111                        chunk_index int(10) unsigned NOT NULL DEFAULT 0,
    93                         content longtext NOT NULL,
     112                        start_offset int(10) unsigned NULL,
     113                        length int(10) unsigned NULL,
     114                        content longtext NULL,
    94115                        embedding longtext NULL,
     116                        embedding_bin mediumblob NULL,
     117                        norm float NULL,
     118                        dims smallint(5) unsigned NULL,
     119                        model varchar(64) NOT NULL DEFAULT '',
    95120                        PRIMARY KEY  (id),
    96121                        UNIQUE KEY chunk_id (chunk_id),
    97                         KEY entry_id (entry_id)
     122                        KEY entry_id (entry_id),
     123                        KEY model (model)
    98124                ) {$charset_collate};";
    99125
    100126                dbDelta( $sql_entries );
    101127                dbDelta( $sql_chunks );
     128                self::make_content_nullable();
     129
     130                if ( ! self::is_complete() ) {
     131                        Logger::error( 'knowledge base schema upgrade incomplete', array( 'version' => self::DB_VERSION ) );
     132                        return;
     133                }
    102134
    103135                update_option( self::VERSION_OPTION, self::DB_VERSION, true );
    104                 self::ensure_upload_dir();
    105136        }
    106137
    107138        /**
    108          * Plugin-owned uploads root for generated markdown.
     139         * Let `chunks.content` hold NULL (dbDelta does not change whether a column accepts NULL).
    109140         */
    110         public static function plugin_upload_dir(): string {
    111                 $uploads = wp_upload_dir();
    112                 $base    = (string) $uploads['basedir'];
     141        private static function make_content_nullable(): void {
     142                global $wpdb;
    113143
    114                 return trailingslashit( $base ) . 'chathearth';
    115         }
    116 
    117         /**
    118          * Absolute directory for generated markdown files.
    119          */
    120         public static function upload_dir(): string {
    121                 return trailingslashit( self::plugin_upload_dir() ) . 'kb';
    122         }
    123 
    124         /**
    125          * Create the markdown directory and deny public listing.
    126          */
    127         public static function ensure_upload_dir(): void {
    128                 self::protect_dir( self::plugin_upload_dir() );
    129                 self::protect_dir( self::upload_dir() );
    130         }
    131 
    132         /**
    133          * Create a directory and deny public HTTP access.
    134          *
    135          * @param string $dir Absolute path.
    136          */
    137         private static function protect_dir( string $dir ): void {
    138                 if ( '' === $dir || '/' === $dir ) {
    139                         return;
    140                 }
    141 
    142                 if ( ! is_dir( $dir ) ) {
    143                         wp_mkdir_p( $dir );
    144                 }
    145 
    146                 $index = trailingslashit( $dir ) . 'index.php';
    147                 if ( ! file_exists( $index ) ) {
    148                         // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- private uploads guard file.
    149                         file_put_contents( $index, "<?php\n// Silence is golden.\n" );
    150                 }
    151 
    152                 $htaccess = trailingslashit( $dir ) . '.htaccess';
    153                 if ( ! file_exists( $htaccess ) ) {
    154                         $rules = "<IfModule mod_authz_core.c>\nRequire all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\nDeny from all\n</IfModule>\n";
    155                         // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- private uploads guard file.
    156                         file_put_contents( $htaccess, $rules );
     144                $chunks = esc_sql( self::chunks_table() );
     145                $column = $wpdb->get_row( "SHOW COLUMNS FROM `{$chunks}` LIKE 'content'", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reads this plugin's own table definition; the name is internally generated.
     146                if ( is_array( $column ) && 'NO' === $column['Null'] ) {
     147                        $wpdb->query( "ALTER TABLE `{$chunks}` MODIFY content longtext NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Version 2 upgrade of this plugin's own table; the name is internally generated.
    157148                }
    158149        }
    159150
    160151        /**
    161          * Markdown file path for a source id.
    162          *
    163          * @param string $source_id Source id such as post:123.
     152         * Whether every version 2 column is there and `content` accepts NULL.
    164153         */
    165         public static function markdown_path( string $source_id ): string {
    166                 $safe = strtolower( preg_replace( '/[^a-zA-Z0-9._-]+/', '-', $source_id ) ?? $source_id );
    167                 $safe = trim( $safe, '-' );
    168                 if ( '' === $safe ) {
    169                         $safe = 'entry';
     154        private static function is_complete(): bool {
     155                global $wpdb;
     156
     157                $required = array(
     158                        self::entries_table() => array( 'needs_export', 'generation', 'attempts', 'retry_at' ),
     159                        self::chunks_table()  => array( 'start_offset', 'length', 'content', 'embedding', 'embedding_bin', 'norm', 'dims', 'model' ),
     160                );
     161                foreach ( $required as $table => $columns ) {
     162                        $name  = esc_sql( $table );
     163                        $found = $wpdb->get_results( "SHOW COLUMNS FROM `{$name}`", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reads this plugin's own table definition; the name is internally generated.
     164                        if ( ! is_array( $found ) || array() === $found ) {
     165                                return false;
     166                        }
     167                        $nullable = array();
     168                        foreach ( $found as $column ) {
     169                                $nullable[ (string) $column['Field'] ] = 'YES' === $column['Null'];
     170                        }
     171                        foreach ( $columns as $column ) {
     172                                if ( ! isset( $nullable[ $column ] ) ) {
     173                                        return false;
     174                                }
     175                        }
     176                        if ( self::chunks_table() === $table && empty( $nullable['content'] ) ) {
     177                                return false;
     178                        }
    170179                }
    171180
    172                 return trailingslashit( self::upload_dir() ) . $safe . '.md';
    173         }
    174 
    175         /**
    176          * Drop tables, cron, files, and version option (uninstall).
    177          */
    178         public static function uninstall(): void {
    179                 global $wpdb;
    180 
    181                 $chunks  = esc_sql( self::chunks_table() );
    182                 $entries = esc_sql( self::entries_table() );
    183 
    184                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- uninstall drop of plugin table.
    185                 $wpdb->query( "DROP TABLE IF EXISTS {$chunks}" );
    186                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- uninstall drop of plugin table.
    187                 $wpdb->query( "DROP TABLE IF EXISTS {$entries}" );
    188 
    189                 delete_option( self::VERSION_OPTION );
    190                 delete_option( 'chathearth_kb_sync_state' );
    191                 wp_clear_scheduled_hook( 'chathearth_process_kb_queue' );
    192 
    193                 $dir = self::upload_dir();
    194                 if ( is_dir( $dir ) ) {
    195                         $files = glob( trailingslashit( $dir ) . '*' );
    196                         if ( is_array( $files ) ) {
    197                                 foreach ( $files as $file ) {
    198                                         if ( is_file( $file ) ) {
    199                                                 wp_delete_file( $file );
    200                                         }
    201                                 }
    202                         }
    203                 }
     181                return true;
    204182        }
    205183}
  • chathearth/tags/2.0.0/includes/Rag/class-vector-store-factory.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Build the WordPress-database vector store.
     3 * Chooses the vector store for a request (feature 011, research R13, FR-014; Constitution III).
     4 *
     5 * The built-in store is offered to the 1.4.9 filter `chathearth_vector_store` with its 1.4.9 arguments. Only a value
     6 * that implements `Vector_Store_Interface` replaces it. Anything else is ignored with one warning per request, and the
     7 * warning never holds the value.
    48 *
    59 * @package ChatHearth
    … …  
    1418}
    1519
     20use ChatHearth\Hooks;
     21use ChatHearth\Logger;
     22
    1623/**
    17  * Factory for Vector_Store_Interface implementations.
    18  *
    19  * ChatHearth stores embeddings in this site's WordPress database. Extra
    20  * processes (Python, Chroma) and third-party indexes (Pinecone) are not used.
     24 * The store factory.
    2125 */
    2226final class Vector_Store_Factory {
    2327
    2428        /**
    25          * Create the in-WordPress store.
     29         * Whether the warning about an ignored value was written during this request.
     30         *
     31         * @var bool
     32         */
     33        private static $warned = false;
     34
     35        /**
     36         * The store to use now.
    2637         */
    2738        public static function make(): Vector_Store_Interface {
    28                 $store    = new Builtin_Vector_Store();
    29                 $filtered = apply_filters( 'chathearth_vector_store', $store, 'builtin' );
    30                 if ( $filtered instanceof Vector_Store_Interface ) {
    31                         return $filtered;
     39                $builtin = new Builtin_Vector_Store();
     40
     41                try {
     42                        /**
     43                         * Replace the vector store (kept from 1.4.9).
     44                         *
     45                         * The value must implement `ChatHearth\Rag\Vector_Store_Interface`; anything else is ignored. A replacement
     46                         * store receives the passage text, titles and addresses of public content through `upsert()`, and
     47                         * answers searches through `query()`. Its privacy is the responsibility of the developer who adds it.
     48                         *
     49                         * @since 1.4.9
     50                         *
     51                         * @param Vector_Store_Interface $store Built-in store.
     52                         * @param string                 $id    `builtin`.
     53                         */
     54                        $store = apply_filters( Hooks::VECTOR_STORE, $builtin, 'builtin' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- Every Hooks constant starts with chathearth_.
     55                } catch ( \Throwable $e ) {
     56                        $store = null;
    3257                }
    3358
    34                 return $store;
     59                if ( $store instanceof Vector_Store_Interface ) {
     60                        return $store;
     61                }
     62
     63                if ( ! self::$warned ) {
     64                        self::$warned = true;
     65                        Logger::warning( 'vector store filter ignored' );
     66                }
     67
     68                return $builtin;
    3569        }
    3670
    3771        /**
    38          * Ping the WordPress-database store.
     72         * Whether a store is the built-in one.
    3973         *
    40          * @return array<string, mixed>
     74         * @param Vector_Store_Interface $store Store.
    4175         */
    42         public static function ping_status(): array {
    43                 $ok = self::make()->ping();
     76        public static function is_builtin( Vector_Store_Interface $store ): bool {
     77                return $store instanceof Builtin_Vector_Store;
     78        }
    4479
    45                 return array(
    46                         'ok'      => $ok,
    47                         'store'   => 'builtin',
    48                         'url'     => '',
    49                         'api'     => '',
    50                         'message' => $ok
    51                                 ? __( 'The knowledge base is stored in this WordPress database. No extra server is required.', 'chathearth' )
    52                                 : __( 'The knowledge base tables are not available.', 'chathearth' ),
    53                 );
     80        /**
     81         * Forget that a warning was written (tests, and the start of a request that shares the process).
     82         */
     83        public static function reset(): void {
     84                self::$warned = false;
    5485        }
    5586}
  • chathearth/tags/2.0.0/includes/Rag/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/includes/Rest/class-cart-controller.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Cart REST route for the chat widget.
     3 * `POST chathearth/v1/cart` (feature 013, contracts/rest-api.md, research R7, R9; FR-013 to FR-017).
     4 *
     5 * The 1.4.9 route, arguments, reply and error codes are kept. Checks come in a fixed order and each refusal changes
     6 * nothing: the token (the permission callback, shared with the chat), the chat switch, the ban list, the shop, the add
     7 * limit, then the product. Every reply, errors included, is marked `no-store`.
    48 *
    59 * @package ChatHearth
    … …  
    1519
    1620use ChatHearth\Commerce\Cart_Service;
    17 use ChatHearth\Commerce\Product_Catalog;
    18 use ChatHearth\Options;
    19 use WP_Error;
     21use ChatHearth\Security\Access_Check;
     22use ChatHearth\Security\Client_Address;
     23use ChatHearth\Security\Counters;
     24use ChatHearth\Settings\Settings_Repository;
    2025use WP_REST_Request;
    2126use WP_REST_Response;
    … …  
    2328
    2429/**
    25  * Guest-accessible add-to-cart using the same REST nonce as chat.
     30 * Cart REST controller. Holds services only, never request state.
    2631 */
    2732final class Cart_Controller {
    2833
    29         public const REST_NAMESPACE = 'chathearth/v1';
    30 
    31         public const NONCE_ACTION = 'wp_rest';
    32 
    33         /**
    34          * Register routes.
     34        /**
     35         * Successful adds one visitor network may make in one window.
     36         */
     37        public const LIMIT = 30;
     38
     39        /**
     40         * The window of the add limit, in seconds.
     41         */
     42        public const WINDOW = 600;
     43
     44        /**
     45         * The route, as the REST server names it.
     46         */
     47        private const ROUTE = '/chathearth/v1/cart';
     48
     49        /**
     50         * @var Settings_Repository
     51         */
     52        private $settings;
     53
     54        /**
     55         * @var Chat_Controller
     56         */
     57        private $chat;
     58
     59        /**
     60         * @var Access_Check
     61         */
     62        private $access;
     63
     64        /**
     65         * @var Client_Address
     66         */
     67        private $address;
     68
     69        /**
     70         * @var Counters
     71         */
     72        private $counters;
     73
     74        /**
     75         * @var Cart_Service
     76         */
     77        private $cart;
     78
     79        /**
     80         * @param Settings_Repository $settings Settings.
     81         * @param Chat_Controller     $chat     Shares the token rule of the chat.
     82         * @param Access_Check        $access   The ban list.
     83         * @param Client_Address      $address  The visitor's network.
     84         * @param Counters            $counters The add counter.
     85         * @param Cart_Service        $cart     Checks and adds.
     86         */
     87        public function __construct( Settings_Repository $settings, Chat_Controller $chat, Access_Check $access, Client_Address $address, Counters $counters, Cart_Service $cart ) {
     88                $this->settings = $settings;
     89                $this->chat     = $chat;
     90                $this->access   = $access;
     91                $this->address  = $address;
     92                $this->counters = $counters;
     93                $this->cart     = $cart;
     94        }
     95
     96        /**
     97         * Hook the route and the cache header.
     98         */
     99        public function register(): void {
     100                add_action( 'rest_api_init', array( $this, 'register_routes' ) );
     101                add_filter( 'rest_post_dispatch', array( $this, 'mark_uncacheable' ), 10, 3 );
     102        }
     103
     104        /**
     105         * Register the route. It is registered with or without WooCommerce, so the contract does not depend on the shop.
    35106         */
    36107        public function register_routes(): void {
    37108                register_rest_route(
    38                         self::REST_NAMESPACE,
     109                        Chat_Controller::REST_NAMESPACE,
    39110                        '/cart',
    40111                        array(
    41112                                'methods'             => WP_REST_Server::CREATABLE,
    42                                 'callback'            => array( $this, 'handle_add' ),
    43                                 'permission_callback' => array( $this, 'permission_check' ),
     113                                'callback'            => array( $this, 'add' ),
     114                                'permission_callback' => array( $this->chat, 'permission_check' ),
    44115                                'args'                => array(
    45116                                        'product_id'   => array(
    … …  
    66137
    67138        /**
    68          * Same nonce gate as chat.
     139         * Mark every reply of the route as not to be cached: a result, a refusal or a missing route for another method.
    69140         *
    70          * @param WP_REST_Request $request Request.
    71          * @return true|WP_Error
    72          */
    73         public function permission_check( WP_REST_Request $request ) {
    74                 $nonce = $request->get_header( 'X-WP-Nonce' );
    75                 if ( ! $nonce ) {
    76                         $nonce = $request->get_param( '_wpnonce' );
    77                 }
    78 
    79                 if ( ! $nonce || ! wp_verify_nonce( (string) $nonce, self::NONCE_ACTION ) ) {
    80                         return new WP_Error(
    81                                 'chathearth_invalid_nonce',
    82                                 __( 'Invalid security token. Please refresh the page and try again.', 'chathearth' ),
    83                                 array( 'status' => 403 )
    84                         );
    85                 }
    86 
    87                 return true;
    88         }
    89 
    90         /**
    91          * Add to cart.
     141         * @param mixed            $response Response.
     142         * @param \WP_REST_Server  $server   Server.
     143         * @param \WP_REST_Request $request  Request.
     144         * @return mixed
     145         */
     146        public function mark_uncacheable( $response, $server, $request ) {
     147                unset( $server );
     148                if ( $response instanceof \WP_HTTP_Response && self::ROUTE === $request->get_route() ) {
     149                        $response->header( 'Cache-Control', 'no-store' );
     150                }
     151
     152                return $response;
     153        }
     154
     155        /**
     156         * Handle an add, after the token has been checked.
    92157         *
    93          * @param WP_REST_Request $request Request.
    94          * @return WP_REST_Response|WP_Error
    95          */
    96         public function handle_add( WP_REST_Request $request ) {
    97                 if ( ! Options::is_chat_enabled() ) {
    98                         return new WP_Error(
     158         * @param WP_REST_Request $request Request, after the argument checks.
     159         * @return WP_REST_Response|\WP_Error
     160         */
     161        public function add( WP_REST_Request $request ) {
     162                $settings = $this->settings->all();
     163                if ( ! (bool) ( $settings['chat_enabled'] ?? true ) ) {
     164                        return new \WP_Error(
    99165                                'chathearth_disabled',
    100166                                __( 'The chatbot is currently disabled.', 'chathearth' ),
    … …  
    103169                }
    104170
    105                 if ( ! Cart_Service::is_available() ) {
    106                         return new WP_Error(
     171                $refusal = $this->access->refusal( $settings );
     172                if ( null !== $refusal ) {
     173                        return $refusal;
     174                }
     175
     176                if ( ! $this->cart->load() ) {
     177                        return new \WP_Error(
    107178                                'chathearth_cart_unavailable',
    108179                                __( 'The store cart is not available.', 'chathearth' ),
    … …  
    111182                }
    112183
    113                 $product_id   = (int) $request->get_param( 'product_id' );
    114                 $quantity     = (int) $request->get_param( 'quantity' );
    115                 $variation_id = (int) $request->get_param( 'variation_id' );
    116 
    117                 $result = ( new Cart_Service() )->add( $product_id, $quantity, $variation_id );
     184                // Look before adding and count only after a success, so a refused add never counts; a counter that cannot be read
     185                // refuses, as the chat's own limits do.
     186                $counter = 'chathearth_cart_' . $this->address->key();
     187                $count   = $this->counters->peek( $counter );
     188                if ( null === $count ) {
     189                        return new \WP_Error(
     190                                'chathearth_rate_busy',
     191                                __( 'Too many requests. Please wait a moment and try again.', 'chathearth' ),
     192                                array( 'status' => 429 )
     193                        );
     194                }
     195                if ( $count >= self::LIMIT ) {
     196                        return new \WP_Error(
     197                                'chathearth_rate_limited',
     198                                __( 'Too many cart requests. Please wait a few minutes and try again.', 'chathearth' ),
     199                                array( 'status' => 429 )
     200                        );
     201                }
     202
     203                $result = $this->cart->add( (int) $request->get_param( 'product_id' ), (int) $request->get_param( 'quantity' ), (int) $request->get_param( 'variation_id' ) );
    118204                if ( is_wp_error( $result ) ) {
    119205                        return $result;
    120206                }
    121207
    122                 $product           = ( new Product_Catalog() )->get_public_product( $product_id );
    123                 $result['product'] = is_array( $product ) ? $product : null;
     208                $this->counters->bump( $counter, self::WINDOW, 'cartadd' );
    124209
    125210                return new WP_REST_Response( $result, 200 );
  • chathearth/tags/2.0.0/includes/Rest/class-chat-controller.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * REST chat endpoint.
     3 * `POST chathearth/v1/chat` (interface layer; contracts/rest-api.md).
     4 *
     5 * The 1.4.9 route, parameters, response keys, error codes and messages are kept. The controller only translates
     6 * the request into a per-request context and the context into the response; the flow lives in the pipeline.
    47 *
    58 * @package ChatHearth
    … …  
    1417}
    1518
    16 use ChatHearth\Ai\Ai_Gateway;
    17 use ChatHearth\Commerce\Cart_Service;
    18 use ChatHearth\Options;
    19 use ChatHearth\Rag\Current_Page;
    20 use ChatHearth\Rag\Retriever;
    21 use ChatHearth\Security\Content_Moderation;
    22 use ChatHearth\Security\Rate_Limiter;
    23 use ChatHearth\Security\Recaptcha;
    24 use WP_Error;
     19use ChatHearth\Chat\Chat_Context;
     20use ChatHearth\Chat\Chat_Pipeline;
     21use ChatHearth\Settings\Settings_Repository;
    2522use WP_REST_Request;
    2623use WP_REST_Response;
    … …  
    2825
    2926/**
    30  * Chat REST controller.
     27 * Chat REST controller. Holds services only, never request state.
    3128 */
    3229final class Chat_Controller {
    … …  
    3431        public const REST_NAMESPACE = 'chathearth/v1';
    3532
    36         /** Must be `wp_rest` — WordPress REST cookie auth validates X-WP-Nonce against this action. */
     33        /**
     34         * The REST token action. It must be `wp_rest`: WordPress's cookie authentication checks `X-WP-Nonce` against it.
     35         */
    3736        public const NONCE_ACTION = 'wp_rest';
    3837
    3938        /**
    40          * Register routes.
     39         * Most history turns accepted in one request.
     40         */
     41        public const MAX_HISTORY_TURNS = 100;
     42
     43        /**
     44         * @var Settings_Repository
     45         */
     46        private $settings;
     47
     48        /**
     49         * @var Chat_Pipeline
     50         */
     51        private $pipeline;
     52
     53        /**
     54         * @param Settings_Repository $settings Settings.
     55         * @param Chat_Pipeline       $pipeline The stages.
     56         */
     57        public function __construct( Settings_Repository $settings, Chat_Pipeline $pipeline ) {
     58                $this->settings = $settings;
     59                $this->pipeline = $pipeline;
     60        }
     61
     62        /**
     63         * Hook the route registration.
     64         */
     65        public function register(): void {
     66                add_action( 'rest_api_init', array( $this, 'register_routes' ) );
     67        }
     68
     69        /**
     70         * Register the route.
    4171         */
    4272        public function register_routes(): void {
    … …  
    5282                                                'required'          => true,
    5383                                                'type'              => 'string',
    54                                                 'sanitize_callback' => 'sanitize_textarea_field',
     84                                                'sanitize_callback' => array( self::class, 'sanitize_text' ),
    5585                                        ),
    5686                                        'history'         => array(
    … …  
    5888                                                'type'              => 'array',
    5989                                                'default'           => array(),
     90                                                'validate_callback' => array( $this, 'validate_history' ),
    6091                                                'sanitize_callback' => array( $this, 'sanitize_history' ),
    6192                                        ),
    6293                                        'recaptcha_token' => array(
     94                                                'required'          => false,
     95                                                'type'              => 'string',
     96                                                'default'           => '',
     97                                                'sanitize_callback' => 'sanitize_text_field',
     98                                        ),
     99                                        'chathearth_hp'   => array(
    63100                                                'required'          => false,
    64101                                                'type'              => 'string',
    … …  
    93130                        )
    94131                );
    95 
    96                 register_rest_route(
    97                         self::REST_NAMESPACE,
    98                         '/recaptcha',
    99                         array(
    100                                 'methods'             => WP_REST_Server::CREATABLE,
    101                                 'callback'            => array( $this, 'handle_recaptcha' ),
    102                                 'permission_callback' => array( $this, 'permission_check' ),
    103                                 'args'                => array(
    104                                         'recaptcha_token' => array(
    105                                                 'required'          => true,
    106                                                 'type'              => 'string',
    107                                                 'sanitize_callback' => 'sanitize_text_field',
    108                                         ),
    109                                 ),
    110                         )
    111                 );
    112         }
    113 
    114         /**
    115          * Sanitize chat history turns from the REST request.
    116          *
    117          * @param mixed           $history History param.
     132        }
     133
     134        /**
     135         * Clean visitor text: markup is removed (`sanitize_textarea_field`), and so are control characters, except
     136         * line breaks and tabs.
     137         *
     138         * @param mixed $value Text as received.
     139         */
     140        public static function sanitize_text( $value ): string {
     141                $text = sanitize_textarea_field( is_scalar( $value ) ? (string) $value : '' );
     142
     143                return (string) preg_replace( '/[\x00-\x08\x0B-\x1F\x7F]/', '', $text );
     144        }
     145
     146        /**
     147         * Accepts a history that is a list of at most 100 entries.
     148         *
     149         * @param mixed $history History as received.
     150         * @return true|\WP_Error
     151         */
     152        public function validate_history( $history ) {
     153                if ( ! is_array( $history ) || count( $history ) > self::MAX_HISTORY_TURNS || ! self::is_list( $history ) ) {
     154                        return new \WP_Error(
     155                                'rest_invalid_param',
     156                                __( 'The conversation history is not valid.', 'chathearth' ),
     157                                array( 'status' => 400 )
     158                        );
     159                }
     160
     161                return true;
     162        }
     163
     164        /**
     165         * Whether an array is a list (keys 0, 1, 2, ...).
     166         *
     167         * @param array<mixed> $values Values.
     168         */
     169        private static function is_list( array $values ): bool {
     170                return array() === $values || array_keys( $values ) === range( 0, count( $values ) - 1 );
     171        }
     172
     173        /**
     174         * Clean the turns: only `user` and `assistant` turns with text remain (as in 1.4.9).
     175         *
     176         * @param mixed           $history History as received.
    118177         * @param WP_REST_Request $request Request.
    119          * @param string          $param   Param name.
    120          * @return list<array{role:string,content:string}>
     178         * @param string          $param   Parameter name.
     179         * @return array<int, array{role: string, content: string}>
    121180         */
    122181        public function sanitize_history( $history, $request, string $param ): array {
    … …  
    127186                }
    128187
    129                 $out = array();
     188                $clean = array();
    130189                foreach ( $history as $turn ) {
    131190                        if ( ! is_array( $turn ) ) {
    … …  
    133192                        }
    134193
    135                         $role    = isset( $turn['role'] ) ? sanitize_key( (string) $turn['role'] ) : '';
    136                         $content = isset( $turn['content'] ) ? sanitize_textarea_field( (string) $turn['content'] ) : '';
     194                        $role    = isset( $turn['role'] ) && is_scalar( $turn['role'] ) ? sanitize_key( (string) $turn['role'] ) : '';
     195                        $content = isset( $turn['content'] ) && is_scalar( $turn['content'] ) ? self::sanitize_text( (string) $turn['content'] ) : '';
    137196
    138197                        if ( ! in_array( $role, array( 'user', 'assistant' ), true ) || '' === $content ) {
    … …  
    140199                        }
    141200
    142                         $out[] = array(
     201                        $clean[] = array(
    143202                                'role'    => $role,
    144203                                'content' => $content,
    … …  
    146205                }
    147206
    148                 return $out;
    149         }
    150 
    151         /**
    152          * Allow guests and logged-in users when a valid REST nonce is present.
    153          *
    154          * WordPress already rejects invalid X-WP-Nonce values via rest_cookie_check_errors
    155          * before this runs (when the header is sent). We still verify here for clarity.
     207                return $clean;
     208        }
     209
     210        /**
     211         * Allow a request that carries a valid REST token (the `X-WP-Nonce` header or `_wpnonce`).
    156212         *
    157213         * @param WP_REST_Request $request Request.
    158          * @return true|WP_Error
     214         * @return true|\WP_Error
    159215         */
    160216        public function permission_check( WP_REST_Request $request ) {
    … …  
    165221
    166222                if ( ! $nonce || ! wp_verify_nonce( (string) $nonce, self::NONCE_ACTION ) ) {
    167                         return new WP_Error(
     223                        return new \WP_Error(
    168224                                'chathearth_invalid_nonce',
    169225                                __( 'Invalid security token. Please refresh the page and try again.', 'chathearth' ),
    … …  
    176232
    177233        /**
    178          * Unlock the chat overlay after a successful reCAPTCHA v3 check.
     234         * Builds the per-request state from the request and one read of the settings.
     235         *
     236         * @param WP_REST_Request $request Request, after the argument checks.
     237         */
     238        public function build_context( WP_REST_Request $request ): Chat_Context {
     239                $context = new Chat_Context( $this->settings->all() );
     240
     241                $history = $request->get_param( 'history' );
     242
     243                $context->set_message( (string) $request->get_param( 'message' ) );
     244                $context->set_history( is_array( $history ) ? $history : array() );
     245                $context->set_extra(
     246                        array(
     247                                'recaptcha_token' => (string) $request->get_param( 'recaptcha_token' ),
     248                                'chathearth_hp'   => (string) $request->get_param( 'chathearth_hp' ),
     249                                'page_id'         => (int) $request->get_param( 'page_id' ),
     250                                'page_type'       => (string) $request->get_param( 'page_type' ),
     251                                'page_taxonomy'   => (string) $request->get_param( 'page_taxonomy' ),
     252                                'page_url'        => (string) $request->get_param( 'page_url' ),
     253                        )
     254                );
     255
     256                return $context;
     257        }
     258
     259        /**
     260         * Handle a chat request.
    179261         *
    180262         * @param WP_REST_Request $request Request.
    181          * @return WP_REST_Response|WP_Error
    182          */
    183         public function handle_recaptcha( WP_REST_Request $request ) {
    184                 if ( ! Options::is_chat_enabled() ) {
    185                         return new WP_Error(
     263         * @return WP_REST_Response|\WP_Error
     264         */
     265        public function handle_chat( WP_REST_Request $request ) {
     266                $context = $this->build_context( $request );
     267
     268                if ( ! $context->setting( 'chat_enabled', true ) ) {
     269                        return new \WP_Error(
    186270                                'chathearth_disabled',
    187271                                __( 'The chatbot is currently disabled.', 'chathearth' ),
    … …  
    190274                }
    191275
    192                 $captcha = ( new Recaptcha() )->verify_or_error( (string) $request->get_param( 'recaptcha_token' ) );
    193                 if ( is_wp_error( $captcha ) ) {
    194                         return $captcha;
    195                 }
    196 
    197                 return new WP_REST_Response(
    198                         array(
    199                                 'ok' => true,
    200                         ),
    201                         200
    202                 );
    203         }
    204 
    205         /**
    206          * Handle chat request.
    207          *
    208          * @param WP_REST_Request $request Request.
    209          * @return WP_REST_Response|WP_Error
    210          */
    211         public function handle_chat( WP_REST_Request $request ) {
    212                 if ( ! Options::is_chat_enabled() ) {
    213                         return new WP_Error(
    214                                 'chathearth_disabled',
    215                                 __( 'The chatbot is currently disabled.', 'chathearth' ),
    216                                 array( 'status' => 403 )
    217                         );
    218                 }
    219 
    220                 $captcha = ( new Recaptcha() )->verify_or_error( (string) $request->get_param( 'recaptcha_token' ) );
    221                 if ( is_wp_error( $captcha ) ) {
    222                         return $captcha;
    223                 }
    224 
    225                 $rate = ( new Rate_Limiter() )->allow_or_error();
    226                 if ( is_wp_error( $rate ) ) {
    227                         return $rate;
    228                 }
    229 
    230                 $message = trim( (string) $request->get_param( 'message' ) );
    231                 $max_len = (int) Options::get( 'max_message_length', 2000 );
    232 
    233                 if ( '' === $message ) {
    234                         return new WP_Error(
    235                                 'chathearth_empty_message',
    236                                 __( 'Please enter a message.', 'chathearth' ),
    237                                 array( 'status' => 400 )
    238                         );
    239                 }
    240 
    241                 if ( mb_strlen( $message, 'UTF-8' ) > $max_len ) {
    242                         $message = mb_substr( $message, 0, $max_len, 'UTF-8' );
    243                 }
    244 
    245                 $history_raw = $request->get_param( 'history' );
    246                 $history     = is_array( $history_raw ) ? $history_raw : array();
    247                 $max_history = (int) Options::get( 'max_history_messages', 20 );
    248 
    249                 foreach ( $history as $i => $turn ) {
    250                         $content = isset( $turn['content'] ) ? (string) $turn['content'] : '';
    251                         if ( mb_strlen( $content, 'UTF-8' ) > $max_len ) {
    252                                 $history[ $i ]['content'] = mb_substr( $content, 0, $max_len, 'UTF-8' );
    253                         }
    254                 }
    255 
    256                 if ( count( $history ) > $max_history ) {
    257                         $history = array_slice( $history, -$max_history );
    258                 }
    259 
    260                 $moderation = ( new Content_Moderation() )->check_or_error( $message, $history );
    261                 if ( is_wp_error( $moderation ) ) {
    262                         return $moderation;
    263                 }
    264 
    265                 Current_Page::instance()->capture(
    266                         (int) $request->get_param( 'page_id' ),
    267                         (string) $request->get_param( 'page_type' ),
    268                         (string) $request->get_param( 'page_taxonomy' ),
    269                         (string) $request->get_param( 'page_url' )
    270                 );
    271 
    272                 $reply = ( new Ai_Gateway() )->generate_reply( $message, $history );
    273 
    274                 if ( is_wp_error( $reply ) ) {
    275                         return $reply;
    276                 }
    277 
    278                 $retriever = Retriever::instance();
    279                 $current   = Current_Page::instance();
    280 
    281                 return new WP_REST_Response(
    282                         array(
    283                                 'reply'    => $reply,
    284                                 'sources'  => self::merge_unique_sources( $current->source(), $retriever->last_sources() ),
    285                                 'products' => self::merge_unique_products( $current->product(), $retriever->last_products() ),
    286                                 'commerce' => array(
    287                                         'enabled'      => Cart_Service::is_available(),
    288                                         'cart_url'     => Cart_Service::is_available() ? Cart_Service::cart_url() : '',
    289                                         'checkout_url' => Cart_Service::is_available() ? Cart_Service::checkout_url() : '',
    290                                 ),
    291                         ),
    292                         200
    293                 );
    294         }
    295 
    296         /**
    297          * Prepend the current-page citation when it is not already in the RAG list.
    298          *
    299          * @param array<string, mixed>|null  $current Current page source.
    300          * @param list<array<string, mixed>> $sources RAG sources.
    301          * @return list<array<string, mixed>>
    302          */
    303         private static function merge_unique_sources( $current, array $sources ): array {
    304                 if ( ! is_array( $current ) ) {
    305                         return $sources;
    306                 }
    307 
    308                 $url = isset( $current['url'] ) ? (string) $current['url'] : '';
    309                 if ( '' === $url ) {
    310                         return $sources;
    311                 }
    312 
    313                 foreach ( $sources as $source ) {
    314                         if ( isset( $source['url'] ) && (string) $source['url'] === $url ) {
    315                                 return $sources;
    316                         }
    317                 }
    318 
    319                 array_unshift( $sources, $current );
    320 
    321                 return $sources;
    322         }
    323 
    324         /**
    325          * Prepend the current-page product when it is not already listed.
    326          *
    327          * @param array<string, mixed>|null  $current Current product.
    328          * @param list<array<string, mixed>> $products RAG/catalog products.
    329          * @return list<array<string, mixed>>
    330          */
    331         private static function merge_unique_products( $current, array $products ): array {
    332                 if ( ! is_array( $current ) ) {
    333                         return $products;
    334                 }
    335 
    336                 $id = isset( $current['id'] ) ? (int) $current['id'] : 0;
    337                 if ( $id <= 0 ) {
    338                         return $products;
    339                 }
    340 
    341                 foreach ( $products as $product ) {
    342                         if ( isset( $product['id'] ) && (int) $product['id'] === $id ) {
    343                                 return $products;
    344                         }
    345                 }
    346 
    347                 array_unshift( $products, $current );
    348 
    349                 return $products;
     276                $error = $this->pipeline->run( $context );
     277                if ( null !== $error ) {
     278                        return $error;
     279                }
     280
     281                return new WP_REST_Response( $context->response(), 200 );
    350282        }
    351283}
  • chathearth/tags/2.0.0/includes/Rest/class-kb-controller.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Knowledge-base admin REST routes.
     3 * The knowledge base routes of the Index card (feature 012, contracts/rest-api.md): `POST /kb/sync`,
     4 * `GET /kb/entries`, `POST /kb/entries` and `POST /kb/ping`. `GET /kb/status` stays in feature 010's controller.
     5 *
     6 * Every route has the same permission rule (`Kb_Permission`: the 1.4.9 `chathearth_forbidden` 403) and every reply is
     7 * marked `no-store` by it. The routes that change something accept only `POST`, so a link or an image cannot trigger
     8 * them. Nothing here exports or embeds in the request, and nothing holds request state: the controller holds services
     9 * only.
    410 *
    511 * @package ChatHearth
    … …  
    1420}
    1521
    16 use ChatHearth\Rag\Indexer;
    17 use ChatHearth\Rag\Kb_Repository;
    18 use ChatHearth\Rag\Schema;
    19 use ChatHearth\Rag\Vector_Store_Factory;
     22use ChatHearth\Kb\Entry_Presenter;
     23use ChatHearth\Kb\Entry_Query;
     24use ChatHearth\Kb\Entry_Repository;
     25use ChatHearth\Kb\Kb_Entry_Toggle;
     26use ChatHearth\Kb\Sources;
     27use ChatHearth\Kb\Status_Report;
     28use ChatHearth\Kb\Store_Check;
     29use ChatHearth\Kb\Sync_Job;
    2030use WP_Error;
    2131use WP_REST_Request;
    … …  
    2434
    2535/**
    26  * Sync, status, and per-entry include/exclude.
     36 * Controller of the four 1.4.9 routes that feature 010 did not bring back.
    2737 */
    2838final class Kb_Controller {
    2939
    30         public const REST_NAMESPACE = 'chathearth/v1';
    31 
    32         /**
    33          * Register routes.
     40        /**
     41         * @var Kb_Permission
     42         */
     43        private $permission;
     44
     45        /**
     46         * @var Status_Report
     47         */
     48        private $report;
     49
     50        /**
     51         * @var Sync_Job
     52         */
     53        private $job;
     54
     55        /**
     56         * @var Sources
     57         */
     58        private $sources;
     59
     60        /**
     61         * @var Entry_Repository
     62         */
     63        private $entries;
     64
     65        /**
     66         * @var Entry_Presenter
     67         */
     68        private $presenter;
     69
     70        /**
     71         * @var Kb_Entry_Toggle
     72         */
     73        private $toggle;
     74
     75        /**
     76         * @var Store_Check
     77         */
     78        private $store_check;
     79
     80        /**
     81         * @param Kb_Permission    $permission The shared permission rule.
     82         * @param Status_Report    $report     The status report.
     83         * @param Sync_Job         $job        The sync job.
     84         * @param Sources          $sources    The selected sources and the Knowledge Base switch.
     85         * @param Entry_Repository $entries    The entries.
     86         * @param Entry_Presenter  $presenter  Row to list item.
     87         * @param Kb_Entry_Toggle  $toggle     The Included switch.
     88         * @param Store_Check      $store_check The storage check.
     89         */
     90        public function __construct( Kb_Permission $permission, Status_Report $report, Sync_Job $job, Sources $sources, Entry_Repository $entries, Entry_Presenter $presenter, Kb_Entry_Toggle $toggle, Store_Check $store_check ) {
     91                $this->permission  = $permission;
     92                $this->report      = $report;
     93                $this->job         = $job;
     94                $this->sources     = $sources;
     95                $this->entries     = $entries;
     96                $this->presenter   = $presenter;
     97                $this->toggle      = $toggle;
     98                $this->store_check = $store_check;
     99        }
     100
     101        /**
     102         * Hook the route registration.
     103         */
     104        public function register(): void {
     105                add_action( 'rest_api_init', array( $this, 'register_routes' ) );
     106        }
     107
     108        /**
     109         * Register the routes.
    34110         */
    35111        public function register_routes(): void {
    36112                register_rest_route(
    37                         self::REST_NAMESPACE,
     113                        Chat_Controller::REST_NAMESPACE,
    38114                        '/kb/sync',
    39115                        array(
    40116                                'methods'             => WP_REST_Server::CREATABLE,
    41                                 'callback'            => array( $this, 'handle_sync' ),
    42                                 'permission_callback' => array( $this, 'can_manage' ),
     117                                'callback'            => array( $this, 'sync' ),
     118                                'permission_callback' => array( $this->permission, 'check' ),
    43119                        )
    44120                );
    45121
    46122                register_rest_route(
    47                         self::REST_NAMESPACE,
    48                         '/kb/status',
    49                         array(
    50                                 'methods'             => WP_REST_Server::READABLE,
    51                                 'callback'            => array( $this, 'handle_status' ),
    52                                 'permission_callback' => array( $this, 'can_manage' ),
     123                        Chat_Controller::REST_NAMESPACE,
     124                        '/kb/ping',
     125                        array(
     126                                'methods'             => WP_REST_Server::CREATABLE,
     127                                'callback'            => array( $this, 'ping' ),
     128                                'permission_callback' => array( $this->permission, 'check' ),
    53129                        )
    54130                );
    55131
    56132                register_rest_route(
    57                         self::REST_NAMESPACE,
     133                        Chat_Controller::REST_NAMESPACE,
    58134                        '/kb/entries',
    59135                        array(
    60                                 'methods'             => WP_REST_Server::READABLE,
    61                                 'callback'            => array( $this, 'handle_entries' ),
    62                                 'permission_callback' => array( $this, 'can_manage' ),
     136                                array(
     137                                        'methods'             => WP_REST_Server::READABLE,
     138                                        'callback'            => array( $this, 'entries' ),
     139                                        'permission_callback' => array( $this->permission, 'check' ),
     140                                        'args'                => array(
     141                                                'page'     => array(
     142                                                        'type'    => 'integer',
     143                                                        'default' => 1,
     144                                                        'minimum' => 1,
     145                                                        'maximum' => 100000,
     146                                                ),
     147                                                'search'   => array(
     148                                                        'type'    => 'string',
     149                                                        'default' => '',
     150                                                ),
     151                                                'type'     => array(
     152                                                        'type'    => 'string',
     153                                                        'default' => '',
     154                                                        'pattern' => '^(?:_site|[a-z0-9_-]{1,32})?\z',
     155                                                ),
     156                                                'status'   => array(
     157                                                        'type'    => 'string',
     158                                                        'default' => '',
     159                                                        'enum'    => array( '', 'indexed', 'pending', 'excluded', 'failed' ),
     160                                                ),
     161                                                'included' => array(
     162                                                        'type'    => 'string',
     163                                                        'default' => '',
     164                                                        'enum'    => array( '', 'yes', 'no' ),
     165                                                ),
     166                                        ),
     167                                ),
     168                                array(
     169                                        'methods'             => WP_REST_Server::CREATABLE,
     170                                        'callback'            => array( $this, 'toggle' ),
     171                                        'permission_callback' => array( $this->permission, 'check' ),
     172                                        'args'                => array(
     173                                                'source_id' => array(
     174                                                        'type'              => 'string',
     175                                                        'default'           => '',
     176                                                        'sanitize_callback' => 'sanitize_text_field',
     177                                                ),
     178                                                'included'  => array(
     179                                                        'type'              => 'boolean',
     180                                                        'default'           => false,
     181                                                        'sanitize_callback' => 'rest_sanitize_boolean',
     182                                                ),
     183                                        ),
     184                                ),
    63185                        )
    64186                );
    65 
    66                 register_rest_route(
    67                         self::REST_NAMESPACE,
    68                         '/kb/entries',
    69                         array(
    70                                 'methods'             => WP_REST_Server::CREATABLE,
    71                                 'callback'            => array( $this, 'handle_toggle' ),
    72                                 'permission_callback' => array( $this, 'can_manage' ),
    73                         )
    74                 );
    75 
    76                 register_rest_route(
    77                         self::REST_NAMESPACE,
    78                         '/kb/ping',
    79                         array(
    80                                 'methods'             => WP_REST_Server::CREATABLE,
    81                                 'callback'            => array( $this, 'handle_ping' ),
    82                                 'permission_callback' => array( $this, 'can_manage' ),
    83                         )
    84                 );
    85         }
    86 
    87         /**
    88          * Require the manage_options capability.
     187        }
     188
     189        /**
     190         * `POST /kb/ping`: test the storage and keep the result (research R10). 200 when it is ready, 502 when it is not.
     191         */
     192        public function ping(): WP_REST_Response {
     193                $result = $this->store_check->run();
     194
     195                return new WP_REST_Response( $result, $result['ok'] ? 200 : 502 );
     196        }
     197
     198        /**
     199         * `GET /kb/entries`: one page of the item list (research R5). One count query and one page query, plus the query for
     200         * the type filter. Only the 1.4.9 list fields and the labels are read, never a document.
    89201         *
    90          * @return true|WP_Error
    91          */
    92         public function can_manage() {
    93                 if ( current_user_can( 'manage_options' ) ) {
    94                         return true;
    95                 }
    96 
    97                 return new WP_Error(
    98                         'chathearth_forbidden',
    99                         __( 'You are not allowed to manage the knowledge base.', 'chathearth' ),
    100                         array( 'status' => 403 )
    101                 );
    102         }
    103 
    104         /**
    105          * Scan sources and embed a batch.
    106          *
    107          * @return WP_REST_Response
    108          */
    109         public function handle_sync() {
    110                 Schema::maybe_install();
    111                 $indexer = Indexer::instance();
    112                 $scanned = $indexer->scan_sources();
    113                 $indexed = $indexer->process_queue( 12 );
    114                 $repo    = new Kb_Repository();
     202         * @param WP_REST_Request $request The request.
     203         */
     204        public function entries( WP_REST_Request $request ): WP_REST_Response {
     205                $page  = $this->entries->list_page( Entry_Query::from_request( $request ) );
     206                $total = $page['total'];
    115207
    116208                return new WP_REST_Response(
    117209                        array(
    118                                 'scanned' => $scanned,
    119                                 'indexed' => $indexed,
    120                                 'counts'  => $repo->status_counts(),
    121                                 'pending' => $repo->has_pending(),
     210                                'items' => array_map( array( $this->presenter, 'item' ), $page['rows'] ),
     211                                'total' => $total,
     212                                'pages' => max( 1, (int) ceil( $total / Entry_Query::PAGE_SIZE ) ),
     213                                'types' => $this->presenter->types( $this->entries->types() ),
    122214                        ),
    123215                        200
    … …  
    126218
    127219        /**
    128          * Counts and store ping.
     220         * `POST /kb/entries`: include or exclude one entry (research R7).
    129221         *
    130          * @return WP_REST_Response
    131          */
    132         public function handle_status() {
    133                 Schema::maybe_install();
    134                 $repo = new Kb_Repository();
     222         * @param WP_REST_Request $request The request.
     223         * @return WP_REST_Response|WP_Error
     224         */
     225        public function toggle( WP_REST_Request $request ) {
     226                $result = $this->toggle->set( (string) $request->get_param( 'source_id' ), (bool) $request->get_param( 'included' ) );
     227
     228                return $result instanceof WP_Error ? $result : new WP_REST_Response( $result, 200 );
     229        }
     230
     231        /**
     232         * `POST /kb/sync`: ask for a full sync in the background (research R3).
     233         *
     234         * Nothing is queued while the Knowledge Base is off or a sync already runs, so a second click, or a click in another
     235         * tab, never resets the progress. The reply keeps the 1.4.9 fields (`scanned` and `indexed` are 0, because the work
     236         * runs in the background) and adds the full report.
     237         */
     238        public function sync(): WP_REST_Response {
     239                $before = $this->report->to_array();
     240                if ( $this->sources->is_enabled() && ! $before['running'] ) {
     241                        $this->job->request_full( 0 );
     242                }
     243                $report = $this->report->to_array();
    135244
    136245                return new WP_REST_Response(
    137246                        array(
    138                                 'counts'   => $repo->status_counts(),
    139                                 'pending'  => $repo->has_pending(),
    140                                 'store_ok' => Vector_Store_Factory::make()->ping(),
    141                                 'store'    => 'builtin',
     247                                'scanned' => 0,
     248                                'indexed' => 0,
     249                                'counts'  => $report['counts'],
     250                                'pending' => $report['pending'],
     251                                'report'  => $report,
    142252                        ),
    143253                        200
    144254                );
    145255        }
    146 
    147         /**
    148          * Paginated entries.
    149          *
    150          * @param WP_REST_Request $request Request.
    151          * @return WP_REST_Response
    152          */
    153         public function handle_entries( WP_REST_Request $request ) {
    154                 Schema::maybe_install();
    155                 $page   = max( 1, (int) $request->get_param( 'page' ) );
    156                 $search = sanitize_text_field( (string) $request->get_param( 'search' ) );
    157                 $data   = ( new Kb_Repository() )->paginate( $page, 20, $search );
    158 
    159                 return new WP_REST_Response( $data, 200 );
    160         }
    161 
    162         /**
    163          * Toggle include flag.
    164          *
    165          * @param WP_REST_Request $request Request.
    166          * @return WP_REST_Response|WP_Error
    167          */
    168         public function handle_toggle( WP_REST_Request $request ) {
    169                 $source_id = sanitize_text_field( (string) $request->get_param( 'source_id' ) );
    170                 $included  = rest_sanitize_boolean( $request->get_param( 'included' ) );
    171                 if ( '' === $source_id ) {
    172                         return new WP_Error(
    173                                 'chathearth_kb_invalid',
    174                                 __( 'Missing source id.', 'chathearth' ),
    175                                 array( 'status' => 400 )
    176                         );
    177                 }
    178 
    179                 Indexer::instance()->set_included( $source_id, (bool) $included );
    180                 $entry = ( new Kb_Repository() )->get_by_source( $source_id );
    181                 if ( ! is_array( $entry ) ) {
    182                         return new WP_Error(
    183                                 'chathearth_kb_missing',
    184                                 __( 'Entry not found.', 'chathearth' ),
    185                                 array( 'status' => 404 )
    186                         );
    187                 }
    188 
    189                 return new WP_REST_Response(
    190                         array(
    191                                 'source_id' => $source_id,
    192                                 'included'  => ! empty( $entry['included'] ),
    193                                 'status'    => (string) $entry['status'],
    194                         ),
    195                         200
    196                 );
    197         }
    198 
    199         /**
    200          * Ping the configured vector store.
    201          *
    202          * @param WP_REST_Request $request Request.
    203          * @return WP_REST_Response
    204          */
    205         public function handle_ping( WP_REST_Request $request ) {
    206                 unset( $request );
    207                 $status = Vector_Store_Factory::ping_status();
    208 
    209                 return new WP_REST_Response(
    210                         $status,
    211                         ! empty( $status['ok'] ) ? 200 : 502
    212                 );
    213         }
    214256}
  • chathearth/tags/2.0.0/includes/Rest/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/includes/Security/class-rate-limiter.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Per-IP and global rate limiter (object cache incr, locked fallback).
     3 * Enforce site-wide and network message quotas before AI calls (FR-004–FR-008).
    44 *
    55 * @package ChatHearth
    … …  
    1414}
    1515
    16 use ChatHearth\Options;
     16use ChatHearth\Logger;
    1717use WP_Error;
    1818
    19 /**
    20  * Limits chat requests by client IP and site-wide quotas.
    21  */
     19/** Consumes the site-wide allowance first and refunds it if the network or user cannot send. */
    2220final class Rate_Limiter {
    2321
    24         private const CACHE_GROUP = 'chathearth';
     22        private const GLOBAL_MINUTE = 'chathearth_rl_g_m';
     23        private const GLOBAL_HOUR   = 'chathearth_rl_g_h';
     24        private const GLOBAL_SCOPE  = 'g';
    2525
    26         private const GLOBAL_MINUTE_KEY   = 'chathearth_rl_g_m';
    27         private const GLOBAL_HOUR_KEY     = 'chathearth_rl_g_h';
    28         private const GLOBAL_INCIDENT_KEY = 'chathearth_rl_g_inc';
    29         private const EMAIL_COOLDOWN_KEY  = 'chathearth_rl_email_cd';
     26        /** @var Counters */
     27        private $counters;
    3028
    31         public const ABUSE_ALERT_OPTION = 'chathearth_abuse_alert';
     29        /** @var array<string,mixed> */
     30        private $settings;
    3231
    33         /** Max attempts to acquire the lock. */
    34         private const LOCK_ATTEMPTS = 3;
     32        /** @var callable():void|null */
     33        private $record_incident;
    3534
    36         /** Microseconds to wait between lock attempts. */
    37         private const LOCK_WAIT_US = 50000;
    38 
    39         /** Lock option TTL in seconds (stored as an expiry timestamp). */
    40         private const LOCK_TTL = 5;
    41 
    42         /** Min seconds between escalation emails. */
    43         private const EMAIL_COOLDOWN = 1800;
     35        /** @var Quota_Policy */
     36        private $policy;
    4437
    4538        /**
    46          * Check whether the current request is allowed; increments counters if allowed.
    47          *
    48          * Order: global site limits, then per-IP limits.
    49          *
    50          * @return true|WP_Error
     39         * @param Counters             $counters        Quota storage.
     40         * @param Client_Address       $client          Visitor network, used for the default quota policy.
     41         * @param array<string,mixed>  $settings        The chat request's settings snapshot.
     42         * @param callable():void|null $record_incident Called on a genuine site-wide limit refusal.
     43         * @param Quota_Policy|null    $policy          The bucket and limits of the second step; the default follows the settings.
    5144         */
    52         public function allow_or_error() {
    53                 $global_min  = (int) Options::get( 'global_rate_limit_per_minute', 60 );
    54                 $global_hour = (int) Options::get( 'global_rate_limit_per_hour', 500 );
     45        public function __construct( Counters $counters, Client_Address $client, array $settings, ?callable $record_incident = null, ?Quota_Policy $policy = null ) {
     46                $this->counters        = $counters;
     47                $this->settings        = $settings;
     48                $this->record_incident = $record_incident;
     49                $this->policy          = $policy ?? new Quota_Policy( $client );
     50        }
    5551
    56                 $global = $this->consume_quota(
    57                         self::GLOBAL_MINUTE_KEY,
    58                         self::GLOBAL_HOUR_KEY,
    59                         'global',
    60                         $global_min,
    61                         $global_hour
     52        /** Get the first refusal, or null when both quotas allowed the chat. */
     53        public function consume(): ?WP_Error {
     54                $global = $this->counters->consume(
     55                        self::GLOBAL_MINUTE,
     56                        self::GLOBAL_HOUR,
     57                        (int) ( $this->settings['global_rate_limit_per_minute'] ?? 60 ),
     58                        (int) ( $this->settings['global_rate_limit_per_hour'] ?? 500 ),
     59                        self::GLOBAL_SCOPE
    6260                );
    63 
    64                 if ( is_wp_error( $global ) ) {
    65                         if ( 'chathearth_rate_busy' !== $global->get_error_code() ) {
    66                                 $this->on_global_limit_hit();
    67                                 return $this->global_error();
     61                if ( 'busy' === $global ) {
     62                        return self::busy( 'global' );
     63                }
     64                if ( 'allowed' !== $global ) {
     65                        if ( null !== $this->record_incident ) {
     66                                try {
     67                                        ( $this->record_incident )();
     68                                } catch ( \Throwable $error ) {
     69                                        Logger::warning( 'The site-wide quota escalation could not be completed.' );
     70                                }
    6871                        }
    69                         return $global;
     72                        return new WP_Error(
     73                                'chathearth_global_rate_limited',
     74                                __( 'The chatbot is temporarily unavailable due to high demand. Please try again later.', 'chathearth' ),
     75                                array( 'status' => 429 )
     76                        );
    7077                }
    7178
    72                 $ip   = $this->client_ip();
    73                 $hash = md5( $ip );
    74 
    75                 $per_minute = (int) Options::get( 'rate_limit_per_minute', 10 );
    76                 $per_hour   = (int) Options::get( 'rate_limit_per_hour', 60 );
    77 
    78                 return $this->consume_quota(
    79                         'chathearth_rl_m_' . $hash,
    80                         'chathearth_rl_h_' . $hash,
    81                         $hash,
    82                         $per_minute,
    83                         $per_hour
     79                // A logged-in user is counted per account (feature 008); everyone else per network.
     80                $bucket  = $this->policy->for_request( $this->settings );
     81                $key     = $bucket['key'];
     82                $network = $this->counters->consume(
     83                        'chathearth_rl_m_' . $key,
     84                        'chathearth_rl_h_' . $key,
     85                        $bucket['minute'],
     86                        $bucket['hour'],
     87                        $key
    8488                );
    85         }
    86 
    87         /**
    88          * Consume one request against a minute/hour quota pair.
    89          *
    90          * @param string $minute_key Minute counter key.
    91          * @param string $hour_key   Hour counter key.
    92          * @param string $lock_id    Lock suffix (IP hash or "global").
    93          * @param int    $per_minute Limit per minute.
    94          * @param int    $per_hour   Limit per hour.
    95          * @return true|WP_Error
    96          */
    97         private function consume_quota( string $minute_key, string $hour_key, string $lock_id, int $per_minute, int $per_hour ) {
    98                 if ( wp_using_ext_object_cache() ) {
    99                         return $this->allow_via_object_cache( $minute_key, $hour_key, $per_minute, $per_hour );
     89                if ( 'allowed' === $network ) {
     90                        return null;
    10091                }
    101 
    102                 return $this->allow_via_locked_transients( $lock_id, $minute_key, $hour_key, $per_minute, $per_hour );
    103         }
    104 
    105         /**
    106          * Atomic counters via external object cache (Redis / Memcached).
    107          *
    108          * @param string $minute_key Minute counter key.
    109          * @param string $hour_key   Hour counter key.
    110          * @param int    $per_minute Limit per minute.
    111          * @param int    $per_hour   Limit per hour.
    112          * @return true|WP_Error
    113          */
    114         private function allow_via_object_cache( string $minute_key, string $hour_key, int $per_minute, int $per_hour ) {
    115                 wp_cache_add( $minute_key, 0, self::CACHE_GROUP, MINUTE_IN_SECONDS );
    116                 $minute_count = wp_cache_incr( $minute_key, 1, self::CACHE_GROUP );
    117 
    118                 if ( false === $minute_count ) {
    119                         return $this->busy_error();
     92                $this->counters->refund( self::GLOBAL_MINUTE, self::GLOBAL_HOUR, self::GLOBAL_SCOPE );
     93                if ( 'busy' === $network ) {
     94                        return self::busy( $bucket['scope'] );
    12095                }
    121 
    122                 if ( (int) $minute_count > $per_minute ) {
    123                         return $this->minute_error();
    124                 }
    125 
    126                 wp_cache_add( $hour_key, 0, self::CACHE_GROUP, HOUR_IN_SECONDS );
    127                 $hour_count = wp_cache_incr( $hour_key, 1, self::CACHE_GROUP );
    128 
    129                 if ( false === $hour_count ) {
    130                         return $this->busy_error();
    131                 }
    132 
    133                 if ( (int) $hour_count > $per_hour ) {
    134                         return $this->hour_error();
    135                 }
    136 
    137                 return true;
    138         }
    139 
    140         /**
    141          * Read/modify/write under a short-lived exclusive option lock.
    142          *
    143          * @param string $lock_id    Lock suffix.
    144          * @param string $minute_key Minute counter key.
    145          * @param string $hour_key   Hour counter key.
    146          * @param int    $per_minute Limit per minute.
    147          * @param int    $per_hour   Limit per hour.
    148          * @return true|WP_Error
    149          */
    150         private function allow_via_locked_transients( string $lock_id, string $minute_key, string $hour_key, int $per_minute, int $per_hour ) {
    151                 $lock_key = 'chathearth_rl_lock_' . $lock_id;
    152 
    153                 if ( ! $this->acquire_lock( $lock_key ) ) {
    154                         return $this->busy_error();
    155                 }
    156 
    157                 try {
    158                         $minute_count = (int) get_transient( $minute_key );
    159                         $hour_count   = (int) get_transient( $hour_key );
    160 
    161                         if ( $minute_count >= $per_minute ) {
    162                                 return $this->minute_error();
    163                         }
    164 
    165                         if ( $hour_count >= $per_hour ) {
    166                                 return $this->hour_error();
    167                         }
    168 
    169                         set_transient( $minute_key, $minute_count + 1, MINUTE_IN_SECONDS );
    170                         set_transient( $hour_key, $hour_count + 1, HOUR_IN_SECONDS );
    171 
    172                         return true;
    173                 } finally {
    174                         delete_option( $lock_key );
    175                 }
    176         }
    177 
    178         /**
    179          * Record a global-limit denial and escalate when the incident threshold is reached.
    180          */
    181         private function on_global_limit_hit(): void {
    182                 $threshold = (int) Options::get( 'global_limit_incident_threshold', 3 );
    183                 $incidents = $this->bump_incident_count();
    184 
    185                 if ( $incidents < $threshold ) {
    186                         return;
    187                 }
    188 
    189                 $this->escalate_to_admin( $incidents );
    190         }
    191 
    192         /**
    193          * Increment the hourly global-limit incident counter.
    194          */
    195         private function bump_incident_count(): int {
    196                 $key = self::GLOBAL_INCIDENT_KEY;
    197 
    198                 if ( wp_using_ext_object_cache() ) {
    199                         wp_cache_add( $key, 0, self::CACHE_GROUP, HOUR_IN_SECONDS );
    200                         $count = wp_cache_incr( $key, 1, self::CACHE_GROUP );
    201                         return false === $count ? 1 : (int) $count;
    202                 }
    203 
    204                 $lock_key = 'chathearth_rl_lock_inc';
    205                 if ( ! $this->acquire_lock( $lock_key ) ) {
    206                         $count = (int) get_transient( $key );
    207                         set_transient( $key, $count + 1, HOUR_IN_SECONDS );
    208                         return $count + 1;
    209                 }
    210 
    211                 try {
    212                         $count = (int) get_transient( $key );
    213                         $next  = $count + 1;
    214                         set_transient( $key, $next, HOUR_IN_SECONDS );
    215                         return $next;
    216                 } finally {
    217                         delete_option( $lock_key );
    218                 }
    219         }
    220 
    221         /**
    222          * Email admin, store notice, optionally disable chat (with email cooldown).
    223          *
    224          * @param int $incidents Incident count in the current window.
    225          */
    226         private function escalate_to_admin( int $incidents ): void {
    227                 $auto_disable = (bool) Options::get( 'auto_disable_on_global_escalation', true );
    228                 $disabled_now = false;
    229 
    230                 if ( $auto_disable && Options::is_chat_enabled() ) {
    231                         $settings                 = Options::all();
    232                         $settings['chat_enabled'] = false;
    233                         update_option( Options::OPTION_KEY, $settings );
    234                         $disabled_now = true;
    235                 }
    236 
    237                 $alert = array(
    238                         'time'          => time(),
    239                         'incidents'     => $incidents,
    240                         'auto_disabled' => $disabled_now,
    241                 );
    242                 update_option( self::ABUSE_ALERT_OPTION, $alert, false );
    243 
    244                 if ( get_transient( self::EMAIL_COOLDOWN_KEY ) ) {
    245                         return;
    246                 }
    247 
    248                 set_transient( self::EMAIL_COOLDOWN_KEY, 1, self::EMAIL_COOLDOWN );
    249 
    250                 $admin_email = get_option( 'admin_email' );
    251                 if ( ! is_string( $admin_email ) || '' === $admin_email ) {
    252                         return;
    253                 }
    254 
    255                 $site_name    = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
    256                 $settings_url = admin_url( 'options-general.php?page=chathearth&tab=protection' );
    257 
    258                 $subject = sprintf(
    259                         /* translators: %s: site name */
    260                         __( '[%s] ChatHearth - AI Chatbot: global rate limit escalation', 'chathearth' ),
    261                         $site_name
    262                 );
    263 
    264                 $lines = array(
    265                         __( 'ChatHearth - AI Chatbot blocked site-wide chat traffic after repeated global rate-limit hits.', 'chathearth' ),
    266                         '',
    267                         sprintf(
    268                                 /* translators: %d: number of global limit hits in the current hour */
    269                                 __( 'Global limit hits in the last hour: %d', 'chathearth' ),
    270                                 $incidents
    271                         ),
    272                         sprintf(
    273                                 /* translators: 1: per-minute limit, 2: per-hour limit */
    274                                 __( 'Configured global limits: %1$d/minute, %2$d/hour', 'chathearth' ),
    275                                 (int) Options::get( 'global_rate_limit_per_minute', 60 ),
    276                                 (int) Options::get( 'global_rate_limit_per_hour', 500 )
    277                         ),
    278                 );
    279 
    280                 if ( $disabled_now ) {
    281                         $lines[] = '';
    282                         $lines[] = __( 'The chatbot has been automatically disabled. Re-enable it under Settings → ChatHearth - AI Chatbot → Protection when ready.', 'chathearth' );
    283                 }
    284 
    285                 $lines[] = '';
    286                 $lines[] = __( 'Protection settings:', 'chathearth' );
    287                 $lines[] = $settings_url;
    288 
    289                 wp_mail( $admin_email, $subject, implode( "\n", $lines ) );
    290         }
    291 
    292         /**
    293          * Acquire an exclusive lock via add_option (succeeds only if the option is missing).
    294          *
    295          * @param string $lock_key Lock option name.
    296          */
    297         private function acquire_lock( string $lock_key ): bool {
    298                 for ( $i = 0; $i < self::LOCK_ATTEMPTS; $i++ ) {
    299                         $now = time();
    300 
    301                         $existing = get_option( $lock_key, false );
    302                         if ( false !== $existing && is_numeric( $existing ) && (int) $existing < $now ) {
    303                                 delete_option( $lock_key );
    304                         }
    305 
    306                         if ( add_option( $lock_key, $now + self::LOCK_TTL, '', false ) ) {
    307                                 return true;
    308                         }
    309 
    310                         usleep( self::LOCK_WAIT_US );
    311                 }
    312 
    313                 return false;
    314         }
    315 
    316         /**
    317          * Return the site-wide rate-limit error.
    318          *
    319          * @return WP_Error
    320          */
    321         private function global_error(): WP_Error {
    32296                return new WP_Error(
    323                         'chathearth_global_rate_limited',
    324                         __( 'The chatbot is temporarily unavailable due to high demand. Please try again later.', 'chathearth' ),
     97                        'chathearth_rate_limited',
     98                        $this->limit_message( 'hour' === $network, $bucket ),
    32599                        array( 'status' => 429 )
    326100                );
    … …  
    328102
    329103        /**
    330          * Return the per-minute rate-limit error.
     104         * The text of a minute or hour refusal: the owner's message with the limit that was reached and the window, or the
     105         * 1.4.9 text when the owner left the message empty.
    331106         *
    332          * @return WP_Error
     107         * @param bool                                                  $hour   Whether the hour limit was reached.
     108         * @param array{scope:string,key:string,minute:int,hour:int} $bucket The bucket that was counted.
    333109         */
    334         private function minute_error(): WP_Error {
    335                 return new WP_Error(
    336                         'chathearth_rate_limited',
    337                         __( 'Too many requests. Please wait a minute and try again.', 'chathearth' ),
    338                         array( 'status' => 429 )
     110        private function limit_message( bool $hour, array $bucket ): string {
     111                $template = isset( $this->settings['rate_limit_message'] ) && is_string( $this->settings['rate_limit_message'] ) ? $this->settings['rate_limit_message'] : '';
     112                $custom   = Limit_Message::render(
     113                        $template,
     114                        $hour ? $bucket['hour'] : $bucket['minute'],
     115                        $hour
     116                                /* translators: The window of a message limit, used in "You can send 10 messages per hour." Keep it a single lower-case word. */
     117                                ? __( 'hour', 'chathearth' )
     118                                /* translators: The window of a message limit, used in "You can send 10 messages per minute." Keep it a single lower-case word. */
     119                                : __( 'minute', 'chathearth' )
    339120                );
     121                if ( '' !== $custom ) {
     122                        return $custom;
     123                }
     124
     125                return $hour
     126                        ? __( 'Hourly message limit reached. Please try again later.', 'chathearth' )
     127                        : __( 'Too many requests. Please wait a minute and try again.', 'chathearth' );
    340128        }
    341129
    342130        /**
    343          * Return the per-hour rate-limit error.
     131         * Deny a storage failure while keeping the network and database details private.
    344132         *
    345          * @return WP_Error
     133         * @param 'global'|'network'|'user' $scope Scope type only.
    346134         */
    347         private function hour_error(): WP_Error {
    348                 return new WP_Error(
    349                         'chathearth_rate_limited',
    350                         __( 'Hourly message limit reached. Please try again later.', 'chathearth' ),
    351                         array( 'status' => 429 )
    352                 );
    353         }
    354 
    355         /**
    356          * Return the lock-contention error.
    357          *
    358          * @return WP_Error
    359          */
    360         private function busy_error(): WP_Error {
     135        private static function busy( string $scope ): WP_Error {
     136                Logger::warning( 'Chat quota counters are busy.', array( 'scope' => $scope ) );
    361137                return new WP_Error(
    362138                        'chathearth_rate_busy',
    … …  
    365141                );
    366142        }
    367 
    368         /**
    369          * Best-effort client IP.
    370          */
    371         private function client_ip(): string {
    372                 $ip = '';
    373                 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
    374                         $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
    375                 }
    376                 if ( false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
    377                         $ip = '0.0.0.0';
    378                 }
    379 
    380                 /**
    381                  * Filter the IP address used for chatbot rate limiting.
    382                  *
    383                  * @param string $ip Detected IP.
    384                  */
    385                 return (string) apply_filters( 'chathearth_client_ip', $ip );
    386         }
    387143}
  • chathearth/tags/2.0.0/includes/Security/index.php

    r3663506 r3833468  
    1 <?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     1<?php // Silence is golden.
  • chathearth/tags/2.0.0/includes/class-autoloader.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Simple PSR-4 style autoloader for ChatHearth.
     3 * Class autoloader, ported from 1.4.9 (research R1).
     4 *
     5 * Maps `ChatHearth\Sub\Class_Name` to `includes/Sub/class-class-name.php`.
    46 *
    57 * @package ChatHearth
    … …  
    2729
    2830        /**
    29          * Load a class file.
     31         * Load a class or interface file.
    3032         *
    3133         * @param string $fqcn Fully qualified class name.
    3234         */
    3335        public static function load( string $fqcn ): void {
     36                self::load_from( constant( 'CHATHEARTH_PATH' ), $fqcn );
     37        }
     38
     39        /**
     40         * Load a class or interface file from a plugin folder.
     41         *
     42         * The class file wins; when it does not exist, the interface file `interface-<name>.php` is tried.
     43         *
     44         * @param string $base Plugin folder with a trailing slash.
     45         * @param string $fqcn Fully qualified class name.
     46         */
     47        public static function load_from( string $base, string $fqcn ): void {
     48                $relative = self::relative_path( $fqcn );
     49                if ( null === $relative ) {
     50                        return;
     51                }
     52
     53                if ( is_readable( $base . $relative ) ) {
     54                        require_once $base . $relative;
     55                        return;
     56                }
     57
     58                $interface = self::interface_path( $fqcn );
     59                if ( null !== $interface && is_readable( $base . $interface ) ) {
     60                        require_once $base . $interface;
     61                }
     62        }
     63
     64        /**
     65         * Path of an interface file relative to the plugin folder, or null for a name outside `ChatHearth\`.
     66         *
     67         * A trailing `_Interface` is dropped: `Ai\Text_Generator_Interface` is `includes/Ai/interface-text-generator.php`.
     68         *
     69         * @param string $fqcn Fully qualified interface name.
     70         */
     71        public static function interface_path( string $fqcn ): ?string {
     72                $relative = self::relative_path( $fqcn );
     73                if ( null === $relative ) {
     74                        return null;
     75                }
     76
     77                // .../class-text-generator-interface.php becomes .../interface-text-generator.php.
     78                $path = (string) preg_replace( '#/class-([^/]+?)(?:-interface)?\.php$#', '/interface-$1.php', $relative );
     79
     80                return $path;
     81        }
     82
     83        /**
     84         * Path of a class file relative to the plugin folder, or null for a class outside `ChatHearth\`.
     85         *
     86         * @param string $fqcn Fully qualified class name.
     87         */
     88        public static function relative_path( string $fqcn ): ?string {
    3489                $prefix = __NAMESPACE__ . '\\';
    3590
    3691                if ( 0 !== strpos( $fqcn, $prefix ) ) {
    37                         return;
     92                        return null;
    3893                }
    3994
    40                 $relative   = substr( $fqcn, strlen( $prefix ) );
    41                 $parts      = explode( '\\', $relative );
    42                 $class_name = array_pop( $parts );
     95                $parts      = explode( '\\', substr( $fqcn, strlen( $prefix ) ) );
     96                $class_name = (string) array_pop( $parts );
    4397
    44                 // Convert Class_Name to class-class-name.php (WordPress style).
    45                 $file = 'class-' . str_replace( '_', '-', strtolower( preg_replace( '/([a-z])([A-Z])/', '$1-$2', $class_name ) ) ) . '.php';
     98                // Class_Name becomes class-class-name.php (WordPress file naming).
     99                $file = 'class-' . str_replace( '_', '-', strtolower( (string) preg_replace( '/([a-z])([A-Z])/', '$1-$2', $class_name ) ) ) . '.php';
     100                $dir  = 'includes/' . ( empty( $parts ) ? '' : implode( '/', $parts ) . '/' );
    46101
    47                 $dir = CHATHEARTH_PATH . 'includes/';
    48                 if ( ! empty( $parts ) ) {
    49                         $dir .= implode( '/', $parts ) . '/';
    50                 }
    51 
    52                 $path = $dir . $file;
    53                 if ( is_readable( $path ) ) {
    54                         require_once $path;
    55                 }
     102                return $dir . $file;
    56103        }
    57104}
  • chathearth/tags/2.0.0/includes/class-logger.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Conditional error logging into WordPress debug.log.
     3 * Masking logger (FR-022, research R13).
     4 *
     5 * Writes one `[chathearth] …` line to the PHP error log only when WP_DEBUG_LOG is already on. It never
     6 * defines or forces WP_DEBUG / WP_DEBUG_LOG. Context values whose key looks like a secret are masked.
    47 *
    58 * @package ChatHearth
    … …  
    1518
    1619/**
    17  * Writes to PHP / WordPress error log only when WP_DEBUG_LOG is already enabled.
    18  * Does not define or force WP_DEBUG / WP_DEBUG_LOG.
     20 * Logger.
    1921 */
    2022final class Logger {
    2123
    2224        /**
    23          * Log an error-level message when WP_DEBUG_LOG is on.
     25         * Key fragments that mark a context value as secret.
     26         */
     27        private const SECRET_FRAGMENTS = array( 'key', 'secret', 'pass', 'token', 'auth', 'cookie', 'nonce', 'ip', 'email' );
     28
     29        /**
     30         * Replacement writer (tests); null writes to the PHP error log.
     31         *
     32         * @var callable|null
     33         */
     34        private static $writer = null;
     35
     36        /**
     37         * Forced on/off state (tests); null follows WP_DEBUG_LOG.
     38         *
     39         * @var bool|null
     40         */
     41        private static $enabled = null;
     42
     43        /**
     44         * Log an error-level message.
    2445         *
    2546         * @param string               $message Human-readable message.
    26          * @param array<string, mixed> $context Optional scalar context (no secrets).
     47         * @param array<string, mixed> $context Optional scalar context.
    2748         */
    2849        public static function error( string $message, array $context = array() ): void {
    29                 if ( ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG ) {
     50                self::write( $message, $context );
     51        }
     52
     53        /**
     54         * Log a warning-level message.
     55         *
     56         * @param string               $message Human-readable message.
     57         * @param array<string, mixed> $context Optional scalar context.
     58         */
     59        public static function warning( string $message, array $context = array() ): void {
     60                self::write( 'warning: ' . $message, $context );
     61        }
     62
     63        /**
     64         * Replace the writer (tests). Pass null to restore the default.
     65         *
     66         * @param callable|null $writer Receives the finished line.
     67         */
     68        public static function set_writer( ?callable $writer ): void {
     69                self::$writer = $writer;
     70        }
     71
     72        /**
     73         * Force logging on or off (tests). Pass null to follow WP_DEBUG_LOG.
     74         *
     75         * @param bool|null $enabled State.
     76         */
     77        public static function set_enabled( ?bool $enabled ): void {
     78                self::$enabled = $enabled;
     79        }
     80
     81        /**
     82         * Build and write one line.
     83         *
     84         * @param string               $message Message.
     85         * @param array<string, mixed> $context Context.
     86         */
     87        private static function write( string $message, array $context ): void {
     88                if ( ! self::is_enabled() ) {
    3089                        return;
    3190                }
    3291
    33                 $line = '[chathearth] ' . self::sanitize_line( $message );
    34 
    35                 if ( ! empty( $context ) ) {
    36                         $parts = array();
    37                         foreach ( $context as $key => $value ) {
    38                                 if ( ! is_scalar( $value ) && null !== $value ) {
    39                                         continue;
    40                                 }
    41                                 $parts[] = sanitize_key( (string) $key ) . '=' . self::sanitize_line( (string) $value );
     92                $line  = '[chathearth] ' . self::single_line( $message );
     93                $parts = array();
     94                foreach ( $context as $key => $value ) {
     95                        if ( ! is_scalar( $value ) && null !== $value ) {
     96                                continue;
    4297                        }
    43                         if ( ! empty( $parts ) ) {
    44                                 $line .= ' ' . implode( ' ', $parts );
    45                         }
     98                        $name    = (string) preg_replace( '/[^a-z0-9_\-]/', '', strtolower( (string) $key ) );
     99                        $parts[] = $name . '=' . ( self::is_secret_key( $name ) ? '[redacted]' : self::single_line( (string) $value ) );
     100                }
     101                if ( ! empty( $parts ) ) {
     102                        $line .= ' ' . implode( ' ', $parts );
    46103                }
    47104
    48                 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- intentional when WP_DEBUG_LOG is on.
     105                if ( null !== self::$writer ) {
     106                        call_user_func( self::$writer, $line );
     107                        return;
     108                }
     109
     110                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional: only runs when WP_DEBUG_LOG is on.
    49111                error_log( $line );
    50112        }
    51113
    52114        /**
    53          * Collapse newlines so log lines stay single-line.
     115         * Whether debug logging is on.
     116         */
     117        private static function is_enabled(): bool {
     118                if ( null !== self::$enabled ) {
     119                        return self::$enabled;
     120                }
     121
     122                return defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG;
     123        }
     124
     125        /**
     126         * Whether a context key looks like it holds a secret.
     127         *
     128         * @param string $name Normalised key.
     129         */
     130        private static function is_secret_key( string $name ): bool {
     131                foreach ( self::SECRET_FRAGMENTS as $fragment ) {
     132                        if ( false !== strpos( $name, $fragment ) ) {
     133                                return true;
     134                        }
     135                }
     136
     137                return false;
     138        }
     139
     140        /**
     141         * Collapse line breaks so a log entry stays one line.
    54142         *
    55143         * @param string $text Raw text.
    56144         */
    57         private static function sanitize_line( string $text ): string {
    58                 return trim( preg_replace( '/[\r\n]+/', ' ', $text ) ?? $text );
     145        private static function single_line( string $text ): string {
     146                return trim( (string) preg_replace( '/[\r\n]+/', ' ', $text ) );
    59147        }
    60148}
  • chathearth/tags/2.0.0/includes/class-options.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Plugin options helper.
     3 * 1.4.9 settings facade (research R3): the static calls other code already makes.
    44 *
    55 * @package ChatHearth
    … …  
    1414}
    1515
     16use ChatHearth\Settings\Settings_Repository;
     17use ChatHearth\Settings\Settings_Schema;
     18
    1619/**
    17  * Reads and sanitizes plugin settings.
     20 * Static access to the settings. Other 1.4.9 helpers return with the feature that owns their behaviour.
    1821 */
    1922final class Options {
    … …  
    2730         */
    2831        public static function defaults(): array {
    29                 return array(
    30                         'chat_enabled'                      => true,
    31                         'icon_shape'                        => 'circle',
    32                         'icon_border_color'                 => '#1e293b',
    33                         'icon_background_color'             => '#0f172a',
    34                         'icon_color'                        => '#ffffff',
    35                         'icon_size'                         => 56,
    36                         'position'                          => 'bottom-right',
    37                         'popup_size'                        => 'medium',
    38                         'header_title'                      => 'Chat with us',
    39                         'user_bubble_color'                 => '#0f172a',
    40                         'assistant_bubble_color'            => '#e2e8f0',
    41                         'welcome_message'                   => 'Hi! How can I help you today?',
    42                         'starter_phrases'                   => "What do you offer?\nHow can I contact you?\nTell me about your services",
    43                         'ai_provider'                       => 'openai',
    44                         'ai_model'                          => defined( 'CHATHEARTH_DEFAULT_MODEL' ) ? CHATHEARTH_DEFAULT_MODEL : 'gpt-4.1',
    45                         'system_prompt'                     => 'You are a helpful assistant for this website. Be concise, friendly, and accurate. If you do not know something, say so.',
    46                         'rate_limit_per_minute'             => 10,
    47                         'rate_limit_per_hour'               => 60,
    48                         'global_rate_limit_per_minute'      => 60,
    49                         'global_rate_limit_per_hour'        => 500,
    50                         'global_limit_incident_threshold'   => 3,
    51                         'auto_disable_on_global_escalation' => true,
    52                         'recaptcha_site_key'                => '',
    53                         'recaptcha_secret_key'              => '',
    54                         'recaptcha_min_score'               => 0.5,
    55                         'max_message_length'                => 2000,
    56                         'max_history_messages'              => 20,
    57                         'content_moderation_enabled'        => true,
    58                         'moderation_use_openai'             => true,
    59                         'moderation_disallowed_phrases'     => '',
    60                         'moderation_block_message'          => 'Sorry, that message cannot be processed. Please rephrase and try again.',
    61                         'rag_enabled'                       => false,
    62                         'rag_vector_store'                  => 'builtin',
    63                         'rag_post_types'                    => array( 'post', 'page', 'product' ),
    64                         'rag_taxonomies'                    => array( 'category', 'post_tag', 'product_cat', 'product_tag' ),
    65                         'rag_include_site_identity'         => true,
    66                         'rag_include_woocommerce'           => true,
    67                         'rag_top_k'                         => 6,
    68                         'rag_chunk_size'                    => 1800,
    69                 );
     32                return Settings_Schema::defaults();
    7033        }
    7134
    7235        /**
    73          * Get all settings merged with defaults.
     36         * Every setting with a valid value.
    7437         *
    7538         * @return array<string, mixed>
    7639         */
    7740        public static function all(): array {
    78                 $stored = get_option( self::OPTION_KEY, array() );
    79                 if ( ! is_array( $stored ) ) {
    80                         $stored = array();
    81                 }
    82 
    83                 $merged                     = array_merge( self::defaults(), $stored );
    84                 $merged['rag_vector_store'] = 'builtin';
    85                 foreach ( self::retired_vector_store_keys() as $retired ) {
    86                         unset( $merged[ $retired ] );
    87                 }
    88 
    89                 return $merged;
     41                return self::repository()->all();
    9042        }
    9143
    9244        /**
    93          * Drop Chroma/Pinecone settings so RAG never depends on extra servers.
     45         * One setting.
     46         *
     47         * @param string $key      Setting key.
     48         * @param mixed  $fallback Returned when the key is not a declared setting.
     49         * @return mixed
    9450         */
    95         public static function maybe_use_wordpress_vector_store(): void {
    96                 $stored = get_option( self::OPTION_KEY, false );
    97                 if ( ! is_array( $stored ) ) {
    98                         return;
    99                 }
     51        public static function get( string $key, $fallback = null ) {
     52                $all = self::repository()->all();
    10053
    101                 $changed = false;
    102                 if ( ( $stored['rag_vector_store'] ?? 'builtin' ) !== 'builtin' ) {
    103                         $stored['rag_vector_store'] = 'builtin';
    104                         $changed                    = true;
    105                 }
    106 
    107                 foreach ( self::retired_vector_store_keys() as $key ) {
    108                         if ( array_key_exists( $key, $stored ) ) {
    109                                 unset( $stored[ $key ] );
    110                                 $changed = true;
    111                         }
    112                 }
    113 
    114                 if ( $changed ) {
    115                         update_option( self::OPTION_KEY, $stored );
    116                 }
     54                return array_key_exists( $key, $all ) ? $all[ $key ] : $fallback;
    11755        }
    11856
    11957        /**
    120          * Get a single setting.
    121          *
    122          * @param string $key     Setting key.
    123          * @param mixed  $fallback Optional fallback.
    124          * @return mixed
     58         * The repository from the container.
    12559         */
    126         public static function get( string $key, $fallback = null ) {
    127                 $all = self::all();
    128 
    129                 if ( array_key_exists( $key, $all ) ) {
    130                         return $all[ $key ];
    131                 }
    132 
    133                 return $fallback;
    134         }
    135 
    136         /**
    137          * Whether the chatbot is enabled.
    138          */
    139         public static function is_chat_enabled(): bool {
    140                 return (bool) self::get( 'chat_enabled', true );
    141         }
    142 
    143         /**
    144          * Whether Google reCAPTCHA v3 is active (both site and secret keys configured).
    145          */
    146         public static function is_recaptcha_enabled(): bool {
    147                 $site   = self::recaptcha_site_key();
    148                 $secret = self::recaptcha_secret_key();
    149 
    150                 return '' !== $site && '' !== $secret;
    151         }
    152 
    153         /**
    154          * Resolved reCAPTCHA v3 site key (environment/constant wins over settings).
    155          */
    156         public static function recaptcha_site_key(): string {
    157                 return self::resolved_secret( 'CHATHEARTH_RECAPTCHA_SITE_KEY', 'recaptcha_site_key' );
    158         }
    159 
    160         /**
    161          * Resolved reCAPTCHA v3 secret key (environment/constant wins over settings).
    162          */
    163         public static function recaptcha_secret_key(): string {
    164                 return self::resolved_secret( 'CHATHEARTH_RECAPTCHA_SECRET_KEY', 'recaptcha_secret_key' );
    165         }
    166 
    167         /**
    168          * Whether site/secret keys come from the server environment rather than plugin settings.
    169          */
    170         public static function recaptcha_keys_from_environment(): bool {
    171                 $site   = self::env_or_constant( 'CHATHEARTH_RECAPTCHA_SITE_KEY' );
    172                 $secret = self::env_or_constant( 'CHATHEARTH_RECAPTCHA_SECRET_KEY' );
    173 
    174                 return '' !== $site && '' !== $secret;
    175         }
    176 
    177         /**
    178          * Minimum v3 score (0–1) required to unlock chat.
    179          */
    180         public static function recaptcha_min_score(): float {
    181                 $score = (float) self::get( 'recaptcha_min_score', 0.5 );
    182                 if ( $score < 0 ) {
    183                         return 0.0;
    184                 }
    185                 if ( $score > 1 ) {
    186                         return 1.0;
    187                 }
    188 
    189                 return $score;
    190         }
    191 
    192         /**
    193          * Whether content moderation (keywords and/or OpenAI Moderations) is enabled.
    194          */
    195         public static function is_content_moderation_enabled(): bool {
    196                 return (bool) self::get( 'content_moderation_enabled', true );
    197         }
    198 
    199         /**
    200          * Whether the OpenAI Moderations API layer is enabled (requires master toggle too).
    201          */
    202         public static function is_moderation_openai_enabled(): bool {
    203                 return (bool) self::get( 'moderation_use_openai', true );
    204         }
    205 
    206         /**
    207          * Disallowed phrases as a list of strings (one per line in settings).
    208          *
    209          * @return list<string>
    210          */
    211         public static function moderation_disallowed_phrases_list(): array {
    212                 $raw   = (string) self::get( 'moderation_disallowed_phrases', '' );
    213                 $lines = preg_split( '/\r\n|\r|\n/', $raw );
    214                 if ( ! is_array( $lines ) ) {
    215                         return array();
    216                 }
    217 
    218                 $out = array();
    219                 foreach ( $lines as $line ) {
    220                         $line = trim( (string) $line );
    221                         if ( '' !== $line ) {
    222                                 $out[] = $line;
    223                         }
    224                 }
    225 
    226                 return $out;
    227         }
    228 
    229         /**
    230          * Supported AI providers for settings (v1: OpenAI only).
    231          *
    232          * @return array<string, string> Provider id => label.
    233          */
    234         public static function available_providers(): array {
    235                 return array(
    236                         'openai' => 'OpenAI',
    237                 );
    238         }
    239 
    240         /**
    241          * OpenAI chat models offered in settings.
    242          *
    243          * @return array<string, string> Model id => label.
    244          */
    245         public static function available_openai_models(): array {
    246                 return array(
    247                         'gpt-4.1'      => 'GPT-4.1',
    248                         'gpt-4.1-mini' => 'GPT-4.1 Mini',
    249                         'gpt-4.1-nano' => 'GPT-4.1 Nano',
    250                         'gpt-4o'       => 'GPT-4o',
    251                         'gpt-4o-mini'  => 'GPT-4o Mini',
    252                         'o4-mini'      => 'o4-mini',
    253                         'o3-mini'      => 'o3-mini',
    254                 );
    255         }
    256 
    257         /**
    258          * Starter phrases as a list of strings.
    259          *
    260          * @return list<string>
    261          */
    262         public static function starter_phrases_list(): array {
    263                 $raw   = (string) self::get( 'starter_phrases', '' );
    264                 $lines = preg_split( '/\r\n|\r|\n/', $raw );
    265                 if ( ! is_array( $lines ) ) {
    266                         return array();
    267                 }
    268 
    269                 $out = array();
    270                 foreach ( $lines as $line ) {
    271                         $line = trim( (string) $line );
    272                         if ( '' !== $line ) {
    273                                 $out[] = $line;
    274                         }
    275                 }
    276 
    277                 return $out;
    278         }
    279 
    280         /**
    281          * Sanitize settings array from the admin form.
    282          *
    283          * @param mixed $input Raw input.
    284          * @return array<string, mixed>
    285          */
    286         public static function sanitize( $input ): array {
    287                 $defaults = self::defaults();
    288                 $input    = is_array( $input ) ? $input : array();
    289                 $out      = self::all();
    290 
    291                 $out['chat_enabled'] = ! empty( $input['chat_enabled'] );
    292 
    293                 $shape             = isset( $input['icon_shape'] ) ? sanitize_key( (string) $input['icon_shape'] ) : $defaults['icon_shape'];
    294                 $out['icon_shape'] = in_array( $shape, array( 'circle', 'square' ), true ) ? $shape : $defaults['icon_shape'];
    295 
    296                 foreach ( array( 'icon_border_color', 'icon_background_color', 'icon_color', 'user_bubble_color', 'assistant_bubble_color' ) as $color_key ) {
    297                         if ( isset( $input[ $color_key ] ) ) {
    298                                 $color             = sanitize_hex_color( (string) $input[ $color_key ] );
    299                                 $out[ $color_key ] = $color ? $color : $defaults[ $color_key ];
    300                         }
    301                 }
    302 
    303                 $size             = isset( $input['icon_size'] ) ? absint( $input['icon_size'] ) : (int) $defaults['icon_size'];
    304                 $out['icon_size'] = max( 40, min( 96, $size ) );
    305 
    306                 $position        = isset( $input['position'] ) ? sanitize_key( (string) $input['position'] ) : $defaults['position'];
    307                 $out['position'] = in_array( $position, array( 'bottom-right', 'bottom-left' ), true ) ? $position : $defaults['position'];
    308 
    309                 $popup             = isset( $input['popup_size'] ) ? sanitize_key( (string) $input['popup_size'] ) : $defaults['popup_size'];
    310                 $out['popup_size'] = in_array( $popup, array( 'small', 'medium', 'large' ), true ) ? $popup : $defaults['popup_size'];
    311 
    312                 if ( isset( $input['header_title'] ) ) {
    313                         $out['header_title'] = sanitize_text_field( (string) $input['header_title'] );
    314                 }
    315 
    316                 if ( isset( $input['welcome_message'] ) ) {
    317                         $out['welcome_message'] = sanitize_textarea_field( (string) $input['welcome_message'] );
    318                 }
    319 
    320                 if ( isset( $input['starter_phrases'] ) ) {
    321                         $out['starter_phrases'] = sanitize_textarea_field( (string) $input['starter_phrases'] );
    322                 }
    323 
    324                 if ( isset( $input['system_prompt'] ) ) {
    325                         $out['system_prompt'] = sanitize_textarea_field( (string) $input['system_prompt'] );
    326                 }
    327 
    328                 $provider           = isset( $input['ai_provider'] ) ? sanitize_key( (string) $input['ai_provider'] ) : $defaults['ai_provider'];
    329                 $out['ai_provider'] = array_key_exists( $provider, self::available_providers() ) ? $provider : $defaults['ai_provider'];
    330 
    331                 $model           = isset( $input['ai_model'] ) ? sanitize_text_field( (string) $input['ai_model'] ) : $defaults['ai_model'];
    332                 $out['ai_model'] = array_key_exists( $model, self::available_openai_models() ) ? $model : $defaults['ai_model'];
    333 
    334                 $per_min                      = isset( $input['rate_limit_per_minute'] ) ? absint( $input['rate_limit_per_minute'] ) : (int) $defaults['rate_limit_per_minute'];
    335                 $out['rate_limit_per_minute'] = max( 1, min( 120, $per_min ) );
    336 
    337                 $per_hour                   = isset( $input['rate_limit_per_hour'] ) ? absint( $input['rate_limit_per_hour'] ) : (int) $defaults['rate_limit_per_hour'];
    338                 $out['rate_limit_per_hour'] = max( 1, min( 1000, $per_hour ) );
    339 
    340                 $g_min                               = isset( $input['global_rate_limit_per_minute'] ) ? absint( $input['global_rate_limit_per_minute'] ) : (int) $defaults['global_rate_limit_per_minute'];
    341                 $out['global_rate_limit_per_minute'] = max( 1, min( 1000, $g_min ) );
    342 
    343                 $g_hour                            = isset( $input['global_rate_limit_per_hour'] ) ? absint( $input['global_rate_limit_per_hour'] ) : (int) $defaults['global_rate_limit_per_hour'];
    344                 $out['global_rate_limit_per_hour'] = max( 1, min( 10000, $g_hour ) );
    345 
    346                 $threshold                              = isset( $input['global_limit_incident_threshold'] ) ? absint( $input['global_limit_incident_threshold'] ) : (int) $defaults['global_limit_incident_threshold'];
    347                 $out['global_limit_incident_threshold'] = max( 1, min( 50, $threshold ) );
    348 
    349                 $out['auto_disable_on_global_escalation'] = ! empty( $input['auto_disable_on_global_escalation'] );
    350 
    351                 if ( isset( $input['recaptcha_site_key'] ) ) {
    352                         $out['recaptcha_site_key'] = sanitize_text_field( (string) $input['recaptcha_site_key'] );
    353                 }
    354 
    355                 if ( ! empty( $input['recaptcha_clear_secret'] ) ) {
    356                         $out['recaptcha_secret_key'] = '';
    357                 } elseif ( isset( $input['recaptcha_secret_key'] ) ) {
    358                         $secret = trim( (string) $input['recaptcha_secret_key'] );
    359                         // Leave blank to keep the existing secret.
    360                         if ( '' !== $secret ) {
    361                                 $out['recaptcha_secret_key'] = sanitize_text_field( $secret );
    362                         }
    363                 }
    364 
    365                 if ( isset( $input['recaptcha_min_score'] ) ) {
    366                         $score                      = (float) $input['recaptcha_min_score'];
    367                         $out['recaptcha_min_score'] = max( 0.0, min( 1.0, round( $score, 2 ) ) );
    368                 }
    369 
    370                 $max_len                   = isset( $input['max_message_length'] ) ? absint( $input['max_message_length'] ) : (int) $defaults['max_message_length'];
    371                 $out['max_message_length'] = max( 100, min( 8000, $max_len ) );
    372 
    373                 $max_hist                    = isset( $input['max_history_messages'] ) ? absint( $input['max_history_messages'] ) : (int) $defaults['max_history_messages'];
    374                 $out['max_history_messages'] = max( 2, min( 50, $max_hist ) );
    375 
    376                 $out['content_moderation_enabled'] = ! empty( $input['content_moderation_enabled'] );
    377                 $out['moderation_use_openai']      = ! empty( $input['moderation_use_openai'] );
    378 
    379                 if ( isset( $input['moderation_disallowed_phrases'] ) ) {
    380                         $out['moderation_disallowed_phrases'] = sanitize_textarea_field( (string) $input['moderation_disallowed_phrases'] );
    381                 }
    382 
    383                 if ( isset( $input['moderation_block_message'] ) ) {
    384                         $msg                             = sanitize_text_field( (string) $input['moderation_block_message'] );
    385                         $out['moderation_block_message'] = '' !== $msg ? $msg : (string) $defaults['moderation_block_message'];
    386                 }
    387 
    388                 if ( isset( $input['rag_vector_store'] ) ) {
    389                         $out['rag_enabled'] = ! empty( $input['rag_enabled'] );
    390 
    391                         $out['rag_vector_store'] = 'builtin';
    392 
    393                         $out['rag_post_types'] = self::sanitize_key_list( $input['rag_post_types'] ?? array() );
    394                         $out['rag_taxonomies'] = self::sanitize_key_list( $input['rag_taxonomies'] ?? array() );
    395 
    396                         $out['rag_include_site_identity'] = ! empty( $input['rag_include_site_identity'] );
    397                         $out['rag_include_woocommerce']   = ! empty( $input['rag_include_woocommerce'] );
    398 
    399                         $top_k            = isset( $input['rag_top_k'] ) ? absint( $input['rag_top_k'] ) : (int) $defaults['rag_top_k'];
    400                         $out['rag_top_k'] = max( 1, min( 12, $top_k ) );
    401 
    402                         $chunk                 = isset( $input['rag_chunk_size'] ) ? absint( $input['rag_chunk_size'] ) : (int) $defaults['rag_chunk_size'];
    403                         $out['rag_chunk_size'] = max( 400, min( 4000, $chunk ) );
    404                 }
    405 
    406                 return $out;
    407         }
    408 
    409         /**
    410          * Whether RAG retrieval is enabled.
    411          */
    412         public static function is_rag_enabled(): bool {
    413                 return (bool) self::get( 'rag_enabled', false );
    414         }
    415 
    416         /**
    417          * Selected post types for the knowledge base.
    418          *
    419          * @return list<string>
    420          */
    421         public static function rag_post_types(): array {
    422                 $types = self::get( 'rag_post_types', array() );
    423                 return self::sanitize_key_list( is_array( $types ) ? $types : array() );
    424         }
    425 
    426         /**
    427          * Selected taxonomies for the knowledge base.
    428          *
    429          * @return list<string>
    430          */
    431         public static function rag_taxonomies(): array {
    432                 $taxes = self::get( 'rag_taxonomies', array() );
    433                 return self::sanitize_key_list( is_array( $taxes ) ? $taxes : array() );
    434         }
    435 
    436         /**
    437          * Whether site identity is indexed.
    438          */
    439         public static function rag_include_site_identity(): bool {
    440                 return (bool) self::get( 'rag_include_site_identity', true );
    441         }
    442 
    443         /**
    444          * Whether the WooCommerce store summary is indexed.
    445          */
    446         public static function rag_include_woocommerce(): bool {
    447                 return (bool) self::get( 'rag_include_woocommerce', true );
    448         }
    449 
    450         /**
    451          * Public post types offered in the Knowledge Base UI (no attachments).
    452          *
    453          * @return array<array-key, string> slug => label.
    454          */
    455         public static function available_content_post_types(): array {
    456                 $objects = get_post_types( array( 'public' => true ), 'objects' );
    457                 $out     = array();
    458                 foreach ( $objects as $name => $object ) {
    459                         if ( 'attachment' === $name ) {
    460                                 continue;
    461                         }
    462                         $label        = isset( $object->labels->name ) ? (string) $object->labels->name : (string) $name;
    463                         $out[ $name ] = $label;
    464                 }
    465 
    466                 return $out;
    467         }
    468 
    469         /**
    470          * Public taxonomies offered in the Knowledge Base UI.
    471          *
    472          * @return array<array-key, string> slug => label.
    473          */
    474         public static function available_content_taxonomies(): array {
    475                 $objects = get_taxonomies( array( 'public' => true ), 'objects' );
    476                 $out     = array();
    477                 foreach ( $objects as $name => $object ) {
    478                         $label                 = isset( $object->labels->name ) ? (string) $object->labels->name : (string) $name;
    479                         $out[ (string) $name ] = $label;
    480                 }
    481 
    482                 return $out;
    483         }
    484 
    485         /**
    486          * Settings keys for stores that required extra software or accounts.
    487          *
    488          * @return list<string>
    489          */
    490         private static function retired_vector_store_keys(): array {
    491                 return array(
    492                         'rag_chroma_url',
    493                         'rag_chroma_collection',
    494                         'rag_chroma_tenant',
    495                         'rag_chroma_database',
    496                         'rag_pinecone_api_key',
    497                         'rag_pinecone_host',
    498                         'rag_pinecone_namespace',
    499                 );
    500         }
    501 
    502         /**
    503          * Read a secret from a PHP constant, then the process environment, then settings.
    504          *
    505          * @param string $env_name Constant / environment variable name.
    506          * @param string $option_key Settings key.
    507          */
    508         private static function resolved_secret( string $env_name, string $option_key ): string {
    509                 $from_env = self::env_or_constant( $env_name );
    510                 if ( '' !== $from_env ) {
    511                         return $from_env;
    512                 }
    513 
    514                 return trim( (string) self::get( $option_key, '' ) );
    515         }
    516 
    517         /**
    518          * Value from a PHP constant or environment variable.
    519          *
    520          * @param string $name Constant and environment variable name.
    521          */
    522         private static function env_or_constant( string $name ): string {
    523                 /**
    524                  * Short-circuit environment/constant secret lookup (tests).
    525                  *
    526                  * Return a string to use that value (empty string disables the env key).
    527                  *
    528                  * @param string|null $pre  Existing override.
    529                  * @param string      $name Variable name.
    530                  */
    531                 $pre = apply_filters( 'chathearth_pre_env_secret', null, $name );
    532                 if ( is_string( $pre ) ) {
    533                         return trim( $pre );
    534                 }
    535                 if ( defined( $name ) ) {
    536                         $value = constant( $name );
    537                         if ( is_string( $value ) || is_numeric( $value ) ) {
    538                                 $value = trim( (string) $value );
    539                                 if ( '' !== $value ) {
    540                                         return $value;
    541                                 }
    542                         }
    543                 }
    544 
    545                 $env = getenv( $name );
    546                 if ( is_string( $env ) ) {
    547                         $env = trim( $env );
    548                         if ( '' !== $env ) {
    549                                 return $env;
    550                         }
    551                 }
    552 
    553                 return '';
    554         }
    555 
    556         /**
    557          * Sanitize a list of WP slugs.
    558          *
    559          * @param mixed $value Raw list.
    560          * @return list<string>
    561          */
    562         private static function sanitize_key_list( $value ): array {
    563                 if ( ! is_array( $value ) ) {
    564                         return array();
    565                 }
    566 
    567                 $out = array();
    568                 foreach ( $value as $item ) {
    569                         $key = sanitize_key( (string) $item );
    570                         if ( '' !== $key ) {
    571                                 $out[] = $key;
    572                         }
    573                 }
    574 
    575                 return array_values( array_unique( $out ) );
     60        private static function repository(): Settings_Repository {
     61                return Plugin::instance()->get( Settings_Repository::class );
    57662        }
    57763}
  • chathearth/tags/2.0.0/includes/class-plugin.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Main plugin bootstrap.
     3 * Plugin container and start-up (research R2).
     4 *
     5 * A small lazy service container: each service is built once per request, on first use. It holds services,
     6 * never request state.
    47 *
    58 * @package ChatHearth
    … …  
    1518
    1619use ChatHearth\Admin\Admin_Notices;
     20use ChatHearth\Admin\Plugin_Links;
    1721use ChatHearth\Admin\Privacy;
    18 use ChatHearth\Admin\Settings_Page;
    19 use ChatHearth\Frontend\Assets;
    20 use ChatHearth\Rag\Current_Page;
    21 use ChatHearth\Rag\Indexer;
     22use ChatHearth\Admin\Reenable_Action;
     23use ChatHearth\Admin\Settings\Abuse_Alert_Actions;
     24use ChatHearth\Admin\Settings\Rate_Limit_Reset_Action;
     25use ChatHearth\Admin\Settings\Settings_Page;
     26use ChatHearth\Admin\Settings\Site_Status;
     27use ChatHearth\Ai\Connectors_Generator;
     28use ChatHearth\Ai\Embedding_Client;
     29use ChatHearth\Ai\Openai_Embedding_Client;
     30use ChatHearth\Chat\Ban_Stage;
     31use ChatHearth\Chat\Catalog_Stage;
     32use ChatHearth\Chat\Chat_Pipeline;
     33use ChatHearth\Chat\Generation_Stage;
     34use ChatHearth\Chat\Honeypot_Stage;
     35use ChatHearth\Chat\Input_Stage;
     36use ChatHearth\Chat\Instructions_Stage;
     37use ChatHearth\Chat\Limits_Stage;
     38use ChatHearth\Chat\Moderation_Stage;
     39use ChatHearth\Chat\Page_Stage;
     40use ChatHearth\Chat\Reply_Stage;
     41use ChatHearth\Chat\Retrieval_Stage;
     42use ChatHearth\Chat\Verification_Stage;
     43use ChatHearth\Commerce\Cart_Service;
     44use ChatHearth\Commerce\Catalog_Block;
     45use ChatHearth\Commerce\Product_Card;
     46use ChatHearth\Commerce\Product_Catalog;
     47use ChatHearth\Commerce\Product_Name_Index;
     48use ChatHearth\Commerce\Product_Name_Index_Invalidator;
     49use ChatHearth\Commerce\Product_Name_Normaliser;
     50use ChatHearth\Commerce\Store_Links;
     51use ChatHearth\Content\Markdown_Exporter;
     52use ChatHearth\Frontend\Current_Page;
     53use ChatHearth\Frontend\Launcher_Icon;
     54use ChatHearth\Frontend\Widget;
     55use ChatHearth\Frontend\Widget_Config;
     56use ChatHearth\Grounding\Current_Page_Section;
     57use ChatHearth\Grounding\Page_Link_Matcher;
     58use ChatHearth\Grounding\Page_Resolver;
     59use ChatHearth\Grounding\Site_Context;
     60use ChatHearth\Grounding\Site_Context_Invalidator;
     61use ChatHearth\Grounding\Site_Grounding;
     62use ChatHearth\Jobs\Job_Runner;
     63use ChatHearth\Jobs\Job_Runner_Factory;
     64use ChatHearth\Kb\Change_Listener;
     65use ChatHearth\Kb\Chunker;
     66use ChatHearth\Kb\Entry_Presenter;
     67use ChatHearth\Kb\Entry_Repository;
     68use ChatHearth\Kb\Kb_Entry_Toggle;
     69use ChatHearth\Kb\Markdown_Files;
     70use ChatHearth\Kb\Passage_Repository;
     71use ChatHearth\Kb\Sources;
     72use ChatHearth\Kb\Status_Report;
     73use ChatHearth\Kb\Store_Check;
     74use ChatHearth\Kb\Sync_Job;
     75use ChatHearth\Kb\Sync_State;
     76use ChatHearth\Lifecycle\Activator;
     77use ChatHearth\Migrations\Migration_Runner;
     78use ChatHearth\Moderation\Content_Moderation;
     79use ChatHearth\Moderation\Openai_Moderation_Client;
     80use ChatHearth\Moderation\Verdict_Cache;
     81use ChatHearth\Rag\Comparison_Detector;
     82use ChatHearth\Rag\Knowledge_Section;
    2283use ChatHearth\Rag\Retriever;
    23 use ChatHearth\Rag\Schema;
    24 use ChatHearth\Rag\Site_Grounding;
     84use ChatHearth\Rag\Source_Gate;
     85use ChatHearth\Readiness\Readiness_Checker;
    2586use ChatHearth\Rest\Cart_Controller;
    2687use ChatHearth\Rest\Chat_Controller;
    2788use ChatHearth\Rest\Kb_Controller;
     89use ChatHearth\Rest\Kb_Permission;
     90use ChatHearth\Rest\Kb_Status_Controller;
     91use ChatHearth\Rest\Nonce_Controller;
     92use ChatHearth\Rest\Nonce_Throttle;
     93use ChatHearth\Rest\Recaptcha_Controller;
     94use ChatHearth\Rest\Request_Guard;
     95use ChatHearth\Security\Access_Check;
     96use ChatHearth\Security\Client_Address;
     97use ChatHearth\Security\Counter_Generation;
     98use ChatHearth\Security\Counters;
     99use ChatHearth\Security\Escalation;
     100use ChatHearth\Security\Escalation_Mailer;
     101use ChatHearth\Security\Human_Check;
     102use ChatHearth\Security\Human_Pass;
     103use ChatHearth\Security\Option_Lock;
     104use ChatHearth\Security\Quota_Policy;
     105use ChatHearth\Security\Rate_Limiter;
     106use ChatHearth\Security\Rearm_Pause;
     107use ChatHearth\Security\Reenable_Link;
     108use ChatHearth\Security\Recaptcha_V3;
     109use ChatHearth\Security\Trusted_Proxy;
     110use ChatHearth\Settings\Server_Overrides;
     111use ChatHearth\Settings\Settings_Repository;
     112use ChatHearth\Settings\Settings_Sanitizer;
    28113
    29114/**
    30  * Plugin singleton.
     115 * Plugin singleton and service container.
    31116 */
    32117final class Plugin {
    … …  
    38123         */
    39124        private static $instance = null;
     125
     126        /**
     127         * Services built so far, by class name.
     128         *
     129         * @var array<string, object>
     130         */
     131        private $services = array();
     132
     133        /**
     134         * Whether boot() already ran on this instance.
     135         *
     136         * @var bool
     137         */
     138        private $booted = false;
    40139
    41140        /**
    … …  
    51150
    52151        /**
    53          * Activation defaults.
    54          */
    55         public static function activate(): void {
    56                 if ( false === get_option( Options::OPTION_KEY ) ) {
    57                         add_option( Options::OPTION_KEY, Options::defaults() );
    58                 }
    59                 Schema::install();
    60                 Indexer::instance()->ensure_cron();
    61         }
    62 
    63         /**
    64          * Wire hooks.
    65          */
    66         public function init(): void {
    67                 Schema::maybe_install();
    68                 Options::maybe_use_wordpress_vector_store();
    69                 ( new Admin_Notices() )->register();
    70                 ( new Privacy() )->register();
    71                 ( new Settings_Page() )->register();
    72                 ( new Assets() )->register();
    73                 Indexer::instance()->register();
    74                 ( new Site_Grounding() )->register();
    75                 Current_Page::instance()->register();
    76                 Retriever::instance()->register();
    77 
    78                 add_action( 'rest_api_init', array( $this, 'register_rest' ) );
    79         }
    80 
    81         /**
    82          * Register REST routes.
    83          */
    84         public function register_rest(): void {
    85                 ( new Chat_Controller() )->register_routes();
    86                 ( new Cart_Controller() )->register_routes();
    87                 ( new Kb_Controller() )->register_routes();
    88         }
    89 
    90         /**
    91          * Whether AI Client + OpenAI provider look available.
    92          *
    93          * Always reaches `chathearth_openai_ready` so callers (and tests) can
    94          * override detection even when WordPress AI support is missing.
     152         * Drop the shared instance and its services (tests).
     153         */
     154        public static function reset(): void {
     155                self::$instance = null;
     156        }
     157
     158        /**
     159         * A service, built on first use and then shared.
     160         *
     161         * @template T of object
     162         * @param class-string<T> $service_class Service class.
     163         * @return T
     164         * @throws \InvalidArgumentException For a class the container does not know.
     165         */
     166        public function get( string $service_class ) {
     167                if ( ! isset( $this->services[ $service_class ] ) ) {
     168                        $this->services[ $service_class ] = $this->build( $service_class );
     169                }
     170
     171                /** @var T $service */
     172                $service = $this->services[ $service_class ];
     173
     174                return $service;
     175        }
     176
     177        /**
     178         * Whether the AI Client and the OpenAI provider are ready (1.4.9 facade).
     179         *
     180         * Computed on every call and always passes through the `chathearth_openai_ready` filter.
    95181         */
    96182        public static function is_openai_ready(): bool {
    97                 $ready = false;
    98 
    99                 if ( function_exists( 'wp_supports_ai' ) && wp_supports_ai() && function_exists( 'wp_ai_client_prompt' ) ) {
    100                         if ( ! function_exists( 'is_plugin_active' ) ) {
    101                                 require_once ABSPATH . 'wp-admin/includes/plugin.php';
    102                         }
    103 
    104                         if ( is_plugin_active( 'ai-provider-for-openai/plugin.php' ) ) {
    105                                 if ( function_exists( 'wp_is_connector_registered' ) && ! wp_is_connector_registered( 'openai' ) ) {
    106                                         $ready = false;
    107                                 } else {
    108                                         $ready = self::is_provider_configured( 'openai' );
    109                                 }
    110                         }
    111                 }
    112 
    113                 /**
    114                  * Whether OpenAI is ready for ChatHearth (Connectors key present).
    115                  *
    116                  * The public chat launcher stays hidden until this is true.
    117                  *
    118                  * @since 1.4.7
    119                  *
    120                  * @param bool $ready Detected readiness.
    121                  */
    122                 return (bool) apply_filters( 'chathearth_openai_ready', $ready );
    123         }
    124 
    125         /**
    126          * Whether an AI provider is configured with working credentials.
    127          *
    128          * Uses the WordPress AI Client registry so the plugin never reads provider
    129          * API keys directly — those credentials were granted by the user to
    130          * WordPress, not to this plugin. Result is not cached so removing a key
    131          * (or adding one) is reflected immediately.
    132          *
    133          * @param string $provider Provider id (e.g. "openai").
    134          */
    135         private static function is_provider_configured( string $provider ): bool {
    136                 if ( ! class_exists( '\\WordPress\\AiClient\\AiClient' ) ) {
    137                         return false;
    138                 }
    139 
    140                 try {
    141                         $registry = \WordPress\AiClient\AiClient::defaultRegistry();
    142                         return $registry->hasProvider( $provider ) && $registry->isProviderConfigured( $provider );
    143                 } catch ( \Throwable $e ) {
    144                         return false;
    145                 }
     183                return self::instance()->get( Readiness_Checker::class )->is_ready();
     184        }
     185
     186        /**
     187         * Wire the hooks and keep the plugin's storage in place. Runs on `plugins_loaded`, priority 5.
     188         */
     189        public function boot(): void {
     190                if ( $this->booted ) {
     191                        return;
     192                }
     193                $this->booted = true;
     194
     195                // Order of contracts/lifecycle.md: storage check, then the upgrade runner.
     196                Activator::ensure();
     197                $this->get( Migration_Runner::class )->run();
     198                $this->get( Settings_Repository::class )->register();
     199                // Content changes happen in the admin, REST, cron and WP-CLI too (feature 009, R4).
     200                $this->get( Site_Context_Invalidator::class )->register();
     201                // The product name index (feature 013): changes are seen in the admin, REST, imports and WP-CLI too, and the
     202                // background job builds it. Without WooCommerce both do nothing.
     203                $this->get( Product_Name_Index_Invalidator::class )->register();
     204                add_action( Product_Name_Index::JOB_HOOK, array( $this->get( Product_Name_Index::class ), 'build' ) );
     205                // The knowledge base index (feature 010): the sync step, the hourly safety net and the settings trigger, and the
     206                // progress route. Content changes and steps happen in the admin, REST, cron and WP-CLI too.
     207                $this->get( Sync_Job::class )->register();
     208                $this->get( Change_Listener::class )->register();
     209                $this->get( Kb_Permission::class )->register();
     210                $this->get( Kb_Status_Controller::class )->register();
     211                $this->get( Kb_Controller::class )->register();
     212                $this->get( Request_Guard::class )->register();
     213                $this->get( Chat_Controller::class )->register();
     214                $this->get( Cart_Controller::class )->register();
     215                $this->get( Nonce_Controller::class )->register();
     216                $this->get( Recaptcha_Controller::class )->register();
     217                $this->get( Widget::class )->register();
     218                if ( is_admin() ) {
     219                        // The notices belong to the admin and show to administrators only; a front end request never prints one (feature 015, FR-017).
     220                        $this->get( Admin_Notices::class )->register();
     221                }
     222                if ( is_admin() && ! is_network_admin() ) {
     223                        $this->get( Settings_Page::class )->register();
     224                        $this->get( Abuse_Alert_Actions::class )->register();
     225                        $this->get( Rate_Limit_Reset_Action::class )->register();
     226                        $this->get( Reenable_Action::class )->register();
     227                        $this->get( Rearm_Pause::class )->register();
     228                        $this->get( Plugin_Links::class )->register();
     229                        $this->get( Privacy::class )->register();
     230                }
     231        }
     232
     233        /**
     234         * Builds a service.
     235         *
     236         * @param string $service_class Service class.
     237         * @throws \InvalidArgumentException For a class the container does not know.
     238         */
     239        private function build( string $service_class ): object {
     240                switch ( $service_class ) {
     241                        case Settings_Repository::class:
     242                                return new Settings_Repository( $this->get( Server_Overrides::class ), $this->get( Settings_Sanitizer::class ) );
     243                        case Migration_Runner::class:
     244                                return new Migration_Runner( $this->get( Settings_Repository::class ) );
     245                        case Readiness_Checker::class:
     246                                return new Readiness_Checker();
     247                        case Admin_Notices::class:
     248                                return new Admin_Notices( $this->get( Readiness_Checker::class ) );
     249                        case Plugin_Links::class:
     250                                return new Plugin_Links();
     251                        case Privacy::class:
     252                                return new Privacy();
     253                        case Reenable_Action::class:
     254                                return new Reenable_Action( $this->get( Settings_Repository::class ), $this->get( Reenable_Link::class ) );
     255                        case Rate_Limit_Reset_Action::class:
     256                                return new Rate_Limit_Reset_Action( $this->get( Counter_Generation::class ) );
     257                        case Counter_Generation::class:
     258                                return new Counter_Generation();
     259                        case Abuse_Alert_Actions::class:
     260                                return new Abuse_Alert_Actions( $this->get( Settings_Repository::class ) );
     261                        case Site_Status::class:
     262                                return new Site_Status( $this->get( Readiness_Checker::class ) );
     263                        case Settings_Page::class:
     264                                return new Settings_Page( $this->get( Settings_Repository::class ), $this->get( Readiness_Checker::class ), $this->get( Site_Status::class ), $this->get( Status_Report::class ) );
     265                        case Request_Guard::class:
     266                                return new Request_Guard();
     267                        case Chat_Controller::class:
     268                                return new Chat_Controller( $this->get( Settings_Repository::class ), $this->get( Chat_Pipeline::class ) );
     269                        case Cart_Service::class:
     270                                return new Cart_Service( $this->get( Product_Catalog::class ), $this->get( Product_Card::class ) );
     271                        case Cart_Controller::class:
     272                                return new Cart_Controller( $this->get( Settings_Repository::class ), $this->get( Chat_Controller::class ), $this->get( Access_Check::class ), $this->get( Client_Address::class ), $this->get( Counters::class ), $this->get( Cart_Service::class ) );
     273                        case Recaptcha_Controller::class:
     274                                return new Recaptcha_Controller( $this->get( Settings_Repository::class ), $this->get( Chat_Controller::class ), \Closure::fromCallable( array( $this, 'check_human' ) ), $this->get( Access_Check::class ) );
     275                        case Widget::class:
     276                                return new Widget( $this->get( Settings_Repository::class ), $this->get( Readiness_Checker::class ), $this->get( Widget_Config::class ), $this->get( Launcher_Icon::class ) );
     277                        case Widget_Config::class:
     278                                return new Widget_Config( $this->get( Settings_Repository::class ), $this->get( Current_Page::class ), $this->get( Store_Links::class ) );
     279                        case Current_Page::class:
     280                                return new Current_Page();
     281                        case Launcher_Icon::class:
     282                                return new Launcher_Icon();
     283                        case Nonce_Controller::class:
     284                                return new Nonce_Controller( $this->get( Settings_Repository::class ), $this->get( Nonce_Throttle::class ), $this->get( Client_Address::class ), $this->get( Access_Check::class ) );
     285                        case Nonce_Throttle::class:
     286                                return new Nonce_Throttle();
     287                        case Client_Address::class:
     288                                return new Client_Address( new Trusted_Proxy( $this->get( Settings_Repository::class )->all() ) );
     289                        case Quota_Policy::class:
     290                                return new Quota_Policy( $this->get( Client_Address::class ) );
     291                        case Option_Lock::class:
     292                                return new Option_Lock();
     293                        case Counters::class:
     294                                return new Counters( $this->get( Option_Lock::class ), null, $this->get( Counter_Generation::class ) );
     295                        case Escalation::class:
     296                                return new Escalation( $this->get( Settings_Repository::class ), $this->get( Counters::class ), $this->get( Rearm_Pause::class ), $this->get( Reenable_Link::class ), new Escalation_Mailer(), $this->get( Option_Lock::class ) );
     297                        case Rearm_Pause::class:
     298                                return new Rearm_Pause( $this->get( Settings_Repository::class ) );
     299                        case Reenable_Link::class:
     300                                return new Reenable_Link();
     301                        case Access_Check::class:
     302                                return new Access_Check( $this->get( Client_Address::class ) );
     303                        case Ban_Stage::class:
     304                                return new Ban_Stage( array( $this->get( Access_Check::class ), 'refusal' ) );
     305                        case Honeypot_Stage::class:
     306                                return new Honeypot_Stage(
     307                                        static function ( string $value, array $settings ): ?\WP_Error {
     308                                                if ( ! (bool) ( $settings['honeypot_enabled'] ?? true ) || '' === trim( $value ) ) {
     309                                                        return null;
     310                                                }
     311                                                // The answer of a failed generation, so a bot learns nothing from it. The value is never logged.
     312                                                Logger::warning( 'Bot trap filled.' );
     313                                                return Chat_Pipeline::generic_error();
     314                                        }
     315                                );
     316                        case Verification_Stage::class:
     317                                return new Verification_Stage( \Closure::fromCallable( array( $this, 'check_human' ) ) );
     318                        case Limits_Stage::class:
     319                                return new Limits_Stage(
     320                                        function ( array $settings ): ?\WP_Error {
     321                                                $limiter = new Rate_Limiter( $this->get( Counters::class ), $this->get( Client_Address::class ), $settings, array( $this->get( Escalation::class ), 'record_incident' ), $this->get( Quota_Policy::class ) );
     322                                                return $limiter->consume();
     323                                        }
     324                                );
     325                        case Verdict_Cache::class:
     326                                return new Verdict_Cache();
     327                        case Moderation_Stage::class:
     328                                return new Moderation_Stage(
     329                                        function ( string $message, array $history, array $settings ): ?\WP_Error {
     330                                                $moderation = new Content_Moderation(
     331                                                        $settings,
     332                                                        $this->get( Readiness_Checker::class ),
     333                                                        $this->get( Verdict_Cache::class ),
     334                                                        new Openai_Moderation_Client( (float) $settings['moderation_timeout'] )
     335                                                );
     336                                                return $moderation->check( $message, $history );
     337                                        }
     338                                );
     339                        case Chat_Pipeline::class:
     340                                return new Chat_Pipeline(
     341                                        array(
     342                                                $this->get( Ban_Stage::class ),
     343                                                $this->get( Honeypot_Stage::class ),
     344                                                new Input_Stage(),
     345                                                $this->get( Verification_Stage::class ),
     346                                                $this->get( Limits_Stage::class ),
     347                                                $this->get( Moderation_Stage::class ),
     348                                                new Page_Stage( $this->get( Page_Resolver::class ) ),
     349                                                new Retrieval_Stage( $this->get( Retriever::class ), $this->get( Readiness_Checker::class ) ),
     350                                                new Catalog_Stage( $this->get( Product_Catalog::class ), $this->get( Product_Name_Index::class ), $this->get( Comparison_Detector::class ) ),
     351                                                new Instructions_Stage( $this->get( Readiness_Checker::class ), $this->get( Site_Grounding::class ), $this->get( Current_Page_Section::class ), $this->get( Knowledge_Section::class ) ),
     352                                                new Generation_Stage( $this->get( Connectors_Generator::class ) ),
     353                                                new Reply_Stage( $this->get( Store_Links::class ), $this->get( Page_Link_Matcher::class ), $this->get( Product_Card::class ) ),
     354                                        )
     355                                );
     356                        case Connectors_Generator::class:
     357                                return new Connectors_Generator();
     358                        case Store_Links::class:
     359                                return new Store_Links();
     360                        case Markdown_Exporter::class:
     361                                return new Markdown_Exporter();
     362                        case Site_Context::class:
     363                                return new Site_Context( $this->get( Markdown_Exporter::class ) );
     364                        case Site_Context_Invalidator::class:
     365                                return new Site_Context_Invalidator( $this->get( Site_Context::class ) );
     366                        case Site_Grounding::class:
     367                                return new Site_Grounding( $this->get( Site_Context::class ) );
     368                        case Current_Page_Section::class:
     369                                return new Current_Page_Section();
     370                        case Page_Resolver::class:
     371                                return new Page_Resolver(
     372                                        $this->get( Markdown_Exporter::class ),
     373                                        static function (): string {
     374                                                return home_url( '/' );
     375                                        }
     376                                );
     377                        case Page_Link_Matcher::class:
     378                                return new Page_Link_Matcher();
     379                        case Product_Card::class:
     380                                return new Product_Card();
     381                        case Product_Catalog::class:
     382                                return new Product_Catalog( $this->get( Product_Card::class ) );
     383                        case Product_Name_Normaliser::class:
     384                                return new Product_Name_Normaliser();
     385                        case Product_Name_Index::class:
     386                                return new Product_Name_Index( $this->get( Product_Name_Normaliser::class ), $this->get( Job_Runner::class ), $this->get( Option_Lock::class ), $this->get( Product_Catalog::class ) );
     387                        case Product_Name_Index_Invalidator::class:
     388                                return new Product_Name_Index_Invalidator( $this->get( Product_Name_Index::class ), $this->get( Product_Catalog::class ) );
     389                        case Job_Runner::class:
     390                                return Job_Runner_Factory::make();
     391                        case Embedding_Client::class:
     392                                return new Openai_Embedding_Client();
     393                        case Source_Gate::class:
     394                                return new Source_Gate( $this->get( Markdown_Exporter::class ), $this->get( Sources::class ) );
     395                        case Comparison_Detector::class:
     396                                return new Comparison_Detector();
     397                        case Catalog_Block::class:
     398                                return new Catalog_Block();
     399                        case Knowledge_Section::class:
     400                                return new Knowledge_Section( $this->get( Catalog_Block::class ), $this->get( Product_Catalog::class ) );
     401                        case Retriever::class:
     402                                return new Retriever(
     403                                        $this->get( Embedding_Client::class ),
     404                                        $this->get( Passage_Repository::class ),
     405                                        $this->get( Entry_Repository::class ),
     406                                        $this->get( Source_Gate::class ),
     407                                        $this->get( Comparison_Detector::class )
     408                                );
     409                        case Sources::class:
     410                                return new Sources( $this->get( Settings_Repository::class ) );
     411                        case Sync_State::class:
     412                                return new Sync_State();
     413                        case Entry_Repository::class:
     414                                return new Entry_Repository();
     415                        case Passage_Repository::class:
     416                                return new Passage_Repository();
     417                        case Chunker::class:
     418                                return new Chunker();
     419                        case Markdown_Files::class:
     420                                return new Markdown_Files();
     421                        case Status_Report::class:
     422                                return new Status_Report( $this->get( Entry_Repository::class ), $this->get( Sync_State::class ), $this->get( Sources::class ), $this->get( Store_Check::class ) );
     423                        case Change_Listener::class:
     424                                return new Change_Listener( $this->get( Sync_Job::class ), $this->get( Sources::class ), $this->get( Markdown_Exporter::class ) );
     425                        case Kb_Permission::class:
     426                                return new Kb_Permission();
     427                        case Store_Check::class:
     428                                return new Store_Check();
     429                        case Entry_Presenter::class:
     430                                return new Entry_Presenter();
     431                        case Kb_Entry_Toggle::class:
     432                                return new Kb_Entry_Toggle( $this->get( Entry_Repository::class ), $this->get( Passage_Repository::class ), $this->get( Sync_Job::class ) );
     433                        case Kb_Controller::class:
     434                                return new Kb_Controller( $this->get( Kb_Permission::class ), $this->get( Status_Report::class ), $this->get( Sync_Job::class ), $this->get( Sources::class ), $this->get( Entry_Repository::class ), $this->get( Entry_Presenter::class ), $this->get( Kb_Entry_Toggle::class ), $this->get( Store_Check::class ) );
     435                        case Kb_Status_Controller::class:
     436                                return new Kb_Status_Controller( $this->get( Status_Report::class ), $this->get( Kb_Permission::class ) );
     437                        case Sync_Job::class:
     438                                return new Sync_Job(
     439                                        $this->get( Sources::class ),
     440                                        $this->get( Sync_State::class ),
     441                                        $this->get( Entry_Repository::class ),
     442                                        $this->get( Passage_Repository::class ),
     443                                        $this->get( Markdown_Exporter::class ),
     444                                        $this->get( Chunker::class ),
     445                                        $this->get( Embedding_Client::class ),
     446                                        $this->get( Job_Runner::class ),
     447                                        $this->get( Markdown_Files::class ),
     448                                        $this->get( Readiness_Checker::class )
     449                                );
     450                        case Server_Overrides::class:
     451                                return new Server_Overrides();
     452                        case Settings_Sanitizer::class:
     453                                return new Settings_Sanitizer();
     454                }
     455
     456                throw new \InvalidArgumentException( 'Unknown service: ' . $service_class ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer message, never output.
     457        }
     458
     459        /**
     460         * Verify against the settings snapshot already read by the calling REST route.
     461         *
     462         * @param string               $token    Visitor challenge token.
     463         * @param array<string, mixed> $settings Effective settings.
     464         */
     465        private function check_human( string $token, array $settings ): ?\WP_Error {
     466                $address = $this->get( Client_Address::class );
     467                $check   = new Human_Check(
     468                        new Recaptcha_V3( $settings ),
     469                        new Human_Pass( $address, (int) $settings['recaptcha_pass_ttl'] ),
     470                        new Nonce_Throttle( 'chathearth_rcv_' ),
     471                        $address
     472                );
     473                return $check->check( $token );
    146474        }
    147475}
  • chathearth/tags/2.0.0/includes/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/languages/chathearth.pot

    r3663506 r3833468  
    1 #, fuzzy
     1# Copyright (C) 2026 PalWP
     2# This file is distributed under the GPL-2.0-or-later.
    23msgid ""
    34msgstr ""
    4 "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
    5 "Project-Id-Version: ChatHearth - AI Chatbot\n"
    6 "POT-Creation-Date: 2026-07-16 18:01+0300\n"
    7 "PO-Revision-Date: 2026-07-16 18:01+0300\n"
    8 "Last-Translator: \n"
    9 "Language-Team: \n"
     5"Project-Id-Version: ChatHearth - AI Chatbot 2.0.0\n"
     6"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/chathearth\n"
     7"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
     8"Language-Team: LANGUAGE <LL@li.org>\n"
    109"MIME-Version: 1.0\n"
    1110"Content-Type: text/plain; charset=UTF-8\n"
    1211"Content-Transfer-Encoding: 8bit\n"
    13 "X-Generator: Poedit 2.2\n"
    14 "X-Poedit-Basepath: ..\n"
    15 "X-Poedit-Flags-xgettext: --add-comments=translators:\n"
    16 "X-Poedit-WPHeader: chathearth.php\n"
    17 "X-Poedit-SourceCharset: UTF-8\n"
    18 "X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;esc_attr__;"
    19 "esc_attr_e;esc_attr_x:1,2c;esc_html__;esc_html_e;esc_html_x:1,2c;_n_noop:1,2;"
    20 "_nx_noop:3c,1,2;__ngettext_noop:1,2\n"
    21 "X-Poedit-SearchPath-0: .\n"
    22 "X-Poedit-SearchPathExcluded-0: *.js\n"
    23 
    24 #: includes/Admin/class-admin-notices.php:56
    25 msgid ""
    26 "ChatHearth - AI Chatbot needs WordPress AI support, the “AI Provider for "
    27 "OpenAI” plugin, and an OpenAI API key under Connectors."
    28 msgstr ""
    29 
    30 #: includes/Admin/class-admin-notices.php:59
     12"POT-Creation-Date: 2026-11-25T16:14:44+01:00\n"
     13"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
     14"X-Generator: WP-CLI 2.12.0\n"
     15"X-Domain: chathearth\n"
     16
     17#. Plugin Name of the plugin
     18#: chathearth.php
     19#: includes/Admin/class-privacy.php:88
     20#: includes/Admin/Settings/class-settings-page.php:101
     21#: includes/Admin/Settings/class-settings-page.php:102
     22msgid "ChatHearth - AI Chatbot"
     23msgstr ""
     24
     25#. Description of the plugin
     26#: chathearth.php
     27msgid "Site-wide AI chatbot for WordPress, powered by the AI Provider for OpenAI plugin."
     28msgstr ""
     29
     30#. Author of the plugin
     31#: chathearth.php
     32msgid "PalWP"
     33msgstr ""
     34
     35#. Author URI of the plugin
     36#: chathearth.php
     37msgid "https://palwp.com/"
     38msgstr ""
     39
     40#. translators: 1: software name (WordPress or PHP), 2: required version, 3: installed version.
     41#: chathearth.php:60
     42#, php-format
     43msgid "%1$s %2$s or newer (this site runs %3$s)"
     44msgstr ""
     45
     46#. translators: %s: the unmet requirements, for example "PHP 7.4 or newer (this site runs 7.3.33)".
     47#: chathearth.php:71
     48#, php-format
     49msgid "ChatHearth - AI Chatbot needs %s. The plugin stays inactive until the site is updated."
     50msgstr ""
     51
     52#: includes/Admin/class-admin-notices.php:76
     53msgid "Rate-limit counters cleared."
     54msgstr ""
     55
     56#: includes/Admin/class-admin-notices.php:91
     57msgid "The chat is switched back on."
     58msgstr ""
     59
     60#: includes/Admin/class-admin-notices.php:95
     61msgid "The chat is already on."
     62msgstr ""
     63
     64#: includes/Admin/class-admin-notices.php:99
     65msgid "This link has expired or was already used. Switch the chat on in the Protection settings."
     66msgstr ""
     67
     68#: includes/Admin/class-admin-notices.php:116
     69msgid "ChatHearth - AI Chatbot could not finish updating its settings. Your site keeps working with your current settings, and the update will be tried again automatically."
     70msgstr ""
     71
     72#: includes/Admin/class-admin-notices.php:136
     73msgid "ChatHearth - AI Chatbot needs WordPress AI support, which is turned off or unavailable on this site. The chat icon stays hidden until it is available."
     74msgstr ""
     75
     76#: includes/Admin/class-admin-notices.php:139
     77msgid "ChatHearth - AI Chatbot needs the “AI Provider for OpenAI” plugin to be installed and active. The chat icon stays hidden until it is."
     78msgstr ""
     79
     80#: includes/Admin/class-admin-notices.php:140
     81msgid "Open Plugins"
     82msgstr ""
     83
     84#: includes/Admin/class-admin-notices.php:143
     85msgid "ChatHearth - AI Chatbot cannot find the OpenAI connector. The chat icon stays hidden until it is available."
     86msgstr ""
     87
     88#: includes/Admin/class-admin-notices.php:144
     89#: includes/Admin/class-admin-notices.php:148
    3190msgid "Open Connectors settings"
    3291msgstr ""
    3392
    34 #: includes/Admin/class-admin-notices.php:82
    35 msgid ""
    36 "ChatHearth - AI Chatbot: global rate limits were hit repeatedly (possible multi-"
    37 "IP abuse)."
    38 msgstr ""
    39 
    40 #. translators: %d: number of hits
    41 #: includes/Admin/class-admin-notices.php:90
     93#: includes/Admin/class-admin-notices.php:147
     94msgid "ChatHearth - AI Chatbot needs an OpenAI API key under Connectors. The chat icon stays hidden until one is added."
     95msgstr ""
     96
     97#: includes/Admin/class-admin-notices.php:186
     98msgid "Site-wide rate limits were hit repeatedly (possible abuse)."
     99msgstr ""
     100
     101#. translators: %s: number of recorded rate-limit hits.
     102#: includes/Admin/class-admin-notices.php:188
    42103#, php-format
    43 msgid "Recorded hits in the window: %d."
    44 msgstr ""
    45 
    46 #: includes/Admin/class-admin-notices.php:97
    47 msgid "The chatbot was automatically disabled."
    48 msgstr ""
    49 
    50 #: includes/Admin/class-admin-notices.php:99
    51 msgid "Open Protection settings"
    52 msgstr ""
    53 
    54 #: includes/Admin/class-admin-notices.php:100
     104msgid "Recorded hit: %s."
     105msgid_plural "Recorded hits: %s."
     106msgstr[0] ""
     107msgstr[1] ""
     108
     109#: includes/Admin/class-admin-notices.php:190
     110msgid "The chat was switched off automatically."
     111msgstr ""
     112
     113#: includes/Admin/class-admin-notices.php:195
     114msgid "Switch chat back on"
     115msgstr ""
     116
     117#: includes/Admin/class-admin-notices.php:197
     118msgid "Review protection settings"
     119msgstr ""
     120
     121#: includes/Admin/class-admin-notices.php:198
     122#: assets/js/admin/toasts.js:33
    55123msgid "Dismiss"
    56124msgstr ""
    57125
    58 #: includes/Admin/class-admin-notices.php:109
     126#: includes/Admin/class-plugin-links.php:41
     127msgid "Settings"
     128msgstr ""
     129
     130#: includes/Admin/class-privacy.php:37
     131msgid "Always, when a visitor sends a message: the message and the recent conversation history of that chat are sent to OpenAI, through the AI provider set up in WordPress (Connectors), so a reply can be generated."
     132msgstr ""
     133
     134#: includes/Admin/class-privacy.php:38
     135msgid "Always, when a visitor sends a message: a short summary of this site’s public pages (and, with WooCommerce, the store and its product categories) and the public content of the page the visitor is on are sent to the AI provider together with the instructions, so the answer is about this site. Drafts, private and password-protected content are never sent, and the page is read as a guest sees it."
     136msgstr ""
     137
     138#: includes/Admin/class-privacy.php:39
     139msgid "Always: the conversation history of the chat is kept in the visitor’s browser (local storage) and removed after 24 hours without a new message, or sooner when the visitor clears the chat. The plugin does not store chat transcripts in the WordPress database."
     140msgstr ""
     141
     142#: includes/Admin/class-privacy.php:40
     143msgid "Always: the visitor’s IP address is used for a short time for rate limits, for blocking the addresses you list and for abuse protection. IPv6 visitors are counted per network block. Visitors behind a proxy share a limit until trusted proxies are set up. The counters are short-lived and are not a chat log."
     144msgstr ""
     145
     146#: includes/Admin/class-privacy.php:41
     147msgid "When you list blocked addresses: the addresses and ranges you enter are stored in the plugin’s settings and compared with each visitor’s address. Visitors’ addresses are not stored."
     148msgstr ""
     149
     150#: includes/Admin/class-privacy.php:42
     151msgid "When “Separate limits for logged-in users” is on: the visitor’s WordPress user account is used to count their messages, so the limits follow the person and not their network."
     152msgstr ""
     153
     154#: includes/Admin/class-privacy.php:43
     155msgid "When the bot trap is on: an invisible form field is added to the chat. Only automated programs fill it in, and the result is used to refuse their requests. Visitors never see it."
     156msgstr ""
     157
     158#: includes/Admin/class-privacy.php:44
     159msgid "When content moderation uses OpenAI: the new message and up to two earlier visitor messages of the same chat (never the assistant’s replies) are also sent to OpenAI’s moderation service before a reply is generated, so harmful or disallowed content can be blocked. Only texts not checked in the last 24 hours are sent. The result is remembered for 24 hours as a salted hash, never as text."
     160msgstr ""
     161
     162#: includes/Admin/class-privacy.php:45
     163msgid "When both Google reCAPTCHA v3 keys are set: Google is contacted only after the visitor presses Continue. Google processes a score-based check and related technical data such as the IP address, under Google’s privacy policy. The HTTP-only chathearth_human cookie lasts at most 60 minutes and is used only to skip repeated checks."
     164msgstr ""
     165
     166#: includes/Admin/class-privacy.php:46
     167msgid "When the Knowledge Base is on and OpenAI is connected: the public content selected in the Knowledge Base settings is sent to the OpenAI embeddings service when it is indexed and when it changes, and each visitor question is sent to the OpenAI embeddings service to find matching passages. ChatHearth does not store the question for this. The index holds only this public site content and its numeric representations (embeddings), stored in the WordPress database of this site, with no visitor or account data, so there is nothing in it to export or erase for a person. Markdown copies of the selected content can be kept in the uploads folder of this site."
     168msgstr ""
     169
     170#: includes/Admin/class-privacy.php:47
     171msgid "Always: ChatHearth does not track visitors. It sets no tracking cookies and sends no analytics."
     172msgstr ""
     173
     174#: includes/Admin/class-privacy.php:48
     175msgid "Always: ChatHearth does not store the AI provider key. That credential is managed by WordPress Connectors or the server environment."
     176msgstr ""
     177
     178#: includes/Admin/class-privacy.php:49
     179msgid "Always: the summary of this site’s public pages that goes with a message is kept on this site for up to 12 hours, so the next messages do not rebuild it."
     180msgstr ""
     181
     182#: includes/Admin/class-privacy.php:50
     183msgid "Always: the rate-limit counters of a visitor’s network or account are kept only for the length of the limit window and are not a chat log."
     184msgstr ""
     185
     186#: includes/Admin/class-privacy.php:51
     187msgid "When the Knowledge Base is on: the index stays in the WordPress database of this site until you delete an item, turn the Knowledge Base off or delete the plugin, and the markdown copies in the uploads folder are removed when you turn the setting off or delete the plugin."
     188msgstr ""
     189
     190#: includes/Admin/class-privacy.php:52
     191msgid "When site-wide rate limits are hit repeatedly: the plugin keeps an abuse alert in this site’s options, with the number of hits and whether the chat was switched off, and shows it to administrators until you dismiss it. It holds no visitor data."
     192msgstr ""
     193
     194#: includes/Admin/class-privacy.php:53
     195msgid "When WP_DEBUG_LOG is already on in your site’s configuration: the plugin writes short failure codes to the PHP error log, and never message text, addresses or keys."
     196msgstr ""
     197
     198#: includes/Admin/class-privacy.php:54
     199msgid "Always: the plugin sets no tracking or analytics cookie, sends no analytics or telemetry request and keeps no visitor identifier beyond the stores described here."
     200msgstr ""
     201
     202#: includes/Admin/class-privacy.php:65
     203msgid "When WooCommerce is active and the assistant shows product cards: the Add to cart button of a product card in the chat uses the WooCommerce cart on this site. Payment still happens at the store checkout."
     204msgstr ""
     205
     206#: includes/Admin/class-privacy.php:66
     207msgid "The facts of the products named in a message or found in the knowledge base (name, price, stock, categories, attributes and short description) are sent to the AI provider with the question."
     208msgstr ""
     209
     210#: includes/Admin/class-privacy.php:82
     211msgid "ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this site. Depending on how the chatbot is set up, the following may apply:"
     212msgstr ""
     213
     214#: includes/Admin/class-privacy.php:86
     215msgid "Site owners should read the privacy policy of their AI provider (and of Google, if reCAPTCHA is used) and make sure this section matches how the chatbot is set up on their site."
     216msgstr ""
     217
     218#: includes/Admin/class-reenable-action.php:54
     219#: includes/Admin/Settings/class-abuse-alert-actions.php:78
     220#: includes/Admin/Settings/class-rate-limit-reset-action.php:48
    59221msgid "Sorry, you are not allowed to do that."
    60222msgstr ""
    61223
    62 #: includes/Admin/class-privacy.php:37
    63 msgid ""
    64 "ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this "
    65 "site. When someone uses the chatbot, the following may apply:"
    66 msgstr ""
    67 
    68 #: includes/Admin/class-privacy.php:43
    69 msgid ""
    70 "Message text and recent conversation history from the chat session are sent "
    71 "to a third-party AI provider (OpenAI in the current version) through "
    72 "WordPress Connectors / the site’s configured AI provider, so a reply can be "
    73 "generated."
    74 msgstr ""
    75 
    76 #: includes/Admin/class-privacy.php:47
    77 msgid ""
    78 "Conversation history for the widget is stored in the visitor’s browser "
    79 "(local storage). The plugin does not store chat transcripts in the WordPress "
    80 "database in the current version."
    81 msgstr ""
    82 
    83 #: includes/Admin/class-privacy.php:51
    84 msgid ""
    85 "The visitor’s IP address may be used temporarily for rate limiting and abuse "
    86 "protection. Related counters are short-lived and are not kept as a chat log."
    87 msgstr ""
    88 
    89 #: includes/Admin/class-privacy.php:55
    90 msgid ""
    91 "If Google reCAPTCHA is enabled in the chatbot settings, Google may process a "
    92 "CAPTCHA challenge (and related technical data such as IP address) according "
    93 "to Google’s privacy policy."
    94 msgstr ""
    95 
    96 #: includes/Admin/class-privacy.php:59
    97 msgid ""
    98 "This plugin does not store the AI provider API key; that credential is "
    99 "managed through WordPress Connectors or the server environment."
    100 msgstr ""
    101 
    102 #: includes/Admin/class-privacy.php:65
    103 msgid ""
    104 "Site owners should review the privacy policy of their chosen AI provider "
    105 "(and Google, if reCAPTCHA is used) and ensure this section matches how the "
    106 "chatbot is configured on their site."
    107 msgstr ""
    108 
    109 #. Plugin Name of the plugin/theme
    110 #: includes/Admin/class-privacy.php:70
    111 #: includes/Admin/class-settings-page.php:68
    112 #: includes/Admin/class-settings-page.php:69
    113 msgid "ChatHearth - AI Chatbot"
    114 msgstr ""
    115 
    116 #: includes/Admin/class-settings-page.php:127
     224#: includes/Admin/Settings/class-field-choices.php:35
     225msgid "Icon only"
     226msgstr ""
     227
     228#: includes/Admin/Settings/class-field-choices.php:36
     229msgid "Icon and text"
     230msgstr ""
     231
     232#: includes/Admin/Settings/class-field-choices.php:40
     233msgid "Circle"
     234msgstr ""
     235
     236#: includes/Admin/Settings/class-field-choices.php:41
     237msgid "Square"
     238msgstr ""
     239
     240#: includes/Admin/Settings/class-field-choices.php:45
     241msgid "Bottom left"
     242msgstr ""
     243
     244#: includes/Admin/Settings/class-field-choices.php:46
     245msgid "Bottom center"
     246msgstr ""
     247
     248#: includes/Admin/Settings/class-field-choices.php:47
     249msgid "Bottom right"
     250msgstr ""
     251
     252#: includes/Admin/Settings/class-field-choices.php:51
     253msgid "Small"
     254msgstr ""
     255
     256#: includes/Admin/Settings/class-field-choices.php:52
     257msgid "Medium"
     258msgstr ""
     259
     260#: includes/Admin/Settings/class-field-choices.php:53
     261msgid "Large"
     262msgstr ""
     263
     264#: includes/Admin/Settings/class-field-choices.php:57
     265msgid "3 seconds: shortest delay"
     266msgstr ""
     267
     268#: includes/Admin/Settings/class-field-choices.php:58
     269msgid "5 seconds: balanced"
     270msgstr ""
     271
     272#: includes/Admin/Settings/class-field-choices.php:59
     273msgid "10 seconds: almost always gets an answer"
     274msgstr ""
     275
     276#: includes/Admin/Settings/class-field-choices.php:60
     277msgid "15 seconds: longest delay"
     278msgstr ""
     279
     280#: includes/Admin/Settings/class-field-choices.php:63
     281msgid "OpenAI"
     282msgstr ""
     283
     284#: includes/Admin/Settings/class-field-renderer.php:297
     285msgid "On"
     286msgstr ""
     287
     288#: includes/Admin/Settings/class-field-renderer.php:297
     289msgid "Off"
     290msgstr ""
     291
     292#. translators: %s: setting name.
     293#: includes/Admin/Settings/class-field-renderer.php:324
     294#, php-format
     295msgid "%s (slider)"
     296msgstr ""
     297
     298#. translators: %s: setting name.
     299#: includes/Admin/Settings/class-field-renderer.php:387
     300#, php-format
     301msgid "%s (colour picker)"
     302msgstr ""
     303
     304#: includes/Admin/Settings/class-field-renderer.php:423
     305msgid "Set by server environment"
     306msgstr ""
     307
     308#: includes/Admin/Settings/class-field-renderer.php:492
     309msgid "(not available)"
     310msgstr ""
     311
     312#: includes/Admin/Settings/class-field-renderer.php:535
     313msgid "A secret key is saved."
     314msgstr ""
     315
     316#: includes/Admin/Settings/class-field-renderer.php:536
     317msgid "Replace"
     318msgstr ""
     319
     320#: includes/Admin/Settings/class-field-renderer.php:543
     321msgid "Remove the saved secret key"
     322msgstr ""
     323
     324#: includes/Admin/Settings/class-settings-page.php:307
     325msgid "Sorry, you are not allowed to access this page."
     326msgstr ""
     327
     328#: includes/Admin/Settings/class-settings-page.php:355
     329msgid "Not ready"
     330msgstr ""
     331
     332#: includes/Admin/Settings/class-settings-page.php:360
     333msgid "Chat is off – switched off automatically"
     334msgstr ""
     335
     336#: includes/Admin/Settings/class-settings-page.php:363
     337msgid "Chat is off"
     338msgstr ""
     339
     340#: includes/Admin/Settings/class-settings-page.php:366
     341msgid "Chat is live"
     342msgstr ""
     343
     344#: includes/Admin/Settings/class-settings-page.php:379
     345msgid "AI Chatbot"
     346msgstr ""
     347
     348#: includes/Admin/Settings/class-settings-page.php:380
     349msgid "Make every conversation feel at home."
     350msgstr ""
     351
     352#: includes/Admin/Settings/class-settings-page.php:381
     353msgid "Plugin version"
     354msgstr ""
     355
     356#: includes/Admin/Settings/class-settings-page.php:383
     357msgid "Help and documentation"
     358msgstr ""
     359
     360#: includes/Admin/Settings/class-settings-page.php:384
     361msgid "(opens in a new tab)"
     362msgstr ""
     363
     364#: includes/Admin/Settings/class-settings-page.php:396
     365msgid "ChatHearth settings"
     366msgstr ""
     367
     368#: includes/Admin/Settings/class-settings-page.php:396
     369msgid "Settings sections"
     370msgstr ""
     371
     372#: includes/Admin/Settings/class-settings-page.php:409
     373#: includes/Admin/Settings/class-settings-page.php:458
     374#: includes/Admin/Settings/class-settings-page.php:532
     375msgid "Unsaved changes"
     376msgstr ""
     377
     378#: includes/Admin/Settings/class-settings-page.php:453
     379msgid "Protection sections"
     380msgstr ""
     381
     382#: includes/Admin/Settings/class-settings-page.php:521
     383msgid "Clear all rate-limit counters now? Visitors and users get their full allowance again."
     384msgstr ""
     385
     386#: includes/Admin/Settings/class-settings-page.php:533
     387msgid "Your settings are up to date."
     388msgstr ""
     389
     390#: includes/Admin/Settings/class-settings-page.php:534
     391msgid "Discard changes"
     392msgstr ""
     393
     394#: includes/Admin/Settings/class-settings-page.php:535
     395msgid "Save settings"
     396msgstr ""
     397
     398#: includes/Admin/Settings/class-site-status.php:119
     399msgid "Could not be checked"
     400msgstr ""
     401
     402#: includes/Admin/Settings/class-site-status.php:133
     403msgid "WordPress version"
     404msgstr ""
     405
     406#: includes/Admin/Settings/class-site-status.php:134
     407msgid "PHP version"
     408msgstr ""
     409
     410#: includes/Admin/Settings/class-site-status.php:135
     411msgid "WordPress AI support"
     412msgstr ""
     413
     414#: includes/Admin/Settings/class-site-status.php:136
     415msgid "AI Provider for OpenAI plugin"
     416msgstr ""
     417
     418#: includes/Admin/Settings/class-site-status.php:137
     419msgid "OpenAI key in Connectors"
     420msgstr ""
     421
     422#: includes/Admin/Settings/class-site-status.php:138
     423msgid "Persistent object cache"
     424msgstr ""
     425
     426#: includes/Admin/Settings/class-site-status.php:139
     427msgid "WooCommerce"
     428msgstr ""
     429
     430#: includes/Admin/Settings/class-site-status.php:140
     431msgid "Background tasks (WP-Cron)"
     432msgstr ""
     433
     434#: includes/Admin/Settings/class-site-status.php:173
     435msgid "Available"
     436msgstr ""
     437
     438#: includes/Admin/Settings/class-site-status.php:173
     439msgid "Not available"
     440msgstr ""
     441
     442#: includes/Admin/Settings/class-site-status.php:182
     443#: includes/Admin/Settings/class-tab-protection.php:285
     444msgid "Active"
     445msgstr ""
     446
     447#: includes/Admin/Settings/class-site-status.php:182
     448#: includes/Admin/Settings/class-site-status.php:216
     449msgid "Not active"
     450msgstr ""
     451
     452#: includes/Admin/Settings/class-site-status.php:192
     453msgid "Configured"
     454msgstr ""
     455
     456#: includes/Admin/Settings/class-site-status.php:192
     457#: includes/Admin/Settings/class-tab-ai-settings.php:98
     458msgid "Not configured"
     459msgstr ""
     460
     461#: includes/Admin/Settings/class-site-status.php:204
     462msgid "Detected"
     463msgstr ""
     464
     465#: includes/Admin/Settings/class-site-status.php:204
     466msgid "Not detected. Rate limits still work. An object cache makes them faster."
     467msgstr ""
     468
     469#. translators: %s: WooCommerce version.
     470#: includes/Admin/Settings/class-site-status.php:218
     471#, php-format
     472msgid "Active %s"
     473msgstr ""
     474
     475#: includes/Admin/Settings/class-site-status.php:229
     476msgid "Disabled (server task)"
     477msgstr ""
     478
     479#: includes/Admin/Settings/class-site-status.php:234
     480msgid "Not scheduled"
     481msgstr ""
     482
     483#: includes/Admin/Settings/class-site-status.php:237
     484msgid "Late"
     485msgstr ""
     486
     487#: includes/Admin/Settings/class-site-status.php:240
     488msgid "Running"
     489msgstr ""
     490
     491#: includes/Admin/Settings/class-site-status.php:250
     492msgid "OK"
     493msgstr ""
     494
     495#: includes/Admin/Settings/class-site-status.php:251
     496msgid "Warning"
     497msgstr ""
     498
     499#: includes/Admin/Settings/class-site-status.php:252
     500msgid "Error"
     501msgstr ""
     502
     503#: includes/Admin/Settings/class-site-status.php:253
     504msgid "Info"
     505msgstr ""
     506
     507#: includes/Admin/Settings/class-site-status.php:265
     508msgid "ChatHearth status report"
     509msgstr ""
     510
     511#. translators: %s: date and time.
     512#: includes/Admin/Settings/class-site-status.php:267
     513#, php-format
     514msgid "Generated: %s"
     515msgstr ""
     516
     517#. translators: %s: site address.
     518#: includes/Admin/Settings/class-site-status.php:269
     519#, php-format
     520msgid "Site: %s"
     521msgstr ""
     522
     523#. translators: %s: plugin version.
     524#: includes/Admin/Settings/class-site-status.php:271
     525#, php-format
     526msgid "ChatHearth: %s"
     527msgstr ""
     528
     529#. translators: 1: theme name, 2: theme version.
     530#: includes/Admin/Settings/class-site-status.php:273
     531#, php-format
     532msgid "Theme: %1$s %2$s"
     533msgstr ""
     534
     535#: includes/Admin/Settings/class-tab-advanced.php:44
     536msgid "Advanced"
     537msgstr ""
     538
     539#: includes/Admin/Settings/class-tab-advanced.php:58
     540msgid "Copy status report"
     541msgstr ""
     542
     543#: includes/Admin/Settings/class-tab-advanced.php:78
     544msgid "How to fix"
     545msgstr ""
     546
     547#: includes/Admin/Settings/class-tab-advanced.php:88
     548msgid "Status report"
     549msgstr ""
     550
     551#: includes/Admin/Settings/class-tab-advanced.php:101
     552msgid "System status"
     553msgstr ""
     554
     555#: includes/Admin/Settings/class-tab-advanced.php:102
     556msgid "A quick check of your site's readiness."
     557msgstr ""
     558
     559#: includes/Admin/Settings/class-tab-advanced.php:111
     560msgid "Data"
     561msgstr ""
     562
     563#: includes/Admin/Settings/class-tab-advanced.php:112
     564msgid "Choose what happens when the plugin is deleted."
     565msgstr ""
     566
     567#: includes/Admin/Settings/class-tab-advanced.php:114
     568msgid "Keep data when the plugin is deleted"
     569msgstr ""
     570
     571#: includes/Admin/Settings/class-tab-advanced.php:114
     572msgid "When off, deleting ChatHearth removes all its settings, knowledge base and files."
     573msgstr ""
     574
     575#: includes/Admin/Settings/class-tab-ai-settings.php:44
     576msgid "AI Settings"
     577msgstr ""
     578
     579#: includes/Admin/Settings/class-tab-ai-settings.php:63
     580msgid "Connection"
     581msgstr ""
     582
     583#: includes/Admin/Settings/class-tab-ai-settings.php:64
     584msgid "Your API key is stored by WordPress, not by ChatHearth."
     585msgstr ""
     586
     587#: includes/Admin/Settings/class-tab-ai-settings.php:70
     588#: includes/Admin/Settings/class-tab-ai-settings.php:74
     589msgid "Model"
     590msgstr ""
     591
     592#: includes/Admin/Settings/class-tab-ai-settings.php:71
     593msgid "Choose the AI that generates replies."
     594msgstr ""
     595
     596#: includes/Admin/Settings/class-tab-ai-settings.php:73
     597msgid "Provider"
     598msgstr ""
     599
     600#: includes/Admin/Settings/class-tab-ai-settings.php:73
     601msgid "More providers will be added in future versions."
     602msgstr ""
     603
     604#: includes/Admin/Settings/class-tab-ai-settings.php:74
     605msgid "Smaller models are faster and cheaper."
     606msgstr ""
     607
     608#: includes/Admin/Settings/class-tab-ai-settings.php:79
     609msgid "Instructions"
     610msgstr ""
     611
     612#: includes/Admin/Settings/class-tab-ai-settings.php:80
     613msgid "Guide how the assistant behaves and speaks."
     614msgstr ""
     615
     616#: includes/Admin/Settings/class-tab-ai-settings.php:82
     617msgid "Additional instructions"
     618msgstr ""
     619
     620#: includes/Admin/Settings/class-tab-ai-settings.php:82
     621msgid "Tone, focus and anything the assistant should know. ChatHearth always keeps the assistant limited to your website."
     622msgstr ""
     623
     624#: includes/Admin/Settings/class-tab-ai-settings.php:95
     625msgid "OpenAI via WordPress Connectors"
     626msgstr ""
     627
     628#: includes/Admin/Settings/class-tab-ai-settings.php:96
     629msgid "Your OpenAI API key is stored securely in WordPress core. ChatHearth never sees or stores it."
     630msgstr ""
     631
     632#: includes/Admin/Settings/class-tab-ai-settings.php:98
     633msgid "Ready"
     634msgstr ""
     635
     636#: includes/Admin/Settings/class-tab-ai-settings.php:99
     637#: includes/Admin/Settings/class-tab-protection.php:314
     638msgid "Open Connectors"
     639msgstr ""
     640
     641#: includes/Admin/Settings/class-tab-ai-settings.php:107
     642msgid "Answer only questions about this website: its pages, posts, products, categories, policies, store, shipping and related services."
     643msgstr ""
     644
     645#: includes/Admin/Settings/class-tab-ai-settings.php:108
     646msgid "When the visitor asks about \"this page\", \"this product\" or \"here\", use the page they are viewing."
     647msgstr ""
     648
     649#: includes/Admin/Settings/class-tab-ai-settings.php:109
     650msgid "Politely refuse unrelated topics (news, homework, other companies, general trivia) and offer help with this website instead."
     651msgstr ""
     652
     653#: includes/Admin/Settings/class-tab-ai-settings.php:110
     654msgid "Never invent pages, URLs, prices, stock or products. If the information is not available, say so."
     655msgstr ""
     656
     657#: includes/Admin/Settings/class-tab-ai-settings.php:111
     658msgid "Link to every page, post, product or category you mention."
     659msgstr ""
     660
     661#: includes/Admin/Settings/class-tab-ai-settings.php:112
     662msgid "Compare products in a table or side-by-side list, using only known facts."
     663msgstr ""
     664
     665#: includes/Admin/Settings/class-tab-ai-settings.php:113
     666msgid "Point buyers to Add to cart, the cart or checkout. Never claim an order was placed."
     667msgstr ""
     668
     669#: includes/Admin/Settings/class-tab-ai-settings.php:116
     670msgid "Show the built-in website rules"
     671msgstr ""
     672
     673#: includes/Admin/Settings/class-tab-appearance.php:46
     674msgid "Appearance"
     675msgstr ""
     676
     677#: includes/Admin/Settings/class-tab-appearance.php:67
     678msgid "Reset appearance to defaults"
     679msgstr ""
     680
     681#: includes/Admin/Settings/class-tab-appearance.php:104
     682#: includes/Admin/Settings/class-tab-appearance.php:106
     683msgid "Live preview"
     684msgstr ""
     685
     686#: includes/Admin/Settings/class-tab-appearance.php:106
     687msgid "Example conversation"
     688msgstr ""
     689
     690#: includes/Admin/Settings/class-tab-appearance.php:114
     691msgid "What do you offer?"
     692msgstr ""
     693
     694#: includes/Admin/Settings/class-tab-appearance.php:115
     695msgid "Here are a few products you might like."
     696msgstr ""
     697
     698#: includes/Admin/Settings/class-tab-appearance.php:119
     699msgid "Type a message…"
     700msgstr ""
     701
     702#: includes/Admin/Settings/class-tab-appearance.php:122
     703msgid "Launcher preview"
     704msgstr ""
     705
     706#: includes/Admin/Settings/class-tab-appearance.php:134
     707msgid "Shirt"
     708msgstr ""
     709
     710#: includes/Admin/Settings/class-tab-appearance.php:135
     711msgid "Shoes"
     712msgstr ""
     713
     714#: includes/Admin/Settings/class-tab-appearance.php:138
     715msgid "Sample products. Scroll sideways to see more."
     716msgstr ""
     717
     718#: includes/Admin/Settings/class-tab-appearance.php:142
     719#: includes/Frontend/class-widget-config.php:270
     720msgid "Add to cart"
     721msgstr ""
     722
     723#: includes/Admin/Settings/class-tab-appearance.php:155
     724msgid "Choose a colour or enter a hex value."
     725msgstr ""
     726
     727#: includes/Admin/Settings/class-tab-appearance.php:156
     728msgid "px"
     729msgstr ""
     730
     731#: includes/Admin/Settings/class-tab-appearance.php:161
     732msgid "Launcher button"
     733msgstr ""
     734
     735#: includes/Admin/Settings/class-tab-appearance.php:162
     736msgid "How visitors open the chat on your site."
     737msgstr ""
     738
     739#: includes/Admin/Settings/class-tab-appearance.php:164
     740msgid "Launcher style"
     741msgstr ""
     742
     743#: includes/Admin/Settings/class-tab-appearance.php:164
     744msgid "Choose a compact icon button or an animated pill with text."
     745msgstr ""
     746
     747#: includes/Admin/Settings/class-tab-appearance.php:165
     748msgid "Button label"
     749msgstr ""
     750
     751#: includes/Admin/Settings/class-tab-appearance.php:165
     752msgid "Text shown next to the sparkle icon on wide screens (up to 50 characters)."
     753msgstr ""
     754
     755#: includes/Admin/Settings/class-tab-appearance.php:166
     756msgid "Shape"
     757msgstr ""
     758
     759#: includes/Admin/Settings/class-tab-appearance.php:166
     760msgid "Shape of the icon-only launcher."
     761msgstr ""
     762
     763#: includes/Admin/Settings/class-tab-appearance.php:167
     764msgid "Size"
     765msgstr ""
     766
     767#: includes/Admin/Settings/class-tab-appearance.php:167
     768msgid "Size of the launcher icon."
     769msgstr ""
     770
     771#: includes/Admin/Settings/class-tab-appearance.php:168
     772msgid "Position"
     773msgstr ""
     774
     775#: includes/Admin/Settings/class-tab-appearance.php:168
     776msgid "Where the launcher sits on your pages."
     777msgstr ""
     778
     779#: includes/Admin/Settings/class-tab-appearance.php:169
     780msgid "Background"
     781msgstr ""
     782
     783#: includes/Admin/Settings/class-tab-appearance.php:170
     784msgid "Border"
     785msgstr ""
     786
     787#: includes/Admin/Settings/class-tab-appearance.php:171
     788msgid "Icon"
     789msgstr ""
     790
     791#: includes/Admin/Settings/class-tab-appearance.php:176
     792msgid "Chat window"
     793msgstr ""
     794
     795#: includes/Admin/Settings/class-tab-appearance.php:177
     796msgid "Make the conversation feel at home on your site."
     797msgstr ""
     798
     799#: includes/Admin/Settings/class-tab-appearance.php:179
     800msgid "Window size"
     801msgstr ""
     802
     803#: includes/Admin/Settings/class-tab-appearance.php:179
     804msgid "How large the chat window opens."
     805msgstr ""
     806
     807#: includes/Admin/Settings/class-tab-appearance.php:180
     808msgid "Window title"
     809msgstr ""
     810
     811#: includes/Admin/Settings/class-tab-appearance.php:180
     812msgid "Shown at the top of the chat window."
     813msgstr ""
     814
     815#: includes/Admin/Settings/class-tab-appearance.php:181
     816msgid "Visitor messages"
     817msgstr ""
     818
     819#: includes/Admin/Settings/class-tab-appearance.php:181
     820msgid "Background colour of the visitor's messages."
     821msgstr ""
     822
     823#: includes/Admin/Settings/class-tab-appearance.php:182
     824msgid "Assistant messages"
     825msgstr ""
     826
     827#: includes/Admin/Settings/class-tab-appearance.php:182
     828msgid "Background colour of the assistant's replies."
     829msgstr ""
     830
     831#: includes/Admin/Settings/class-tab-appearance.php:187
     832msgid "Product cards"
     833msgstr ""
     834
     835#: includes/Admin/Settings/class-tab-appearance.php:188
     836msgid "Style how products appear when the assistant suggests them from your store."
     837msgstr ""
     838
     839#: includes/Admin/Settings/class-tab-appearance.php:190
     840msgid "Card background"
     841msgstr ""
     842
     843#: includes/Admin/Settings/class-tab-appearance.php:190
     844msgid "Background of each product card."
     845msgstr ""
     846
     847#: includes/Admin/Settings/class-tab-appearance.php:191
     848msgid "Card border"
     849msgstr ""
     850
     851#: includes/Admin/Settings/class-tab-appearance.php:191
     852msgid "Outline around each product card."
     853msgstr ""
     854
     855#: includes/Admin/Settings/class-tab-appearance.php:192
     856msgid "Card text"
     857msgstr ""
     858
     859#: includes/Admin/Settings/class-tab-appearance.php:192
     860msgid "Colour of product names and prices."
     861msgstr ""
     862
     863#: includes/Admin/Settings/class-tab-appearance.php:193
     864msgid "Add to cart button"
     865msgstr ""
     866
     867#: includes/Admin/Settings/class-tab-appearance.php:193
     868msgid "Background of the Add to cart button."
     869msgstr ""
     870
     871#: includes/Admin/Settings/class-tab-appearance.php:194
     872msgid "Add to cart button text"
     873msgstr ""
     874
     875#: includes/Admin/Settings/class-tab-appearance.php:194
     876msgid "Text colour of the Add to cart button."
     877msgstr ""
     878
     879#: includes/Admin/Settings/class-tab-appearance.php:195
     880msgid "Add to cart button corners"
     881msgstr ""
     882
     883#: includes/Admin/Settings/class-tab-appearance.php:195
     884msgid "Round the corners of the Add to cart button."
     885msgstr ""
     886
     887#: includes/Admin/Settings/class-tab-appearance.php:196
     888msgid "Card corners"
     889msgstr ""
     890
     891#: includes/Admin/Settings/class-tab-appearance.php:196
     892msgid "Round the corners of each product card."
     893msgstr ""
     894
     895#: includes/Admin/Settings/class-tab-appearance.php:197
     896msgid "Card width"
     897msgstr ""
     898
     899#: includes/Admin/Settings/class-tab-appearance.php:197
     900msgid "Width of each card in the horizontal product list."
     901msgstr ""
     902
     903#: includes/Admin/Settings/class-tab-knowledge-base.php:55
     904#: includes/Admin/Settings/class-tab-knowledge-base.php:74
     905msgid "Knowledge Base"
     906msgstr ""
     907
     908#: includes/Admin/Settings/class-tab-knowledge-base.php:75
     909msgid "Give the assistant accurate facts from your own content."
     910msgstr ""
     911
     912#: includes/Admin/Settings/class-tab-knowledge-base.php:77
     913msgid "Use the Knowledge Base"
     914msgstr ""
     915
     916#: includes/Admin/Settings/class-tab-knowledge-base.php:77
     917msgid "Answers use matching content from your site. The assistant stays limited to your website even when this is off."
     918msgstr ""
     919
     920#: includes/Admin/Settings/class-tab-knowledge-base.php:83
     921#: includes/Frontend/class-widget-config.php:249
     922msgid "Sources"
     923msgstr ""
     924
     925#: includes/Admin/Settings/class-tab-knowledge-base.php:84
     926msgid "Choose what the assistant can read."
     927msgstr ""
     928
     929#: includes/Admin/Settings/class-tab-knowledge-base.php:86
     930msgid "Content types"
     931msgstr ""
     932
     933#: includes/Admin/Settings/class-tab-knowledge-base.php:86
     934msgid "Posts and pages included in searches."
     935msgstr ""
     936
     937#: includes/Admin/Settings/class-tab-knowledge-base.php:87
     938msgid "Categories and tags"
     939msgstr ""
     940
     941#: includes/Admin/Settings/class-tab-knowledge-base.php:87
     942msgid "Term names and descriptions."
     943msgstr ""
     944
     945#: includes/Admin/Settings/class-tab-knowledge-base.php:88
     946#: includes/Kb/class-entry-presenter.php:113
     947msgid "Site summary"
     948msgstr ""
     949
     950#: includes/Admin/Settings/class-tab-knowledge-base.php:88
     951msgid "Site name, tagline, address and list of pages."
     952msgstr ""
     953
     954#: includes/Admin/Settings/class-tab-knowledge-base.php:89
     955msgid "Store summary"
     956msgstr ""
     957
     958#: includes/Admin/Settings/class-tab-knowledge-base.php:89
     959msgid "Shop links, currency and product categories."
     960msgstr ""
     961
     962#: includes/Admin/Settings/class-tab-knowledge-base.php:94
     963msgid "Search tuning"
     964msgstr ""
     965
     966#: includes/Admin/Settings/class-tab-knowledge-base.php:95
     967msgid "Fine-tune how content is matched and broken up."
     968msgstr ""
     969
     970#: includes/Admin/Settings/class-tab-knowledge-base.php:97
     971msgid "Passages per question"
     972msgstr ""
     973
     974#: includes/Admin/Settings/class-tab-knowledge-base.php:97
     975msgid "More passages give fuller answers but cost more."
     976msgstr ""
     977
     978#: includes/Admin/Settings/class-tab-knowledge-base.php:98
     979msgid "Passage size"
     980msgstr ""
     981
     982#: includes/Admin/Settings/class-tab-knowledge-base.php:98
     983msgid "Changing this re-indexes the whole knowledge base."
     984msgstr ""
     985
     986#: includes/Admin/Settings/class-tab-knowledge-base.php:98
     987#: includes/Admin/Settings/class-tab-protection.php:116
     988msgid "characters"
     989msgstr ""
     990
     991#: includes/Admin/Settings/class-tab-knowledge-base.php:99
     992msgid "Keep markdown copies"
     993msgstr ""
     994
     995#: includes/Admin/Settings/class-tab-knowledge-base.php:99
     996msgid "Saves a protected copy of each document in your uploads folder."
     997msgstr ""
     998
     999#: includes/Admin/Settings/class-tab-knowledge-base.php:104
     1000msgid "Index"
     1001msgstr ""
     1002
     1003#: includes/Admin/Settings/class-tab-knowledge-base.php:105
     1004msgid "The content the assistant can search."
     1005msgstr ""
     1006
     1007#: includes/Admin/Settings/class-tab-knowledge-base.php:122
     1008msgid "Stored in your WordPress database. No extra servers or accounts needed."
     1009msgstr ""
     1010
     1011#: includes/Admin/Settings/class-tab-knowledge-base.php:140
     1012#: includes/Admin/Settings/class-tab-knowledge-base.php:227
     1013msgid "Sync now"
     1014msgstr ""
     1015
     1016#: includes/Admin/Settings/class-tab-knowledge-base.php:141
     1017msgid "Test storage"
     1018msgstr ""
     1019
     1020#: includes/Admin/Settings/class-tab-knowledge-base.php:159
     1021#: includes/Admin/Settings/class-tab-knowledge-base.php:194
     1022#: assets/js/admin/kb-index.js:96
     1023msgid "Indexed"
     1024msgstr ""
     1025
     1026#: includes/Admin/Settings/class-tab-knowledge-base.php:160
     1027#: includes/Admin/Settings/class-tab-knowledge-base.php:195
     1028#: assets/js/admin/kb-index.js:97
     1029msgid "Pending"
     1030msgstr ""
     1031
     1032#: includes/Admin/Settings/class-tab-knowledge-base.php:161
     1033#: includes/Admin/Settings/class-tab-knowledge-base.php:196
     1034#: includes/Admin/Settings/class-tab-knowledge-base.php:202
     1035#: assets/js/admin/kb-index.js:98
     1036msgid "Excluded"
     1037msgstr ""
     1038
     1039#: includes/Admin/Settings/class-tab-knowledge-base.php:162
     1040#: includes/Admin/Settings/class-tab-knowledge-base.php:197
     1041#: assets/js/admin/kb-index.js:99
     1042msgid "Failed"
     1043msgstr ""
     1044
     1045#: includes/Admin/Settings/class-tab-knowledge-base.php:179
     1046msgid "Try again"
     1047msgstr ""
     1048
     1049#: includes/Admin/Settings/class-tab-knowledge-base.php:182
     1050msgid "Sync progress"
     1051msgstr ""
     1052
     1053#: includes/Admin/Settings/class-tab-knowledge-base.php:183
     1054msgid "You can leave this page. Syncing continues in the background."
     1055msgstr ""
     1056
     1057#: includes/Admin/Settings/class-tab-knowledge-base.php:186
     1058msgid "Show failed items"
     1059msgstr ""
     1060
     1061#: includes/Admin/Settings/class-tab-knowledge-base.php:189
     1062msgid "Search titles, URLs…"
     1063msgstr ""
     1064
     1065#: includes/Admin/Settings/class-tab-knowledge-base.php:189
     1066msgid "Search items in Knowledge Base"
     1067msgstr ""
     1068
     1069#: includes/Admin/Settings/class-tab-knowledge-base.php:191
     1070msgid "Filter by content type"
     1071msgstr ""
     1072
     1073#: includes/Admin/Settings/class-tab-knowledge-base.php:191
     1074#: assets/js/admin/kb-index.js:451
     1075msgid "All types"
     1076msgstr ""
     1077
     1078#: includes/Admin/Settings/class-tab-knowledge-base.php:192
     1079msgid "Filter by index status"
     1080msgstr ""
     1081
     1082#: includes/Admin/Settings/class-tab-knowledge-base.php:193
     1083msgid "All statuses"
     1084msgstr ""
     1085
     1086#: includes/Admin/Settings/class-tab-knowledge-base.php:199
     1087msgid "Filter by inclusion"
     1088msgstr ""
     1089
     1090#: includes/Admin/Settings/class-tab-knowledge-base.php:200
     1091msgid "All"
     1092msgstr ""
     1093
     1094#: includes/Admin/Settings/class-tab-knowledge-base.php:201
     1095#: includes/Admin/Settings/class-tab-knowledge-base.php:213
     1096msgid "Included"
     1097msgstr ""
     1098
     1099#: includes/Admin/Settings/class-tab-knowledge-base.php:207
     1100msgid "Knowledge Base items"
     1101msgstr ""
     1102
     1103#: includes/Admin/Settings/class-tab-knowledge-base.php:209
     1104msgid "Title"
     1105msgstr ""
     1106
     1107#: includes/Admin/Settings/class-tab-knowledge-base.php:210
     1108msgid "Type"
     1109msgstr ""
     1110
     1111#: includes/Admin/Settings/class-tab-knowledge-base.php:211
     1112msgid "Status"
     1113msgstr ""
     1114
     1115#: includes/Admin/Settings/class-tab-knowledge-base.php:212
     1116msgid "Updated"
     1117msgstr ""
     1118
     1119#: includes/Admin/Settings/class-tab-knowledge-base.php:216
     1120msgid "No items match your search."
     1121msgstr ""
     1122
     1123#: includes/Admin/Settings/class-tab-knowledge-base.php:217
     1124msgid "Clear search and filters"
     1125msgstr ""
     1126
     1127#: includes/Admin/Settings/class-tab-knowledge-base.php:218
     1128msgid "Knowledge Base pagination"
     1129msgstr ""
     1130
     1131#: includes/Admin/Settings/class-tab-knowledge-base.php:219
     1132msgid "‹ Previous"
     1133msgstr ""
     1134
     1135#: includes/Admin/Settings/class-tab-knowledge-base.php:221
     1136msgid "Next ›"
     1137msgstr ""
     1138
     1139#: includes/Admin/Settings/class-tab-knowledge-base.php:226
     1140msgid "No items yet."
     1141msgstr ""
     1142
     1143#: includes/Admin/Settings/class-tab-knowledge-base.php:226
     1144msgid "Choose your sources above, save settings, then click Sync now."
     1145msgstr ""
     1146
     1147#: includes/Admin/Settings/class-tab-knowledge-base.php:241
     1148#: assets/js/admin/kb-status.js:69
     1149msgid "Markdown copies could not be saved because your server asks for file system credentials. Indexing is not affected."
     1150msgstr ""
     1151
     1152#. translators: 1: date the last sync finished, 2: time it finished.
     1153#: includes/Admin/Settings/class-tab-knowledge-base.php:260
     1154#: assets/js/admin/kb-status.js:108
     1155#, php-format,js-format
     1156msgid "Last sync: %1$s, %2$s."
     1157msgstr ""
     1158
     1159#: includes/Admin/Settings/class-tab-protection.php:47
     1160msgid "Protection"
     1161msgstr ""
     1162
     1163#: includes/Admin/Settings/class-tab-protection.php:71
     1164#: includes/Admin/Settings/class-tab-protection.php:104
     1165msgid "Availability"
     1166msgstr ""
     1167
     1168#: includes/Admin/Settings/class-tab-protection.php:72
     1169#: includes/Admin/Settings/class-tab-protection.php:113
     1170msgid "Message limits"
     1171msgstr ""
     1172
     1173#: includes/Admin/Settings/class-tab-protection.php:73
     1174#: includes/Admin/Settings/class-tab-protection.php:122
     1175msgid "Rate limits"
     1176msgstr ""
     1177
     1178#: includes/Admin/Settings/class-tab-protection.php:74
     1179#: includes/Admin/Settings/class-tab-protection.php:154
     1180msgid "Escalation"
     1181msgstr ""
     1182
     1183#: includes/Admin/Settings/class-tab-protection.php:75
     1184#: includes/Admin/Settings/class-tab-protection.php:164
     1185msgid "Access rules"
     1186msgstr ""
     1187
     1188#: includes/Admin/Settings/class-tab-protection.php:76
     1189msgid "Human verification"
     1190msgstr ""
     1191
     1192#: includes/Admin/Settings/class-tab-protection.php:77
     1193#: includes/Admin/Settings/class-tab-protection.php:192
     1194msgid "Content moderation"
     1195msgstr ""
     1196
     1197#: includes/Admin/Settings/class-tab-protection.php:87
     1198msgid "messages"
     1199msgstr ""
     1200
     1201#: includes/Admin/Settings/class-tab-protection.php:93
     1202msgid "Per visitor"
     1203msgstr ""
     1204
     1205#: includes/Admin/Settings/class-tab-protection.php:97
     1206msgid "Whole site"
     1207msgstr ""
     1208
     1209#: includes/Admin/Settings/class-tab-protection.php:99
     1210msgid "Logged-in users"
     1211msgstr ""
     1212
     1213#: includes/Admin/Settings/class-tab-protection.php:105
     1214msgid "Choose when the chatbot accepts messages on your site."
     1215msgstr ""
     1216
     1217#: includes/Admin/Settings/class-tab-protection.php:107
     1218msgid "Enable chatbot"
     1219msgstr ""
     1220
     1221#: includes/Admin/Settings/class-tab-protection.php:107
     1222msgid "Shows the chat on your site and accepts messages. Turning it off hides the chat immediately."
     1223msgstr ""
     1224
     1225#: includes/Admin/Settings/class-tab-protection.php:114
     1226msgid "Cap the size and memory of each conversation."
     1227msgstr ""
     1228
     1229#: includes/Admin/Settings/class-tab-protection.php:116
     1230msgid "Maximum message length"
     1231msgstr ""
     1232
     1233#: includes/Admin/Settings/class-tab-protection.php:116
     1234msgid "Longer messages are shortened before they are sent to the AI."
     1235msgstr ""
     1236
     1237#: includes/Admin/Settings/class-tab-protection.php:117
     1238msgid "Conversation memory"
     1239msgstr ""
     1240
     1241#: includes/Admin/Settings/class-tab-protection.php:117
     1242msgid "How many earlier messages are sent with each question. Lower values reduce cost."
     1243msgstr ""
     1244
     1245#: includes/Admin/Settings/class-tab-protection.php:123
     1246msgid "Prevent misuse by limiting how fast questions can be sent."
     1247msgstr ""
     1248
     1249#: includes/Admin/Settings/class-tab-protection.php:128
     1250#: includes/Admin/Settings/class-tab-protection.php:134
     1251msgid "Per minute"
     1252msgstr ""
     1253
     1254#: includes/Admin/Settings/class-tab-protection.php:129
     1255msgid "Highest number of questions one visitor can send each minute."
     1256msgstr ""
     1257
     1258#: includes/Admin/Settings/class-tab-protection.php:130
     1259msgid "Behind a content delivery network or proxy, all visitors share one limit until trusted proxies are set up."
     1260msgstr ""
     1261
     1262#: includes/Admin/Settings/class-tab-protection.php:133
     1263#: includes/Admin/Settings/class-tab-protection.php:135
     1264msgid "Per hour"
     1265msgstr ""
     1266
     1267#: includes/Admin/Settings/class-tab-protection.php:133
     1268msgid "Highest number of questions one visitor can send each hour."
     1269msgstr ""
     1270
     1271#: includes/Admin/Settings/class-tab-protection.php:134
     1272msgid "Site-wide limit per minute. A shared ceiling across all visitors."
     1273msgstr ""
     1274
     1275#: includes/Admin/Settings/class-tab-protection.php:135
     1276msgid "Site-wide limit per hour. Protects against attacks from many addresses."
     1277msgstr ""
     1278
     1279#: includes/Admin/Settings/class-tab-protection.php:136
     1280msgid "Separate limits for logged-in users"
     1281msgstr ""
     1282
     1283#: includes/Admin/Settings/class-tab-protection.php:136
     1284msgid "Logged-in users get their own limits instead of sharing their network's."
     1285msgstr ""
     1286
     1287#: includes/Admin/Settings/class-tab-protection.php:137
     1288msgid "Extra allowance by role"
     1289msgstr ""
     1290
     1291#: includes/Admin/Settings/class-tab-protection.php:137
     1292msgid "×2 doubles the per-visitor limits for that role (1–10)."
     1293msgstr ""
     1294
     1295#: includes/Admin/Settings/class-tab-protection.php:141
     1296msgid "Message when a limit is reached"
     1297msgstr ""
     1298
     1299#: includes/Admin/Settings/class-tab-protection.php:142
     1300msgid "Optional. You can use {limit} and {window}. Leave empty for the default text."
     1301msgstr ""
     1302
     1303#: includes/Admin/Settings/class-tab-protection.php:144
     1304msgid "Limit message"
     1305msgstr ""
     1306
     1307#: includes/Admin/Settings/class-tab-protection.php:146
     1308#: includes/Rest/class-nonce-controller.php:111
     1309#: includes/Security/class-rate-limiter.php:127
     1310msgid "Too many requests. Please wait a minute and try again."
     1311msgstr ""
     1312
     1313#: includes/Admin/Settings/class-tab-protection.php:155
     1314msgid "What happens when the whole-site limit is hit again and again."
     1315msgstr ""
     1316
     1317#: includes/Admin/Settings/class-tab-protection.php:157
     1318msgid "Alert after"
     1319msgstr ""
     1320
     1321#: includes/Admin/Settings/class-tab-protection.php:157
     1322msgid "The site admin gets an email (at most every 30 minutes) and an admin notice."
     1323msgstr ""
     1324
     1325#: includes/Admin/Settings/class-tab-protection.php:157
     1326msgid "limit hits within an hour"
     1327msgstr ""
     1328
     1329#: includes/Admin/Settings/class-tab-protection.php:158
     1330msgid "Switch chat off automatically"
     1331msgstr ""
     1332
     1333#: includes/Admin/Settings/class-tab-protection.php:158
     1334msgid "Stops all chat traffic until you switch it back on."
     1335msgstr ""
     1336
     1337#: includes/Admin/Settings/class-tab-protection.php:159
     1338msgid "Protection cool-down"
     1339msgstr ""
     1340
     1341#: includes/Admin/Settings/class-tab-protection.php:159
     1342msgid "After you switch the chat back on, it cannot be switched off automatically again for this long."
     1343msgstr ""
     1344
     1345#: includes/Admin/Settings/class-tab-protection.php:159
     1346#: includes/Admin/Settings/class-tab-protection.php:183
     1347msgid "minutes"
     1348msgstr ""
     1349
     1350#: includes/Admin/Settings/class-tab-protection.php:165
     1351msgid "Block unwanted visitors and handle reverse proxies."
     1352msgstr ""
     1353
     1354#: includes/Admin/Settings/class-tab-protection.php:167
     1355msgid "Blocked addresses"
     1356msgstr ""
     1357
     1358#: includes/Admin/Settings/class-tab-protection.php:167
     1359msgid "One IP address or range per line, for example 203.0.113.7 or 198.51.100.0/24. IPv6 is supported."
     1360msgstr ""
     1361
     1362#: includes/Admin/Settings/class-tab-protection.php:168
     1363msgid "Bot trap"
     1364msgstr ""
     1365
     1366#: includes/Admin/Settings/class-tab-protection.php:168
     1367msgid "Adds an invisible field that only bots fill in. Visitors never see it."
     1368msgstr ""
     1369
     1370#: includes/Admin/Settings/class-tab-protection.php:169
     1371msgid "Use a trusted proxy"
     1372msgstr ""
     1373
     1374#: includes/Admin/Settings/class-tab-protection.php:169
     1375msgid "Turn on only if your site is behind a proxy or CDN such as Cloudflare."
     1376msgstr ""
     1377
     1378#: includes/Admin/Settings/class-tab-protection.php:170
     1379msgid "Visitor IP header"
     1380msgstr ""
     1381
     1382#: includes/Admin/Settings/class-tab-protection.php:170
     1383msgid "Header that contains the real visitor IP."
     1384msgstr ""
     1385
     1386#: includes/Admin/Settings/class-tab-protection.php:171
     1387msgid "Trusted proxy addresses"
     1388msgstr ""
     1389
     1390#: includes/Admin/Settings/class-tab-protection.php:171
     1391msgid "The header is only trusted for requests coming from these addresses. One per line."
     1392msgstr ""
     1393
     1394#: includes/Admin/Settings/class-tab-protection.php:177
     1395msgid "Human verification (Google reCAPTCHA v3)"
     1396msgstr ""
     1397
     1398#: includes/Admin/Settings/class-tab-protection.php:178
     1399msgid "Stop bots without giving visitors puzzles to solve."
     1400msgstr ""
     1401
     1402#: includes/Admin/Settings/class-tab-protection.php:180
     1403msgid "Site key"
     1404msgstr ""
     1405
     1406#: includes/Admin/Settings/class-tab-protection.php:180
     1407msgid "Your public reCAPTCHA v3 site key."
     1408msgstr ""
     1409
     1410#: includes/Admin/Settings/class-tab-protection.php:181
     1411msgid "Secret key"
     1412msgstr ""
     1413
     1414#: includes/Admin/Settings/class-tab-protection.php:181
     1415msgid "Your reCAPTCHA v3 secret key. Kept private and never shown after saving."
     1416msgstr ""
     1417
     1418#: includes/Admin/Settings/class-tab-protection.php:182
     1419msgid "Minimum score"
     1420msgstr ""
     1421
     1422#: includes/Admin/Settings/class-tab-protection.php:182
     1423msgid "0.0 is likely a bot, 1.0 is likely a human. 0.5 is a good start."
     1424msgstr ""
     1425
     1426#: includes/Admin/Settings/class-tab-protection.php:183
     1427msgid "Verified for"
     1428msgstr ""
     1429
     1430#: includes/Admin/Settings/class-tab-protection.php:183
     1431msgid "How long a verified visitor can chat before being checked again."
     1432msgstr ""
     1433
     1434#: includes/Admin/Settings/class-tab-protection.php:193
     1435msgid "Filter harmful or unwanted questions before they reach the AI."
     1436msgstr ""
     1437
     1438#: includes/Admin/Settings/class-tab-protection.php:195
     1439msgid "Check messages before they reach the AI"
     1440msgstr ""
     1441
     1442#: includes/Admin/Settings/class-tab-protection.php:195
     1443msgid "Checks each question with OpenAI moderation and your list of blocked words."
     1444msgstr ""
     1445
     1446#: includes/Admin/Settings/class-tab-protection.php:196
     1447msgid "Use OpenAI moderation"
     1448msgstr ""
     1449
     1450#: includes/Admin/Settings/class-tab-protection.php:196
     1451msgid "Uses your Connectors key. No extra key needed."
     1452msgstr ""
     1453
     1454#: includes/Admin/Settings/class-tab-protection.php:197
     1455msgid "Moderation time limit"
     1456msgstr ""
     1457
     1458#: includes/Admin/Settings/class-tab-protection.php:197
     1459msgid "How long to wait for OpenAI moderation. If it does not answer in time, the message is sent without it."
     1460msgstr ""
     1461
     1462#: includes/Admin/Settings/class-tab-protection.php:198
     1463msgid "Blocked words and phrases"
     1464msgstr ""
     1465
     1466#: includes/Admin/Settings/class-tab-protection.php:198
     1467msgid "One per line. Whole words, not case-sensitive."
     1468msgstr ""
     1469
     1470#: includes/Admin/Settings/class-tab-protection.php:199
     1471msgid "Reply to blocked messages"
     1472msgstr ""
     1473
     1474#: includes/Admin/Settings/class-tab-protection.php:199
     1475msgid "Shown to visitors when their question is refused by moderation."
     1476msgstr ""
     1477
     1478#: includes/Admin/Settings/class-tab-protection.php:218
     1479msgid "Use a trusted proxy is on, but no trusted proxy addresses are listed, so the header is not used."
     1480msgstr ""
     1481
     1482#: includes/Admin/Settings/class-tab-protection.php:222
     1483msgid "A trusted proxy address is also in the blocked list: every request through it would be refused."
     1484msgstr ""
     1485
     1486#: includes/Admin/Settings/class-tab-protection.php:229
     1487msgid "Some trusted proxy ranges are too wide and are ignored: list only your proxy's own addresses."
     1488msgstr ""
     1489
     1490#: includes/Admin/Settings/class-tab-protection.php:246
     1491msgid "Clear rate-limit counters"
     1492msgstr ""
     1493
     1494#: includes/Admin/Settings/class-tab-protection.php:248
     1495msgid "Starts every visitor, user and site-wide count from zero, for example after a false alarm. Verification passes and settings are not changed."
     1496msgstr ""
     1497
     1498#. translators: %s: date the chat was switched off.
     1499#: includes/Admin/Settings/class-tab-protection.php:266
     1500#, php-format
     1501msgid "Switched off automatically on %s after repeated site-wide limit hits."
     1502msgstr ""
     1503
     1504#: includes/Admin/Settings/class-tab-protection.php:282
     1505msgid "Active – keys from server environment"
     1506msgstr ""
     1507
     1508#: includes/Admin/Settings/class-tab-protection.php:288
     1509msgid "Off – add both keys to enable"
     1510msgstr ""
     1511
     1512#: includes/Admin/Settings/class-tab-protection.php:299
     1513msgid "Visitors see a short verification overlay on the chat window. Google's script loads only when both keys are set."
     1514msgstr ""
     1515
     1516#: includes/Admin/Settings/class-tab-protection.php:300
     1517msgid "Get reCAPTCHA v3 keys ↗"
     1518msgstr ""
     1519
     1520#: includes/Admin/Settings/class-tab-protection.php:313
     1521msgid "OpenAI moderation is unavailable until an OpenAI key is configured in WordPress Connectors."
     1522msgstr ""
     1523
     1524#: includes/Admin/Settings/class-tab-welcome.php:44
    1171525msgid "Welcome"
    1181526msgstr ""
    1191527
    120 #: includes/Admin/class-settings-page.php:128
    121 msgid "Protection"
    122 msgstr ""
    123 
    124 #: includes/Admin/class-settings-page.php:129
    125 msgid "Appearance"
    126 msgstr ""
    127 
    128 #: includes/Admin/class-settings-page.php:130
    129 msgid "AI Settings"
    130 msgstr ""
    131 
    132 #: includes/Admin/class-settings-page.php:173
    133 msgid "ChatHearth - AI Chatbot Settings"
    134 msgstr ""
    135 
    136 #: includes/Admin/class-settings-page.php:178
    137 msgid ""
    138 "Configure OpenAI API key under WordPress Connectors. This plugin does not "
    139 "store the API key."
    140 msgstr ""
    141 
    142 #: includes/Admin/class-settings-page.php:182
    143 msgid "Open Connectors"
    144 msgstr ""
    145 
    146 #: includes/Admin/class-settings-page.php:185
    147 msgid "Settings sections"
    148 msgstr ""
    149 
    150 #: includes/Admin/class-settings-page.php:204
     1528#: includes/Admin/Settings/class-tab-welcome.php:60
     1529msgid "Live suggestion chips preview"
     1530msgstr ""
     1531
     1532#. translators: %d: number of further suggestions that are not shown as chips.
     1533#: includes/Admin/Settings/class-tab-welcome.php:68
     1534#: assets/js/admin/starters.js:38
     1535#, php-format,js-format
     1536msgid "+%d more"
     1537msgid_plural "+%d more"
     1538msgstr[0] ""
     1539msgstr[1] ""
     1540
     1541#: includes/Admin/Settings/class-tab-welcome.php:85
     1542msgid "Greeting"
     1543msgstr ""
     1544
     1545#: includes/Admin/Settings/class-tab-welcome.php:86
     1546msgid "What visitors see when they open the chat."
     1547msgstr ""
     1548
     1549#: includes/Admin/Settings/class-tab-welcome.php:88
    1511550msgid "Welcome message"
    1521551msgstr ""
    1531552
    154 #: includes/Admin/class-settings-page.php:208
    155 msgid "Starter phrases"
    156 msgstr ""
    157 
    158 #: includes/Admin/class-settings-page.php:211
    159 msgid "One suggested prompt per line. Shown as clickable chips in the chat."
    160 msgstr ""
    161 
    162 #: includes/Admin/class-settings-page.php:220
    163 msgid "Enable chatbot"
    164 msgstr ""
    165 
    166 #: includes/Admin/class-settings-page.php:224
    167 msgid "Show the chatbot on the front end and allow chat requests"
    168 msgstr ""
    169 
    170 #: includes/Admin/class-settings-page.php:229
    171 msgid "Max requests per minute (per IP)"
    172 msgstr ""
    173 
    174 #: includes/Admin/class-settings-page.php:233
    175 msgid "Max requests per hour (per IP)"
    176 msgstr ""
    177 
    178 #: includes/Admin/class-settings-page.php:237
    179 msgid "Max requests per minute (entire site)"
    180 msgstr ""
    181 
    182 #: includes/Admin/class-settings-page.php:240
    183 msgid "Applies across all visitors. Helps stop multi-IP floods."
    184 msgstr ""
    185 
    186 #: includes/Admin/class-settings-page.php:244
    187 msgid "Max requests per hour (entire site)"
    188 msgstr ""
    189 
    190 #: includes/Admin/class-settings-page.php:248
    191 msgid "Escalate after global limit hits"
    192 msgstr ""
    193 
    194 #: includes/Admin/class-settings-page.php:251
    195 msgid ""
    196 "Number of site-wide limit blocks within an hour before emailing the admin."
    197 msgstr ""
    198 
    199 #: includes/Admin/class-settings-page.php:255
    200 msgid "Auto-disable on escalation"
    201 msgstr ""
    202 
    203 #: includes/Admin/class-settings-page.php:259
    204 msgid "Turn off the chatbot when the escalation threshold is reached"
    205 msgstr ""
    206 
    207 #: includes/Admin/class-settings-page.php:264
    208 msgid "Max message length"
    209 msgstr ""
    210 
    211 #: includes/Admin/class-settings-page.php:268
    212 msgid "Google reCAPTCHA v2"
    213 msgstr ""
    214 
    215 #: includes/Admin/class-settings-page.php:272
    216 msgid ""
    217 "CAPTCHA is enabled. Visitors complete the reCAPTCHA v2 checkbox once; "
    218 "further messages in the next hour stay unlocked."
    219 msgstr ""
    220 
    221 #: includes/Admin/class-settings-page.php:275
    222 msgid ""
    223 "CAPTCHA is disabled until both site key and secret key are set. Create a "
    224 "reCAPTCHA v2 (“I’m not a robot” Checkbox) key for your domain."
    225 msgstr ""
    226 
    227 #: includes/Admin/class-settings-page.php:280
    228 msgid "reCAPTCHA site key"
    229 msgstr ""
    230 
    231 #: includes/Admin/class-settings-page.php:286
    232 msgid "reCAPTCHA secret key"
    233 msgstr ""
    234 
    235 #: includes/Admin/class-settings-page.php:288
    236 msgid "•••••••• (saved — leave blank to keep)"
    237 msgstr ""
    238 
    239 #: includes/Admin/class-settings-page.php:292
    240 msgid "Clear saved secret key"
    241 msgstr ""
    242 
    243 #: includes/Admin/class-settings-page.php:297
    244 msgid ""
    245 "Get keys from Google reCAPTCHA admin. Leave the secret blank when saving to "
    246 "keep the current value."
    247 msgstr ""
    248 
    249 #: includes/Admin/class-settings-page.php:308
    250 msgid "Icon shape"
    251 msgstr ""
    252 
    253 #: includes/Admin/class-settings-page.php:311
    254 msgid "Circle"
    255 msgstr ""
    256 
    257 #: includes/Admin/class-settings-page.php:312
    258 msgid "Square"
    259 msgstr ""
    260 
    261 #: includes/Admin/class-settings-page.php:317
    262 msgid "Position"
    263 msgstr ""
    264 
    265 #: includes/Admin/class-settings-page.php:320
    266 msgid "Bottom right"
    267 msgstr ""
    268 
    269 #: includes/Admin/class-settings-page.php:321
    270 msgid "Bottom left"
    271 msgstr ""
    272 
    273 #: includes/Admin/class-settings-page.php:326
    274 msgid "Popup size"
    275 msgstr ""
    276 
    277 #: includes/Admin/class-settings-page.php:329
    278 msgid "Small"
    279 msgstr ""
    280 
    281 #: includes/Admin/class-settings-page.php:330
    282 msgid "Medium"
    283 msgstr ""
    284 
    285 #: includes/Admin/class-settings-page.php:331
    286 msgid "Large"
    287 msgstr ""
    288 
    289 #: includes/Admin/class-settings-page.php:336
    290 msgid "Icon size (px)"
    291 msgstr ""
    292 
    293 #: includes/Admin/class-settings-page.php:340
    294 msgid "Header title"
    295 msgstr ""
    296 
    297 #: includes/Admin/class-settings-page.php:345
    298 msgid "Icon background color"
    299 msgstr ""
    300 
    301 #: includes/Admin/class-settings-page.php:346
    302 msgid "Icon border color"
    303 msgstr ""
    304 
    305 #: includes/Admin/class-settings-page.php:347
    306 msgid "Icon (glyph) color"
    307 msgstr ""
    308 
    309 #: includes/Admin/class-settings-page.php:348
    310 msgid "User bubble color"
    311 msgstr ""
    312 
    313 #: includes/Admin/class-settings-page.php:349
    314 msgid "Assistant bubble color"
    315 msgstr ""
    316 
    317 #: includes/Admin/class-settings-page.php:364
    318 msgid "AI provider"
    319 msgstr ""
    320 
    321 #: includes/Admin/class-settings-page.php:371
    322 msgid ""
    323 "More providers can be added in future releases. Configure the API key under "
    324 "Connectors."
    325 msgstr ""
    326 
    327 #: includes/Admin/class-settings-page.php:375
    328 msgid "Chat model"
    329 msgstr ""
    330 
    331 #: includes/Admin/class-settings-page.php:382
    332 msgid "Select an OpenAI model for chat replies."
    333 msgstr ""
    334 
    335 #: includes/Admin/class-settings-page.php:386
    336 msgid "System prompt"
    337 msgstr ""
    338 
    339 #: includes/Admin/class-settings-page.php:394
    340 msgid "Save settings"
    341 msgstr ""
    342 
    343 #: includes/Ai/class-ai-gateway.php:45
    344 msgid ""
    345 "The AI provider is not configured. Please check OpenAI Connectors settings."
    346 msgstr ""
    347 
    348 #: includes/Ai/class-ai-gateway.php:133
    349 msgid ""
    350 "Sorry, the assistant could not generate a reply. Please try again later."
    351 msgstr ""
    352 
    353 #: includes/Frontend/class-assets.php:88
     1553#: includes/Admin/Settings/class-tab-welcome.php:88
     1554msgid "Shown as the first message in the chat."
     1555msgstr ""
     1556
     1557#: includes/Admin/Settings/class-tab-welcome.php:89
     1558msgid "Starter suggestions"
     1559msgstr ""
     1560
     1561#: includes/Admin/Settings/class-tab-welcome.php:89
     1562msgid "One suggestion per line. Visitors can click them to start a conversation."
     1563msgstr ""
     1564
     1565#. translators: 1: help text, 2: the allowed range, such as "100–8,000".
     1566#: includes/Admin/Settings/class-tab.php:152
     1567#, php-format
     1568msgctxt "help text followed by its allowed range"
     1569msgid "%1$s (%2$s)"
     1570msgstr ""
     1571
     1572#. translators: %s: the product names joined by " vs ".
     1573#: includes/Chat/class-catalog-stage.php:136
     1574#: includes/Frontend/class-widget-config.php:252
     1575#, php-format
     1576msgid "Compare %s in a markdown table covering price, stock, and key differences. Use only catalog facts and include product links."
     1577msgstr ""
     1578
     1579#: includes/Chat/class-chat-pipeline.php:130
     1580msgid "Sorry, the assistant could not generate a reply. Please try again later."
     1581msgstr ""
     1582
     1583#: includes/Chat/class-input-stage.php:48
     1584msgid "Please enter a message."
     1585msgstr ""
     1586
     1587#: includes/Chat/class-instructions-stage.php:74
     1588msgid "The AI provider is not configured. Please check OpenAI Connectors settings."
     1589msgstr ""
     1590
     1591#: includes/Commerce/class-cart-service.php:116
     1592#: includes/Frontend/class-widget-config.php:274
     1593msgid "Could not add that product to the cart."
     1594msgstr ""
     1595
     1596#: includes/Commerce/class-cart-service.php:224
     1597msgid "That product is not available."
     1598msgstr ""
     1599
     1600#: includes/Commerce/class-cart-service.php:235
     1601msgid "That product cannot be added to the cart."
     1602msgstr ""
     1603
     1604#: includes/Frontend/class-widget-config.php:242
    3541605msgid "Type your message…"
    3551606msgstr ""
    3561607
    357 #: includes/Frontend/class-assets.php:89
     1608#: includes/Frontend/class-widget-config.php:243
    3581609msgid "Send"
    3591610msgstr ""
    3601611
    361 #: includes/Frontend/class-assets.php:90
     1612#: includes/Frontend/class-widget-config.php:244
    3621613msgid "Clear chat"
    3631614msgstr ""
    3641615
    365 #: includes/Frontend/class-assets.php:91
     1616#: includes/Frontend/class-widget-config.php:245
    3661617msgid "Close chat"
    3671618msgstr ""
    3681619
    369 #: includes/Frontend/class-assets.php:92
     1620#: includes/Frontend/class-widget-config.php:246
    3701621msgid "Open chat"
    3711622msgstr ""
    3721623
    373 #: includes/Frontend/class-assets.php:93
     1624#: includes/Frontend/class-widget-config.php:247
    3741625msgid "Sorry, something went wrong. Please try again."
    3751626msgstr ""
    3761627
    377 #: includes/Frontend/class-assets.php:94
     1628#: includes/Frontend/class-widget-config.php:248
     1629#: includes/Frontend/class-widget-config.php:284
    3781630msgid "Thinking…"
    3791631msgstr ""
    3801632
    381 #: includes/Frontend/class-assets.php:95
    382 msgid "Please complete the CAPTCHA before sending."
    383 msgstr ""
    384 
    385 #: includes/Rest/class-chat-controller.php:124
     1633#: includes/Frontend/class-widget-config.php:250
     1634msgid "Compare these products"
     1635msgstr ""
     1636
     1637#: includes/Frontend/class-widget-config.php:253
     1638msgid "Tell me about this page"
     1639msgstr ""
     1640
     1641#: includes/Frontend/class-widget-config.php:254
     1642msgid "Double chat size"
     1643msgstr ""
     1644
     1645#: includes/Frontend/class-widget-config.php:255
     1646msgid "Restore chat size"
     1647msgstr ""
     1648
     1649#: includes/Frontend/class-widget-config.php:256
     1650msgid "Please reload the page to keep chatting."
     1651msgstr ""
     1652
     1653#: includes/Frontend/class-widget-config.php:257
     1654msgid "Reload page"
     1655msgstr ""
     1656
     1657#: includes/Frontend/class-widget-config.php:258
     1658msgid "New reply"
     1659msgstr ""
     1660
     1661#: includes/Frontend/class-widget-config.php:259
     1662msgid "Please verify you are human before chatting."
     1663msgstr ""
     1664
     1665#: includes/Frontend/class-widget-config.php:260
     1666msgid "Please verify you are human to start chatting."
     1667msgstr ""
     1668
     1669#: includes/Frontend/class-widget-config.php:261
     1670msgid "Continue"
     1671msgstr ""
     1672
     1673#: includes/Frontend/class-widget-config.php:262
     1674msgid "Verifying…"
     1675msgstr ""
     1676
     1677#: includes/Frontend/class-widget-config.php:263
     1678msgid "Verification failed. Please try again."
     1679msgstr ""
     1680
     1681#. translators: 1: privacy policy link, 2: terms of service link
     1682#: includes/Frontend/class-widget-config.php:265
     1683#, php-format
     1684msgid "This site is protected by reCAPTCHA and the Google %1$s and %2$s apply."
     1685msgstr ""
     1686
     1687#: includes/Frontend/class-widget-config.php:266
     1688msgid "Privacy Policy"
     1689msgstr ""
     1690
     1691#: includes/Frontend/class-widget-config.php:267
     1692msgid "Terms of Service"
     1693msgstr ""
     1694
     1695#: includes/Frontend/class-widget-config.php:268
     1696msgid "Your browser did not keep the verification. Please allow cookies for this site to keep chatting."
     1697msgstr ""
     1698
     1699#: includes/Frontend/class-widget-config.php:269
     1700msgid "Leave this field empty"
     1701msgstr ""
     1702
     1703#: includes/Frontend/class-widget-config.php:271
     1704msgid "Added to cart."
     1705msgstr ""
     1706
     1707#: includes/Frontend/class-widget-config.php:272
     1708msgid "View cart"
     1709msgstr ""
     1710
     1711#: includes/Frontend/class-widget-config.php:273
     1712msgid "Checkout"
     1713msgstr ""
     1714
     1715#: includes/Frontend/class-widget-config.php:275
     1716msgid "In stock"
     1717msgstr ""
     1718
     1719#: includes/Frontend/class-widget-config.php:276
     1720msgid "Out of stock"
     1721msgstr ""
     1722
     1723#: includes/Frontend/class-widget-config.php:277
     1724msgid "Choose an option"
     1725msgstr ""
     1726
     1727#: includes/Frontend/class-widget-config.php:278
     1728msgid "Choose options"
     1729msgstr ""
     1730
     1731#: includes/Frontend/class-widget-config.php:279
     1732msgid "Adding…"
     1733msgstr ""
     1734
     1735#: includes/Frontend/class-widget-config.php:280
     1736msgid "Not available to buy in the chat"
     1737msgstr ""
     1738
     1739#. translators: %s: a product option and its value, for example "Size: Large".
     1740#: includes/Frontend/class-widget-config.php:282
     1741#, php-format
     1742msgid "%s (out of stock)"
     1743msgstr ""
     1744
     1745#: includes/Frontend/class-widget-config.php:285
     1746msgid "Reading your question…"
     1747msgstr ""
     1748
     1749#: includes/Frontend/class-widget-config.php:286
     1750msgid "Looking through the site…"
     1751msgstr ""
     1752
     1753#: includes/Frontend/class-widget-config.php:287
     1754msgid "Searching for relevant information…"
     1755msgstr ""
     1756
     1757#: includes/Frontend/class-widget-config.php:288
     1758msgid "Checking the details…"
     1759msgstr ""
     1760
     1761#: includes/Frontend/class-widget-config.php:289
     1762msgid "Putting the pieces together…"
     1763msgstr ""
     1764
     1765#: includes/Frontend/class-widget-config.php:290
     1766msgid "Preparing the best answer for you…"
     1767msgstr ""
     1768
     1769#: includes/Frontend/class-widget-config.php:291
     1770msgid "Almost there…"
     1771msgstr ""
     1772
     1773#: includes/Frontend/class-widget-config.php:292
     1774msgid "Still working on it…"
     1775msgstr ""
     1776
     1777#: includes/Frontend/class-widget-config.php:293
     1778msgid "Thanks for waiting, just a moment more…"
     1779msgstr ""
     1780
     1781#: includes/Kb/class-failure-reasons.php:33
     1782msgid "OpenAI was busy or did not answer. It will be tried again on the next sync."
     1783msgstr ""
     1784
     1785#: includes/Kb/class-failure-reasons.php:36
     1786msgid "OpenAI could not use this item. Editing the item or the next sync may fix it."
     1787msgstr ""
     1788
     1789#: includes/Kb/class-failure-reasons.php:38
     1790msgid "OpenAI refused the connection. Check the connection under Settings → Connectors."
     1791msgstr ""
     1792
     1793#: includes/Kb/class-failure-reasons.php:40
     1794msgid "This item has no text to index."
     1795msgstr ""
     1796
     1797#: includes/Kb/class-failure-reasons.php:43
     1798msgid "This item could not be indexed. It will be tried again on the next sync."
     1799msgstr ""
     1800
     1801#: includes/Kb/class-kb-entry-toggle.php:69
     1802msgid "Missing source id."
     1803msgstr ""
     1804
     1805#: includes/Kb/class-kb-entry-toggle.php:73
     1806#: includes/Kb/class-kb-entry-toggle.php:88
     1807msgid "Entry not found."
     1808msgstr ""
     1809
     1810#: includes/Kb/class-status-report.php:114
     1811msgid "The Knowledge Base is off."
     1812msgstr ""
     1813
     1814#: includes/Kb/class-status-report.php:117
     1815msgid "Indexing is paused until OpenAI is ready."
     1816msgstr ""
     1817
     1818#. translators: %s: number of items waiting to be indexed.
     1819#: includes/Kb/class-status-report.php:121
     1820#, php-format
     1821msgid "Indexing %s item…"
     1822msgid_plural "Indexing %s items…"
     1823msgstr[0] ""
     1824msgstr[1] ""
     1825
     1826#: includes/Kb/class-status-report.php:124
     1827#: assets/js/admin/kb-status.js:167
     1828msgid "Checking your content…"
     1829msgstr ""
     1830
     1831#: includes/Kb/class-status-report.php:127
     1832msgid "Indexing finished. Some items could not be indexed."
     1833msgstr ""
     1834
     1835#: includes/Kb/class-status-report.php:130
     1836msgid "Everything is indexed."
     1837msgstr ""
     1838
     1839#: includes/Kb/class-status-report.php:133
     1840msgid "Nothing is indexed yet."
     1841msgstr ""
     1842
     1843#: includes/Kb/class-store-check.php:92
     1844msgid "The knowledge base is stored in this WordPress database. No extra server is required."
     1845msgstr ""
     1846
     1847#: includes/Kb/class-store-check.php:93
     1848msgid "The knowledge base tables are not available."
     1849msgstr ""
     1850
     1851#: includes/Kb/class-store-check.php:96
     1852msgid "Storage is ready."
     1853msgstr ""
     1854
     1855#: includes/Kb/class-store-check.php:97
     1856msgid "The custom storage did not answer."
     1857msgstr ""
     1858
     1859#: includes/Moderation/class-content-moderation.php:231
     1860msgid "Sorry, that message cannot be processed. Please rephrase and try again."
     1861msgstr ""
     1862
     1863#: includes/Rest/class-cart-controller.php:166
     1864#: includes/Rest/class-chat-controller.php:271
     1865#: includes/Rest/class-nonce-controller.php:98
     1866#: includes/Rest/class-recaptcha-controller.php:80
     1867msgid "The chatbot is currently disabled."
     1868msgstr ""
     1869
     1870#: includes/Rest/class-cart-controller.php:179
     1871msgid "The store cart is not available."
     1872msgstr ""
     1873
     1874#: includes/Rest/class-cart-controller.php:191
     1875#: includes/Security/class-human-check.php:61
     1876#: includes/Security/class-rate-limiter.php:139
     1877msgid "Too many requests. Please wait a moment and try again."
     1878msgstr ""
     1879
     1880#: includes/Rest/class-cart-controller.php:198
     1881msgid "Too many cart requests. Please wait a few minutes and try again."
     1882msgstr ""
     1883
     1884#: includes/Rest/class-chat-controller.php:156
     1885msgid "The conversation history is not valid."
     1886msgstr ""
     1887
     1888#: includes/Rest/class-chat-controller.php:225
    3861889msgid "Invalid security token. Please refresh the page and try again."
    3871890msgstr ""
    3881891
    389 #: includes/Rest/class-chat-controller.php:142
    390 msgid "The chatbot is currently disabled."
    391 msgstr ""
    392 
    393 #: includes/Rest/class-chat-controller.php:163
    394 msgid "Please enter a message."
    395 msgstr ""
    396 
    397 #. translators: %s: site name
    398 #: includes/Security/class-rate-limiter.php:260
     1892#: includes/Rest/class-kb-permission.php:51
     1893msgid "You are not allowed to manage the knowledge base."
     1894msgstr ""
     1895
     1896#: includes/Rest/class-request-guard.php:95
     1897msgid "Your message is too long to send. Please shorten the conversation and try again."
     1898msgstr ""
     1899
     1900#: includes/Security/class-access-check.php:49
     1901msgid "Sorry, the chat is not available to you."
     1902msgstr ""
     1903
     1904#. translators: %s: site name.
     1905#: includes/Security/class-escalation-mailer.php:80
    3991906#, php-format
    4001907msgid "[%s] ChatHearth - AI Chatbot: global rate limit escalation"
    4011908msgstr ""
    4021909
    403 #: includes/Security/class-rate-limiter.php:265
    404 msgid ""
    405 "ChatHearth - AI Chatbot blocked site-wide chat traffic after repeated global "
    406 "rate-limit hits."
    407 msgstr ""
    408 
    409 #. translators: %d: number of global limit hits in the current hour
    410 #: includes/Security/class-rate-limiter.php:269
     1910#: includes/Security/class-escalation-mailer.php:84
     1911msgid "ChatHearth - AI Chatbot blocked site-wide chat traffic after repeated global rate-limit hits."
     1912msgstr ""
     1913
     1914#. translators: %d: number of site-wide rate limit hits.
     1915#: includes/Security/class-escalation-mailer.php:87
    4111916#, php-format
    4121917msgid "Global limit hits in the last hour: %d"
    4131918msgstr ""
    4141919
    415 #. translators: 1: per-minute limit, 2: per-hour limit
    416 #: includes/Security/class-rate-limiter.php:274
     1920#. translators: 1: site-wide limit per minute, 2: site-wide limit per hour.
     1921#: includes/Security/class-escalation-mailer.php:89
    4171922#, php-format
    4181923msgid "Configured global limits: %1$d/minute, %2$d/hour"
    4191924msgstr ""
    4201925
    421 #: includes/Security/class-rate-limiter.php:282
    422 msgid ""
    423 "The chatbot has been automatically disabled. Re-enable it under Settings → "
    424 "ChatHearth - AI Chatbot → Protection when ready."
    425 msgstr ""
    426 
    427 #: includes/Security/class-rate-limiter.php:286
     1926#: includes/Security/class-escalation-mailer.php:93
     1927msgid "The chatbot has been automatically disabled. Re-enable it under Settings → ChatHearth - AI Chatbot → Protection when ready."
     1928msgstr ""
     1929
     1930#: includes/Security/class-escalation-mailer.php:95
     1931msgid "Switch the chat back on now (administrators only; works once, for 24 hours):"
     1932msgstr ""
     1933
     1934#. translators: %d: configured re-arm pause in minutes.
     1935#: includes/Security/class-escalation-mailer.php:100
     1936#, php-format
     1937msgid "The chat was not switched off, because it was switched back on less than %d minutes ago."
     1938msgstr ""
     1939
     1940#: includes/Security/class-escalation-mailer.php:103
    4281941msgid "Protection settings:"
    4291942msgstr ""
    4301943
    431 #: includes/Security/class-rate-limiter.php:322
    432 msgid ""
    433 "The chatbot is temporarily unavailable due to high demand. Please try again "
    434 "later."
    435 msgstr ""
    436 
    437 #: includes/Security/class-rate-limiter.php:333
    438 msgid "Too many requests. Please wait a minute and try again."
    439 msgstr ""
    440 
    441 #: includes/Security/class-rate-limiter.php:344
     1944#: includes/Security/class-rate-limiter.php:74
     1945msgid "The chatbot is temporarily unavailable due to high demand. Please try again later."
     1946msgstr ""
     1947
     1948#. translators: The window of a message limit, used in "You can send 10 messages per hour." Keep it a single lower-case word.
     1949#: includes/Security/class-rate-limiter.php:117
     1950msgid "hour"
     1951msgstr ""
     1952
     1953#. translators: The window of a message limit, used in "You can send 10 messages per minute." Keep it a single lower-case word.
     1954#: includes/Security/class-rate-limiter.php:119
     1955msgid "minute"
     1956msgstr ""
     1957
     1958#: includes/Security/class-rate-limiter.php:126
    4421959msgid "Hourly message limit reached. Please try again later."
    4431960msgstr ""
    4441961
    445 #: includes/Security/class-rate-limiter.php:355
    446 msgid "Too many requests. Please wait a moment and try again."
    447 msgstr ""
    448 
    449 #: includes/Security/class-recaptcha.php:54
     1962#: includes/Security/class-recaptcha-v3.php:88
     1963msgid "CAPTCHA verification failed. Please try again."
     1964msgstr ""
     1965
     1966#: includes/Security/class-recaptcha-v3.php:95
    4501967msgid "Please complete the CAPTCHA and try again."
    4511968msgstr ""
    4521969
    453 #: includes/Security/class-recaptcha.php:84
     1970#: includes/Security/class-recaptcha-v3.php:100
    4541971msgid "CAPTCHA verification is temporarily unavailable. Please try again."
    4551972msgstr ""
    4561973
    457 #: includes/Security/class-recaptcha.php:95
    458 msgid "CAPTCHA verification failed. Please try again."
    459 msgstr ""
    460 
    461 #. Description of the plugin/theme
    462 msgid "Site-wide AI chatbot powered by WordPress Connectors (OpenAI in v1)."
    463 msgstr ""
    464 
    465 #. Author of the plugin/theme
    466 msgid "PalWP"
    467 msgstr ""
    468 
    469 #. Author URI of the plugin/theme
    470 msgid "https://palwp.com/"
    471 msgstr ""
     1974#: includes/Settings/class-settings-repository.php:83
     1975msgid "ChatHearth settings."
     1976msgstr ""
     1977
     1978#. translators: 1: setting name, 2: the line numbers that were removed, such as "2 and 5".
     1979#: includes/Settings/class-settings-repository.php:244
     1980#, php-format
     1981msgid "%1$s: line %2$s was removed"
     1982msgid_plural "%1$s: lines %2$s were removed"
     1983msgstr[0] ""
     1984msgstr[1] ""
     1985
     1986#. translators: 1: setting name, 2: the value that was submitted, 3: the value that was kept.
     1987#: includes/Settings/class-settings-repository.php:256
     1988#, php-format
     1989msgid "%1$s: \"%2$s\" became \"%3$s\""
     1990msgstr ""
     1991
     1992#: includes/Settings/class-settings-repository.php:266
     1993msgid "ChatHearth corrected some values before saving:"
     1994msgstr ""
     1995
     1996#. translators: %s: contrast ratio such as 3.1 (shown as 3.1:1).
     1997#: assets/js/admin/appearance-preview.js:147
     1998#, js-format
     1999msgid "Low contrast (%s:1). Some visitors may find messages hard to read."
     2000msgstr ""
     2001
     2002#. translators: %d: number of settings that need correcting.
     2003#: assets/js/admin/error-summary.js:47
     2004#, js-format
     2005msgid "Please correct %d setting before saving:"
     2006msgid_plural "Please correct %d settings before saving:"
     2007msgstr[0] ""
     2008msgstr[1] ""
     2009
     2010#. translators: %s: the setting name and its problem.
     2011#: assets/js/admin/error-summary.js:68
     2012#, js-format
     2013msgid "Go to %s"
     2014msgstr ""
     2015
     2016#: assets/js/admin/kb-index.js:198
     2017msgid "Your session has expired. Reload the page to continue."
     2018msgstr ""
     2019
     2020#: assets/js/admin/kb-index.js:267
     2021msgid "Save your changes first"
     2022msgstr ""
     2023
     2024#: assets/js/admin/kb-index.js:271
     2025msgid "The Knowledge Base is off. Turn it on and save to sync."
     2026msgstr ""
     2027
     2028#: assets/js/admin/kb-index.js:310
     2029msgid "Sync could not be started. Try again."
     2030msgstr ""
     2031
     2032#: assets/js/admin/kb-index.js:367
     2033msgid "Storage could not be tested. Try again."
     2034msgstr ""
     2035
     2036#. translators: %s: number of items in the list.
     2037#: assets/js/admin/kb-index.js:438
     2038#, js-format
     2039msgid "%s item"
     2040msgid_plural "%s items"
     2041msgstr[0] ""
     2042msgstr[1] ""
     2043
     2044#. translators: %s: title of the item.
     2045#: assets/js/admin/kb-index.js:530
     2046#, js-format
     2047msgid "%s included"
     2048msgstr ""
     2049
     2050#. translators: %s: title of the item.
     2051#: assets/js/admin/kb-index.js:535
     2052#, js-format
     2053msgid "%s excluded"
     2054msgstr ""
     2055
     2056#: assets/js/admin/kb-index.js:550
     2057msgid "The change could not be saved. Try again."
     2058msgstr ""
     2059
     2060#. translators: %s: title of the item.
     2061#: assets/js/admin/kb-index.js:577
     2062#, js-format
     2063msgid "Include %s"
     2064msgstr ""
     2065
     2066#. translators: 1: current page, 2: number of pages.
     2067#: assets/js/admin/kb-index.js:650
     2068#, js-format
     2069msgid "Page %1$s of %2$s"
     2070msgstr ""
     2071
     2072#: assets/js/admin/kb-index.js:715
     2073msgid "The list could not be loaded. Try again."
     2074msgstr ""
     2075
     2076#. translators: 1: number of items done, 2: number of items in all.
     2077#: assets/js/admin/kb-status.js:176
     2078#, js-format
     2079msgid "Syncing… %1$s of %2$s item"
     2080msgid_plural "Syncing… %1$s of %2$s items"
     2081msgstr[0] ""
     2082msgstr[1] ""
     2083
     2084#. translators: %s: number of items that could not be indexed.
     2085#: assets/js/admin/kb-status.js:196
     2086#, js-format
     2087msgid "%s item could not be indexed."
     2088msgid_plural "%s items could not be indexed."
     2089msgstr[0] ""
     2090msgstr[1] ""
     2091
     2092#: assets/js/admin/kb-status.js:240
     2093msgid "Indexing paused."
     2094msgstr ""
     2095
     2096#: assets/js/admin/kb-status.js:242
     2097msgid "Indexing finished."
     2098msgstr ""
     2099
     2100#: assets/js/admin/status-report.js:26
     2101msgid "Could not copy the status report. Select the text and copy it manually."
     2102msgstr ""
     2103
     2104#: assets/js/admin/status-report.js:56
     2105msgid "Status report copied."
     2106msgstr ""
     2107
     2108#. translators: 1: the first line numbers, 2: the last line number, as in "1, 2 and 3".
     2109#: assets/js/admin/validation.js:32
     2110#, js-format
     2111msgid "%1$s and %2$s"
     2112msgstr ""
     2113
     2114#. translators: %s: line number.
     2115#: assets/js/admin/validation.js:54
     2116#, js-format
     2117msgid "Line %s is not a valid IP address or range."
     2118msgstr ""
     2119
     2120#. translators: %s: line numbers such as "1, 2 and 3".
     2121#: assets/js/admin/validation.js:62
     2122#, js-format
     2123msgid "Lines %s are not valid IP addresses or ranges."
     2124msgstr ""
     2125
     2126#. translators: %d: highest number of lines.
     2127#: assets/js/admin/validation.js:80
     2128#, js-format
     2129msgid "Use at most %d lines."
     2130msgstr ""
     2131
     2132#: assets/js/admin/validation.js:90
     2133msgid "Fill in this field."
     2134msgstr ""
     2135
     2136#: assets/js/admin/validation.js:94
     2137msgid "Enter a hex colour such as #0f172a."
     2138msgstr ""
     2139
     2140#: assets/js/admin/validation.js:95
     2141#: assets/js/admin/validation.js:118
     2142msgid "This value is not valid."
     2143msgstr ""
     2144
     2145#: assets/js/admin/validation.js:98
     2146msgid "Enter a number."
     2147msgstr ""
     2148
     2149#. translators: 1: lowest value, 2: highest value.
     2150#: assets/js/admin/validation.js:103
     2151#, js-format
     2152msgid "Enter a number between %1$s and %2$s."
     2153msgstr ""
     2154
     2155#: assets/js/admin/validation.js:110
     2156msgid "Enter a whole number."
     2157msgstr ""
     2158
     2159#. translators: %s: allowed step between values.
     2160#: assets/js/admin/validation.js:113
     2161#, js-format
     2162msgid "Enter a value in steps of %s."
     2163msgstr ""
  • chathearth/tags/2.0.0/languages/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/tags/2.0.0/readme.txt

    r3673790 r3833468  
    11=== ChatHearth - AI Chatbot ===
    22Contributors: palwp, momadhoun
    3 Tags: chatbot, ai, openai, connectors, customer-support
     3Tags: chatbot, ai, openai, assistant, chat
    44Requires at least: 7.0
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.4.9
    8 License: GPLv2 or later
     7Stable tag: 2.0.0
     8License: GPL-2.0-or-later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Site-wide AI chatbot powered by WordPress Connectors. Version 1 uses OpenAI via the AI Provider for OpenAI plugin.
     11An AI chatbot for WordPress that answers from your own content and your shop, powered by the AI Provider for OpenAI plugin.
     12
    1213
    1314== Description ==
    1415
    15 ChatHearth - AI Chatbot adds a floating chat widget to your site. Visitors get a welcome message and starter phrases, then chat with an AI assistant configured through WordPress Connectors.
    16 
    17 Owned by [PalWP](https://palwp.com/). Support by [Mohammed Al-Madhoun](https://profiles.wordpress.org/momadhoun/) (`momadhoun`).
    18 
    19 **Version 1 highlights**
    20 
    21 * OpenAI via WordPress Connectors / AI Client (provider and chat model selectable in settings)
    22 * Settings page under Settings → ChatHearth - AI Chatbot (Welcome, Protection, Appearance, AI Settings, Knowledge Base)
    23 * Appearance controls (shape, colors, position, popup size)
    24 * Welcome message and clickable starter phrases
    25 * System prompt settings plus always-on website-only grounding
    26 * Knowledge Base (RAG): markdown from selected pages, posts, custom post types, products, and taxonomies; embeddings stored in the WordPress database; incremental updates
    27 * Product comparison in chat and add to WooCommerce cart from the widget
    28 * The chat icon is not shown on the site until an OpenAI API key is configured under Connectors
    29 * Answers questions about the page the visitor is currently viewing (public WordPress content for that URL)
    30 * Protection: kill switch, per-IP and site-wide (global) rate limits, escalation email/admin notice, optional auto-disable, max message length, content moderation (keyword list + optional OpenAI Moderations API), optional Google reCAPTCHA v3 overlay (once per hour after first success; enabled when both keys are set)
    31 * Conversation history in the browser (localStorage)
    32 * Non-streaming replies with a typing indicator and Markdown rendering
    33 
    34 Configure your OpenAI API key under **Connectors**. This plugin does not store the API key.
    35 
    36 **Planned: Evaluation and observability**
    37 
    38 Later releases are expected to add more CAPTCHA providers (Cloudflare Turnstile, hCaptcha), tokens and cost monitoring, hard cost ceilings with admin escalation, latency and reliability metrics, RAG quality evaluation, hallucination detection, explainability, transparency, and controllability. See the plugin `plan/` docs (especially `metrics-and-methods-for-quality.md` and `functionalities.md`) for details.
     16ChatHearth adds an AI chatbot to your WordPress site. Visitors ask a question in a chat window and get an answer from your own pages, posts and, with WooCommerce, your products, with links to the pages the answer comes from. It uses the AI connection that WordPress itself manages, through the **AI Provider for OpenAI** plugin, so your API key is never entered or stored in ChatHearth.
     17
     18**Requirements.** WordPress 7.0 or newer, PHP 7.4 or newer, and the **AI Provider for OpenAI** plugin with an OpenAI API key under Settings → Connectors. WordPress will not activate ChatHearth until that plugin is installed and active. WooCommerce is optional: the shop features only appear on a site that has it.
     19
     20**The chat widget.** A launcher in the corner of every public page, as an icon or as a pill with your own label, opens a chat panel. The panel shows your welcome message and suggestions, a "Tell me about this page" suggestion where the page is known, formatted answers (headings, lists, tables, code and safe links), the sources of an answer and product cards. It follows your appearance settings and keeps its look on any theme, works with the keyboard and screen readers, mirrors for right-to-left languages and fills the screen on phones. The launcher only appears when the chat is switched on and OpenAI is ready, and never in the admin area or on the login page.
     21
     22**Website grounding.** The assistant answers only about this website. With every message it is given a short summary of your public pages (and, with WooCommerce, your store and its product categories), so it can answer from your site and politely refuse unrelated questions. When a visitor asks about "this page" or "this product", it also reads the public content of the page they are on. A source, and for a product a product card, is shown only when the answer links to that page. Your own instructions in the AI Settings tab are added after these rules and cannot widen the scope. Drafts, private and password-protected content are never used.
     23
     24**Knowledge Base.** You choose which public content the assistant can learn from: content types (posts, pages, products and custom types), categories and tags, a summary of your site and, with WooCommerce, a summary of your store. The content is indexed in the background, in small steps, so even a site with thousands of posts never times out, and the Knowledge Base tab shows how far indexing has got. Later changes (new, edited, unpublished and deleted items, renamed categories, price and stock changes) update only what really changed, so nothing is paid for twice. Passages are stored once, in a compact form, in your WordPress database. Optional protected markdown copies of your content can be kept in your uploads folder. The index needs no extra server or account. Each question then finds the passages that match it best, in your language or another, and the answer lists the pages it links to under Sources. Questions that compare things use twice as many passages. The built-in store suits about 10,000 passages (roughly 2,500 pages); larger sites should use a persistent object cache or plug in another store through the `chathearth_vector_store` filter. A search never takes longer than about 2 seconds: it stops reading and uses the best passages found so far.
     25
     26**Shop.** With WooCommerce, the assistant shows products as cards: the products a visitor names, the product of the page they are on and the products it finds in your Knowledge Base. A card shows the picture, price and stock, a choice of option for a variable product and an Add to cart button that works for guests too, followed by View cart and Checkout links. Comparisons show exactly the products that were named and use their real price, stock, categories and attributes. Payment always happens at your store's own checkout. Nothing shop-related appears on a site without WooCommerce.
     27
     28**Protection and moderation.** Visitors and the whole site have rate limits, so a burst of messages cannot run up your bill. When the site-wide limits are hit repeatedly you get an alert, the chat can switch itself off, and a one-click link switches it back on. Content moderation refuses a message that holds a blocked word or phrase (whole words, in any language) or that OpenAI moderation flags, with a reply you wrote, before any answer is generated. Optional Google reCAPTCHA v3 asks a visitor to verify once before chatting.
     29
     30**Protection extras.** Logged-in users get their own message limits, counted per account instead of per network, and you can give a role a larger allowance (×1 to ×10). A list of blocked addresses and ranges, IPv4 and IPv6, refuses unwanted visitors before anything else happens. An invisible bot trap catches programs that fill in every form field. One button clears all rate-limit counters, for example after a false alarm. Your "limit reached" message can show the limit and the time window with `{limit}` and `{window}`. Behind a CDN or reverse proxy such as Cloudflare, turn on the trusted proxy and list its addresses, so limits and blocking use the real visitor address.
     31
     32The conversation is kept in the visitor's browser and removed after 24 hours without a new message, or sooner when the visitor clears the chat. The Knowledge Base setting is off by default. Nothing is sent to OpenAI or Google when a page loads: only a visitor's message, or the changes you make to the Knowledge Base, start a request (see External services).
     33
     34== Installation ==
     35
     361. Install and activate the **AI Provider for OpenAI** plugin first (Plugins → Add New). ChatHearth requires it, and WordPress will not activate ChatHearth without it.
     372. Add your OpenAI API key under **Settings → Connectors**. ChatHearth never sees or stores the key.
     383. Install ChatHearth: upload the `chathearth` folder to `/wp-content/plugins/`, or install it through Plugins → Add New, and activate it.
     394. Open **Settings → ChatHearth - AI Chatbot**. Check the Welcome and Appearance tabs, then **Switch the chat on** with "Enable chatbot" in the Protection tab and save. The chat icon appears on your public pages once the chat is on and OpenAI is ready.
     405. Optional: turn on the **Knowledge Base** tab to let the assistant learn from your content, enter both **reCAPTCHA** keys under Protection to verify visitors, and install **WooCommerce** to show product cards with Add to cart.
     41
     42== Frequently Asked Questions ==
     43
     44= Does this plugin store my OpenAI API key? =
     45
     46No. The key is managed by WordPress under Settings → Connectors (or by your server's environment), through the AI Provider for OpenAI plugin. ChatHearth never reads, stores or passes it on.
     47
     48= What does it cost to run? =
     49
     50ChatHearth itself is free. The replies, the optional moderation check and the optional Knowledge Base indexing are billed by OpenAI to your own account, by the amount of text sent. Rate limits for each visitor and for the whole site keep a burst of messages from running up the bill, and indexing only sends what changed (see "Does indexing cost anything?").
     51
     52= Why does WordPress refuse to activate ChatHearth? =
     53
     54ChatHearth requires the AI Provider for OpenAI plugin. Install and activate that plugin first, then activate ChatHearth.
     55
     56= Why don't I see the chat on my site? =
     57
     58The chat icon appears on your public pages only when the chat is switched on, OpenAI is ready (the plugin is active and an API key is saved under Settings → Connectors) and the page is not the admin area or the login page. The settings page shows whether the chat is live, off or not ready.
     59
     60= Where is the conversation kept? =
     61
     62In the visitor's browser only. It is kept in the visitor's browser and removed after 24 hours without a new message, or sooner when the visitor clears the chat. ChatHearth does not store conversations on your server.
     63
     64= Can customers buy from the chat? =
     65
     66Yes, when WooCommerce is active. The assistant shows product cards with a price, the stock and an Add to cart button, also to guests (visitors who are not signed in), and after an add the card offers View cart and Checkout. For a product with options such as a size, the visitor picks an option first; a product whose options cannot be chosen in a card gets a Choose options link to its page. The assistant never places an order: payment happens at your store's checkout. To keep the chat fair, one visitor network can add 30 products to the cart in 10 minutes.
     67
     68= Where are the settings? =
     69
     70Under Settings, ChatHearth - AI Chatbot, or through the Settings link on the Plugins screen. The page has six tabs: Welcome, Protection, Appearance, AI Settings, Knowledge Base and Advanced.
     71
     72= How does abuse and rate-limit protection work? =
     73
     74Under Protection you set message limits for each visitor network and for the whole site, separate limits for logged-in users, a list of blocked addresses, an invisible bot trap and an "Enable chatbot" switch. When the site-wide limits are hit repeatedly, ChatHearth emails you, shows an alert in the admin area and can switch the chat off by itself; a one-click link switches it back on. Optional content moderation checks each message against your blocked words and, if you choose, OpenAI moderation, before any answer is generated. Optional Google reCAPTCHA v3 asks a visitor to press Continue and verify once, and a short-lived cookie keeps the visitor from being asked again for an hour. The checks run in this order: kill switch, blocked addresses, bot trap, human verification, site-wide limits, visitor limits, moderation, then the AI.
     75
     76= Why do visitors behind a proxy share a limit? =
     77
     78Behind a content delivery network or proxy, all visitors share one limit until trusted proxies are set up. Behind a CDN or proxy such as Cloudflare, turn on "Use a trusted proxy" under Protection, Access rules, and list its addresses, so limits and blocking use the real visitor address.
     79
     80= Does the human verification overlay record consent? =
     81
     82The overlay explains the Google check before it starts. ChatHearth does not record consent through this overlay.
     83
     84= What happens if a visitor blocks cookies? =
     85
     86With human verification enabled, a browser that blocks cookies asks the visitor to verify before every message.
     87
     88= Is the Knowledge Base on? =
     89
     90No. The Knowledge Base is off by default. Turn it on in the Knowledge Base tab when you want answers to use content from your site. Indexing starts in the background when you save, and the Index section shows its progress.
     91
     92= Does indexing cost anything? =
     93
     94OpenAI charges for creating the embeddings. Only content that changed is embedded again: saving an item without changing it costs nothing. About US$0.10 indexes 5,000 average posts with the default model (the price at the time of writing).
     95
     96= Is there a limit to the size of the Knowledge Base? =
     97
     98The built-in store suits about 10,000 passages (roughly 2,500 pages). Above that, use a persistent object cache or a larger InnoDB buffer pool, or have a developer replace the store through the `chathearth_vector_store` filter. Every search stops reading after 2 seconds and uses the best passages found so far, so a very large index gives less complete answers instead of a slow chat.
     99
     100= How do I keep a page out of the assistant's answers? =
     101
     102Open the Knowledge Base tab, find the page in the Index list (search by title or address, or filter by type, status and Included), and turn off its Included switch. The assistant stops using the page at once, even for the very next question. Turn the switch on again to bring it back: the page is indexed again in the background.
     103
     104= Can I upgrade from ChatHearth 1.4.9 without indexing again? =
     105
     106Yes. Update the plugin as usual: your settings, Knowledge Base, alerts and visitors' saved chats are kept. An existing 1.4.9 index keeps working. It is converted to the smaller storage format in the background, without asking OpenAI again. Each old text copy of a vector is removed as soon as its converted copy is stored, so going back to 1.4.9 afterwards needs a new index there. If you use a page cache, clear it after the update.
     107
     108= How do I go back to 1.4.9? =
     109
     110Install the 1.4.9 package (`chathearth-1.4.9.zip`) over ChatHearth 2.0 on the Plugins screen, choosing to replace the current version, or run `wp plugin install chathearth-1.4.9.zip --force`. Nothing needs to be deleted first. 1.4.9 keeps your settings and the entries of your Knowledge Base, and it ignores the settings that only 2.0 has.
     111
     1121.4.9 cannot read the compact passage storage that 2.0 converted your index to, so it must index the Knowledge Base again. Mark every included entry for indexing with a database tool, using your own table prefix instead of `wp_`: `UPDATE wp_chathearth_kb_entries SET status = 'pending', error_message = NULL WHERE included = 1;` Then open the Knowledge Base tab and press Sync now. The cost is one embedding of your whole Knowledge Base, the same as the first indexing.
     113
     114The extra columns and options that 2.0 added stay in the database, unused by 1.4.9. Deleting the plugin removes them.
     115
     116== Screenshots ==
     117
     1181. Answers from your own website (what you sell, how to contact you, delivery), each with its source.
     1192. Helpful suggestions that link to the right categories and products, here for choosing a gift.
     1203. Product cards with price, stock and Add to cart, for guests too.
     1214. Ask about a product by name and get its price, stock and card.
     1225. Ask about the page you are on: the assistant answers from that product, with its options and Add to cart.
     1236. Product comparisons as a table, using only facts from your shop.
     1247. Store policies answered from your own pages, such as what to do when an item arrives broken.
     1258. Welcome settings: the greeting and the starter suggestions visitors can click.
     1269. Protection, Availability: switch the chat on or off for your whole site.
     12710. Protection, Message limits: the longest message and how much of the conversation is sent with each question.
     12811. Protection, Rate limits: questions per minute and per hour for each visitor and for the whole site, with extra allowance for logged-in roles.
     12912. Protection, Escalation: an e-mail and an admin notice when the site limit is hit again and again, and an optional automatic switch-off.
     13013. Protection, Access rules: blocked addresses, an invisible bot trap and support for proxies such as Cloudflare.
     13114. Protection, Human verification: optional Google reCAPTCHA v3 with no puzzles; a verified visitor chats for a set time before the next check.
     13215. Protection, Content moderation: OpenAI moderation and your own blocked words check each question before it reaches the AI.
     13316. Appearance: the launcher, the chat window and the product cards, with a live preview.
     13417. AI Settings: the model, your own instructions and the built-in website rules; the API key stays in WordPress Connectors.
     13518. Knowledge Base: what the assistant learns from, search tuning, and the index with its sync status.
     13619. Advanced: the system status report and what happens to your data when the plugin is deleted.
    39137
    40138== External services ==
    41139
    42 This plugin relies on the following third-party services to work. It does not send any data to these services until the site owner configures them and a visitor actively uses the chatbot. No visitor is tracked automatically, and the plugin adds no analytics, advertising, or usage-tracking calls of its own.
    43 
    44 = OpenAI (AI chat replies) =
    45 
    46 The chatbot generates replies using OpenAI's API, accessed through WordPress Connectors / the core AI Client and the required "AI Provider for OpenAI" plugin. This is the core service that produces the assistant's answers.
    47 
    48 * **What is sent:** the text of the message a visitor types, the recent conversation history from that visitor's browser session, the site's configured system prompt, the URL and WordPress id of the page they are viewing (so the assistant can load that page's public content from WordPress — not the raw HTML from the browser), and the selected model name.
    49 * **When it is sent:** only when a visitor actively submits a message in the chat widget. Nothing is sent on page load or in the background.
    50 * **Where the API key lives:** the OpenAI API key is configured under WordPress Connectors (or the `OPENAI_API_KEY` environment variable / constant). This plugin does not store the API key and does not store chat transcripts in the WordPress database.
    51 
    52 OpenAI Terms of Use: https://openai.com/policies/terms-of-use/
    53 OpenAI Privacy Policy: https://openai.com/policies/privacy-policy/
    54 OpenAI API data usage policy: https://openai.com/policies/usage-policies/
    55 
    56 = OpenAI Moderations API (content moderation) =
    57 
    58 When content moderation is enabled under Settings → ChatHearth - AI Chatbot → Protection and the OpenAI Moderations layer is on, visitor message text is checked with OpenAI’s Moderations endpoint before a chat reply is generated. This helps block harmful or disallowed content and ToS-violating usage.
    59 
    60 * **What is sent:** the text of the current message and prior user turns from that visitor’s browser session (truncated to a safe length). No system prompt is sent to Moderations.
    61 * **When it is sent:** only when a visitor submits a message, content moderation is enabled, the OpenAI Moderations option is on, and OpenAI is configured under Connectors. If moderation is off or only the keyword list is used, this endpoint is not called.
    62 * **Where the API key lives:** the same OpenAI API key from WordPress Connectors (or `OPENAI_API_KEY`). This plugin does not store a separate moderation key.
    63 * **Endpoint used:** `https://api.openai.com/v1/moderations`
    64 
    65 OpenAI Terms of Use: https://openai.com/policies/terms-of-use/
    66 OpenAI Privacy Policy: https://openai.com/policies/privacy-policy/
    67 OpenAI API data usage policy: https://openai.com/policies/usage-policies/
    68 
    69 = OpenAI Embeddings API (knowledge base) =
    70 
    71 When the Knowledge Base (RAG) is enabled, ChatHearth creates embeddings for selected site content and for visitor questions so matching passages can be retrieved. This uses the same OpenAI API key from Connectors.
    72 
    73 * **What is sent:** markdown generated from selected pages, posts, products, taxonomies, and site/store summaries (at index time), and the visitor’s current question (at chat time).
    74 * **When it is sent:** only when RAG is enabled and the site owner runs a sync / content changes, or a visitor sends a chat message while RAG is on.
    75 * **Endpoint used:** `https://api.openai.com/v1/embeddings`
    76 
    77 Embeddings and generated markdown stay on this WordPress site (custom tables and `uploads/chathearth/kb/`). The plugin does not contact Chroma, Pinecone, or any other vector-database service.
    78 
    79 = Google reCAPTCHA v3 (optional bot/abuse protection) =
    80 
    81 Google reCAPTCHA v3 is an optional, score-based human-verification service used only to protect the chat endpoint from automated abuse. It is **disabled by default** and only becomes active when the site owner provides both a reCAPTCHA site key and secret key (under Settings → ChatHearth - AI Chatbot → Protection, or via the `CHATHEARTH_RECAPTCHA_SITE_KEY` and `CHATHEARTH_RECAPTCHA_SECRET_KEY` environment variables).
    82 
    83 * **What is sent:** when enabled, the reCAPTCHA JavaScript is loaded from Google on front-end pages where the chat widget appears, and Google may collect device, browser, and usage data (including the visitor's IP address) to assess whether the visitor is human. When the chat opens, a verification token and the visitor's IP address are sent to Google's verification endpoint. A white, translucent, blurred overlay covers the chat window until verification succeeds.
    84 * **When it is sent:** only when the site owner has enabled reCAPTCHA (both keys set). If reCAPTCHA is not configured, no request is ever made to Google and Google's script is not loaded.
    85 * **Endpoints used:** `https://www.google.com/recaptcha/api.js` (script) and `https://www.google.com/recaptcha/api/siteverify` (server-side verification).
    86 
    87 Google Terms of Service: https://policies.google.com/terms
    88 Google Privacy Policy: https://policies.google.com/privacy
    89 
    90 = Privacy and consent =
    91 
    92 This plugin does not track users and does not contact any external server without consent:
    93 
    94 * **OpenAI** is only reached after the site owner installs the required provider plugin and configures an API key under Connectors. By installing, configuring, and activating that service, the site owner grants consent for chat messages to be sent to OpenAI (the Software as a Service exception). Data is sent only when a visitor actively submits a message. When content moderation with OpenAI Moderations is enabled, message text may also be sent to OpenAI’s Moderations endpoint before a reply is generated.
    95 * **Google reCAPTCHA** is opt-in and off by default. It loads and contacts Google only after the site owner enters both reCAPTCHA keys. With no keys set, Google is never contacted.
    96 * **No silent tracking:** the plugin includes no analytics, advertising, fingerprinting, or usage-tracking calls. The visitor's IP address is used locally for rate limiting and abuse protection only (short-lived counters), and is not sold, shared, or logged as a chat transcript.
    97 
    98 Site owners should review the privacy policies of any service they enable and update their own site's privacy policy accordingly. Suggested privacy-policy text is provided under Settings → Privacy.
    99 
    100 == Installation ==
    101 
    102 1. Install and activate the **AI Provider for OpenAI** plugin.
    103 2. Add your OpenAI API key under WordPress **Connectors**.
    104 3. Upload the `chathearth` folder to `/wp-content/plugins/`, or install the zip.
    105 4. Activate **ChatHearth - AI Chatbot**.
    106 5. Open **Settings → ChatHearth - AI Chatbot** and save your settings.
    107 
    108 == Frequently Asked Questions ==
    109 
    110 = Does this plugin store my OpenAI API key? =
    111 
    112 No. Use WordPress Connectors (or the OPENAI_API_KEY environment variable / constant).
    113 
    114 = Why don't replies stream token by token? =
    115 
    116 WordPress AI Client / Connectors do not expose streaming yet. v1 shows a typing indicator, then the full reply. Streaming is planned for a later release.
    117 
    118 = Where is chat history stored? =
    119 
    120 In the visitor's browser via localStorage. Server-side history is planned for a future release.
    121 
    122 = How does abuse / rate-limit protection work? =
    123 
    124 Under Settings → ChatHearth - AI Chatbot → Protection you can set per-IP limits, site-wide (global) limits, an escalation threshold, and optional auto-disable. Optionally add Google reCAPTCHA v3 site and secret keys — CAPTCHA turns on automatically when both are set (green status in settings). Visitors then see a white blurred overlay on the chat window until Google verifies them. Content moderation can check messages with a keyword list and/or OpenAI’s Moderations API before they reach the chat model. Chat requests are checked in order: kill switch, reCAPTCHA (if enabled), then global limits, then per-IP limits, then content moderation (if enabled), then the AI call. When global limits are hit repeatedly within an hour, the plugin emails the admin, shows an admin notice, and can turn the chatbot off automatically.
    125 
    126 = Will there be usage, cost, or quality monitoring? =
    127 
    128 Yes — planned under Evaluation and observability (tokens/cost, latency, groundedness, hallucination checks, admin dashboards). Request-count protection, admin escalation, and optional reCAPTCHA v3 ship now; hard dollar/token ceilings and additional CAPTCHA providers (Turnstile, hCaptcha) are still planned.
    129 
    130 == Screenshots ==
    131 
    132 1. Floating chat widget on the front end with welcome message and starter phrases.
    133 2. Settings → ChatHearth - AI Chatbot — Welcome tab (greeting and starter phrases).
    134 3. Settings → ChatHearth - AI Chatbot — Protection tab (rate limits, content moderation, and optional reCAPTCHA).
    135 4. Settings → ChatHearth - AI Chatbot — Appearance tab (colors, shape, position, and size).
    136 5. Settings → ChatHearth - AI Chatbot — AI Settings tab (provider, model, and system prompt).
    137 6. Settings → ChatHearth - AI Chatbot — Knowledge Base tab (RAG sources, sync).
     140ChatHearth sends text to OpenAI so that it can write a reply, check a message and search your content, and, when you turn it on, asks Google to check that a visitor is human. Nothing is sent when a page loads: only a visitor's message, a visitor pressing Continue, or the changes you make to the Knowledge Base start a request, and nothing is sent while the chat is switched off. ChatHearth never reads, stores or passes on your OpenAI API key.
     141
     142**OpenAI chat replies, through the AI Provider for OpenAI plugin**
     143
     144* **What is sent:** the visitor's message, the recent part of the conversation (up to the number of messages you allow in the settings) and the instructions you wrote in the AI Settings tab.
     145* **Website grounding:** with each message, ChatHearth also sends a summary of your public pages (their titles and addresses, up to 40) and, with WooCommerce, your store and up to 50 product categories, and the public content of the page the visitor is on. Drafts, private and password-protected content is never sent, and content is read as a guest sees it. The summary is kept on your server for up to 12 hours.
     146* **Shop facts:** when WooCommerce is active, the facts of the products named in a message or found in your Knowledge Base (name, price, stock, categories, attributes and short description) go with the message.
     147* **When:** only when a visitor sends a message. Nothing is sent when a page loads, and nothing is sent while the chat is switched off.
     148* **Where:** `https://api.openai.com/v1/`, through WordPress's own AI Client and the AI Provider for OpenAI plugin, which makes the request with your key and has its own disclosure: [AI Provider for OpenAI](https://wordpress.org/plugins/ai-provider-for-openai/).
     149* **Not stored:** ChatHearth does not store messages, conversations or replies.
     150* **OpenAI's terms and privacy policy:** [Terms of use](https://openai.com/policies/terms-of-use/) and [Privacy policy](https://openai.com/policies/privacy-policy/).
     151
     152**Knowledge Base indexing and search**
     153
     154* **What is sent:** The public content selected in the Knowledge Base settings is sent to the OpenAI embeddings service when it is indexed and when it changes, only while the Knowledge Base is on and OpenAI is connected. Each item is sent as readable text (its title, address, text, categories and, for a product, its price, stock and attributes), in batches. Drafts, private and password-protected content, comments and author e-mail addresses are never sent.
     155* **Where:** `https://api.openai.com/v1/embeddings`. WordPress's AI Client has no embeddings request, so ChatHearth sends this request to OpenAI's address itself, signed by the AI Client's own OpenAI connection (the AI Provider for OpenAI plugin). ChatHearth never reads, stores or passes on your API key, and no setting or filter changes the address. Plugin Check lists this as a direct integration.
     156* **Visitor questions:** While the Knowledge Base is on and OpenAI is connected, each visitor question is sent to the OpenAI embeddings service to find matching passages. ChatHearth does not store the question for this. It is sent once for each message that passed the protection checks, and not for a message that was refused.
     157* **When:** the content is sent in the background after you turn the Knowledge Base on, change its sources or the passage size, or change an item. A question is sent when a visitor sends a message. Nothing is sent while the Knowledge Base is off.
     158* **Stored:** the vectors and the readable text of your own public content stay in your WordPress database. The index holds no visitor or account data.
     159* **OpenAI's terms and privacy policy:** [Terms of use](https://openai.com/policies/terms-of-use/) and [Privacy policy](https://openai.com/policies/privacy-policy/).
     160
     161**OpenAI moderation**
     162
     163* **What is sent:** the new message and up to two earlier visitor messages of the same chat, never the assistant's replies. Only texts that were not checked in the last 24 hours are sent.
     164* **Where:** `https://api.openai.com/v1/moderations`. WordPress's AI Client has no moderation request, so ChatHearth sends this request to OpenAI's address itself, signed by the AI Client's own OpenAI connection. ChatHearth never reads, stores or passes on your API key. Plugin Check lists this as a direct integration.
     165* **When:** only when a visitor sends a message and both "Check messages before they reach the AI" and "Use OpenAI moderation" are on. If OpenAI does not answer in the time you choose, the message is sent without the check.
     166* **Remembered:** the result of a check is remembered for 24 hours under a salted hash. The text itself is never stored.
     167* **OpenAI's terms and privacy policy:** [Terms of use](https://openai.com/policies/terms-of-use/) and [Privacy policy](https://openai.com/policies/privacy-policy/).
     168
     169**Google reCAPTCHA v3**
     170
     171* **When Google is contacted.** The owner must configure both reCAPTCHA keys. The browser loads Google's script only after the visitor presses Continue. Your server contacts Google when verifying the resulting token.
     172* **Where:** `https://www.google.com/recaptcha/api.js` (the script, loaded by the visitor's browser) and `https://www.google.com/recaptcha/api/siteverify` (the check, made by your server).
     173* **What is sent.** Google's script sends its own technical data from the browser. Your server sends the verification token and the visitor's IP address to Google.
     174* **Cookie.** After a successful check ChatHearth sets a cookie called `chathearth_human` (HTTP-only) that lasts at most 60 minutes and is used only to skip repeated checks.
     175* [Google Terms of Service](https://policies.google.com/terms) and [Google Privacy Policy](https://policies.google.com/privacy).
     176
     177== Source code and build ==
     178
     179The scripts of the settings page are written as small readable modules in `assets/js/admin/`, and the script of the chat widget as modules in `assets/js/frontend/` and `assets/js/shared/`; all of them are included in this plugin. The files in `assets/js/build/` (`assets/js/build/index.js` for the settings page and `assets/js/build/widget.js` for the chat widget) are generated from them with the `@wordpress/scripts` package. The styles in `assets/css/admin.css` and `assets/css/widget.css` are written by hand and are not generated.
     180
     181To rebuild the scripts, open a terminal in the plugin folder and run:
     182
     1831. `npm install`
     1842. `npm run build`
     185
     186
     187== Credits ==
     188
     189The icons on the settings page are original line drawings created for ChatHearth. They are released under the GPL-2.0-or-later licence, like the rest of the plugin.
    138190
    139191== Changelog ==
     192
     193= 2.0.0 =
     194ChatHearth 2, a complete rewrite of 1.4.9. What changed since 1.4.9:
     195
     196**Chat**
     197* A new chat window: a launcher (icon or pill) on public pages opens a panel with your welcome message and suggestions, formatted answers, sources and product cards. It follows your appearance settings on any theme, works with the keyboard and screen readers, mirrors for right-to-left languages, fills the screen on phones and respects "reduce motion".
     198* The conversation is kept in the visitor's browser and removed after 24 hours without a new message. Answers are shown safely: nothing in an answer can add markup or run a script, and links are limited to web addresses.
     199* A temporary provider failure is retried once, and visitors only ever see a generic message. The 1.4.9 developer hooks work again, and a translation template (`languages/chathearth.pot`) ships with the plugin.
     200
     201**Website grounding**
     202* The assistant answers only about your website and politely refuses other topics. Every message carries a short summary of your public pages and, with WooCommerce, your store and its categories.
     203* "This page" and "this product" work: the public content of the page the visitor is on is added to the message. Sources, and for a product a product card, appear under an answer that links to that page.
     204* Your site's instructions in the AI Settings tab are added after the rules of the website and cannot widen the scope. Drafts, private and password-protected content is never used.
     205
     206**Knowledge Base**
     207* Your chosen public content is turned into readable documents and indexed in the background, in small steps, so large sites never time out. The Knowledge Base tab shows the progress, and indexing waits on its own while OpenAI is not ready.
     208* Later changes update only what changed: publishing, editing, unpublishing, deleting, renamed categories, price and stock changes. Saving an item without a change costs nothing. Changing the passage size or the embedding model re-indexes in the background.
     209* Every question that passes the protection checks is matched against your indexed passages, and the best passages are given to the assistant. Answers list their sources. Comparison questions use twice as many passages, in English and Arabic, and developers can add words with the `chathearth_comparison_words` filter.
     210* Searching stays light as the site grows: about 6 MB of memory at 10,000 passages and no more beyond, and an optional object cache keeps the searched data. The built-in vector store suits about 10,000 passages (roughly 2,500 pages) and every search stops after 2 seconds; the `chathearth_vector_store` filter works for larger sites.
     211* The Index card works: counts of indexed, pending, excluded and failed items, the time of the last sync, a Sync now button with a progress bar, a list of items you can search, filter by type, status and Included, and switch on or off, and a Failed alert that shows the reason for each item. Test storage checks that the index storage is ready.
     212* Optional protected markdown copies of your content are kept in the uploads folder and removed when you turn the setting off. An index from ChatHearth 1.4.9 keeps working and is converted to the new format in the background, without new OpenAI requests.
     213
     214**Protection**
     215* Per-visitor-network and site-wide rate limits; sustained abuse raises an alert by e-mail and in the admin area, and the chat can switch itself off with a one-click recovery link.
     216* Logged-in users are counted per account, with an optional larger allowance for each role (×1 to ×10). A list of blocked addresses and ranges (IPv4 and IPv6) refuses a visitor before anything else happens. An invisible bot trap refuses requests that fill in a hidden field. "Clear rate-limit counters" starts every count from zero, and the limit message can show `{limit}` and `{window}`.
     217* Behind a CDN or proxy such as Cloudflare, turn on "Use a trusted proxy" and list its addresses, so limits and blocking use the real visitor address.
     218* Optional Google reCAPTCHA v3 verification loads when the visitor selects Continue. A short-lived cookie lets verified visitors keep chatting on the same network.
     219
     220**Moderation**
     221* Messages that contain a blocked word or phrase, or that OpenAI moderation flags, are refused with your reply before any answer is generated. Blocked phrases now match whole words only, in any language, so "ass" no longer blocks "class". A 1.4.9 list that relied on matches inside words may block less.
     222* OpenAI moderation checks the new message and up to two earlier visitor messages, remembers results for 24 hours, and lets the message through when OpenAI is unavailable. "Moderation time limit" controls how long to wait.
     223
     224**Shop**
     225* With WooCommerce, the products a visitor names, the product of the page they are on and the products found in your Knowledge Base appear as cards with price, stock and, for a variable product, a choice of option. Cards are styled by the eight product card settings.
     226* Add to cart works from the chat, for guests too, with "Added to cart." and View cart and Checkout links. One visitor network can add 30 products in 10 minutes.
     227* Comparisons: when a visitor names two or more products and asks to compare them, the answer and the cards cover exactly those products, with their real price, stock, categories, attributes and short description.
     228* Product names are found through a cached index that is built in the background and kept current, so a shop of 50,000 products stays fast. Compatible with WooCommerce's custom order tables and the cart and checkout blocks. Without WooCommerce nothing of this appears.
     229
     230**Settings**
     231* A settings page under Settings, ChatHearth - AI Chatbot, with six tabs and a Settings link on the Plugins screen; a live preview of the chat window while you change colours, sizes and text, with a warning when text would be hard to read; unsaved changes are marked, and mistakes are explained with links to each field.
     232* The page shows whether the chat is live, off or not ready and a System status list with a report you can copy. Suggested privacy-policy text covers every way ChatHearth handles visitor data. The reCAPTCHA secret key is never shown after it is saved. Deleting the plugin removes all of its data, unless "Keep data on uninstall" is on.
     233
     234**Update from 1.4.9**
     235* Updating from 1.4.9 is checked end to end: a populated 1.4.9 site is updated and compared before and after. Your settings, Knowledge Base entries and passages, an abuse alert and visitors' saved chats are all kept, and nothing is embedded again. The unused Chroma and Pinecone settings are removed.
     236* A CAPTCHA pass earned in 1.4.9 keeps working until it expires, up to one hour after the update, and is never renewed. A pass earned after the update belongs to the visitor's network.
     237* The `chatHearth` script data prints the 1.4.9 keys that the 2.0 widget does not read again, for themes and plugins that read them. How to go back to 1.4.9 is explained in the FAQ.
    140238
    141239= 1.4.9 =
    … …  
    205303== Upgrade Notice ==
    206304
     305= 2.0.0 =
     306No action is needed after updating: your settings, Knowledge Base, alerts and visitors' saved chats are kept and nothing is embedded again. If you use a page cache, clear it after the update.
     307
    207308= 1.4.9 =
    208309Fixes chat button styling on themes such as WoodMart, and the Knowledge Base entries list on plain permalinks.
  • chathearth/tags/2.0.0/uninstall.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Uninstall cleanup.
     3 * Runs when the plugin is deleted from the Plugins screen.
     4 *
     5 * Removes the plugin's data on every site unless "Keep data on uninstall" is on (see Lifecycle\Uninstaller).
    46 *
    57 * @package ChatHearth
    68 */
    7 
    8 declare(strict_types=1);
    99
    1010if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    … …  
    1212}
    1313
    14 delete_option( 'chathearth_settings' );
    15 delete_option( 'chathearth_abuse_alert' );
     14if ( ! defined( 'ABSPATH' ) ) {
     15        exit;
     16}
    1617
     18// The plugin itself is not loaded during an uninstall, so the autoloader is registered here.
    1719if ( ! defined( 'CHATHEARTH_PATH' ) ) {
    1820        define( 'CHATHEARTH_PATH', plugin_dir_path( __FILE__ ) );
     21}
     22
     23// Up to here the file only uses syntax PHP 5.6 can parse. On an unsupported site the cleanup code cannot
     24// run, so the data is left in place rather than ending the uninstall with a fatal error.
     25require_once CHATHEARTH_PATH . 'includes/class-requirements.php';
     26if ( ! ChatHearth\Requirements::met( isset( $GLOBALS['wp_version'] ) ? $GLOBALS['wp_version'] : '0', PHP_VERSION ) ) {
     27        return;
    1928}
    2029
    … …  
    2231ChatHearth\Autoloader::register();
    2332
    24 ChatHearth\Rag\Schema::uninstall();
     33ChatHearth\Lifecycle\Uninstaller::run();
  • chathearth/trunk/assets/css/admin.css

    r3663506 r3833468  
    1 .chathearth-settings .form-table th {
    2         width: 220px;
     1/*
     2 * ChatHearth settings page styles.
     3 *
     4 * One hand-written stylesheet, scoped under .chathearth-settings, with logical
     5 * properties only so that right-to-left pages mirror without extra rules.
     6 * The accent follows the WordPress admin colour scheme.
     7 *
     8 * Contents:
     9 *   1. Tokens and base
     10 *   2. Header and notices
     11 *   3. Layout and tab navigation
     12 *   4. Cards and fields
     13 *   5. Controls (toggle, segmented, number, colour, secret, checkgrid)
     14 *   6. Small components (pill, badge, callout, stats, progress, toast, ...)
     15 *   7. Protection sub-tabs and rate-limit groups
     16 *   8. Appearance: live preview, launcher, product cards
     17 *   9. Knowledge Base index
     18 *  10. Advanced: system status
     19 */
     20
     21/* 1. Tokens and base
     22   ========================================================================== */
     23
     24.chathearth-settings {
     25        --chathearth-accent: var(--wp-admin-theme-color, #2271b1);
     26        --chathearth-accent-strong: var(--wp-admin-theme-color-darker-10, #135e96);
     27        --chathearth-text: #1d2327;
     28        --chathearth-text-muted: #50575e;
     29        --chathearth-border: #dcdcde;
     30        --chathearth-control-border: #8c8f94;
     31        --chathearth-surface: #fff;
     32        --chathearth-surface-alt: #f6f7f7;
     33        --chathearth-page: #f0f0f1;
     34
     35        --chathearth-success: #00a32a;
     36        --chathearth-success-bg: #edfaef;
     37        --chathearth-success-text: #0a6b20;
     38        --chathearth-warning: #996800;
     39        --chathearth-warning-bg: #fcf9e8;
     40        --chathearth-warning-text: #7a5200;
     41        --chathearth-error: #d63638;
     42        --chathearth-error-bg: #fcf0f1;
     43        --chathearth-error-text: #b32d2e;
     44        --chathearth-info: #72aee6;
     45        --chathearth-info-bg: #f0f6fc;
     46
     47        --chathearth-radius-card: 8px;
     48        --chathearth-radius-control: 4px;
     49        --chathearth-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
     50
     51        --chathearth-space-1: 4px;
     52        --chathearth-space-2: 8px;
     53        --chathearth-space-3: 12px;
     54        --chathearth-space-4: 16px;
     55        --chathearth-space-5: 24px;
     56        --chathearth-space-6: 32px;
     57        --chathearth-space-7: 48px;
     58
     59        --chathearth-motion: 150ms ease-out;
     60        --chathearth-label-width: 220px;
     61        --chathearth-sticky-top: calc(var(--wp-admin--admin-bar--height, 32px) + 16px);
     62
     63        color: var(--chathearth-text);
     64        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
     65        font-size: 13px;
     66        line-height: 1.5;
     67        min-inline-size: 0;
     68}
     69
     70.chathearth-settings *,
     71.chathearth-settings *::before,
     72.chathearth-settings *::after {
     73        box-sizing: border-box;
     74}
     75
     76.chathearth-settings [hidden] {
     77        display: none !important;
     78}
     79
     80.chathearth-icon {
     81        display: inline-block;
     82        inline-size: 18px;
     83        block-size: 18px;
     84        flex: none;
     85        fill: none;
     86        stroke: currentcolor;
     87        stroke-width: 1.8;
     88        stroke-linecap: round;
     89        stroke-linejoin: round;
     90        vertical-align: middle;
     91}
     92
     93/* Accessible focus ring for all interactive elements */
     94.chathearth-settings :focus-visible {
     95        outline: 2px solid transparent;
     96        box-shadow: 0 0 0 2px var(--chathearth-surface), 0 0 0 4px var(--chathearth-accent) !important;
     97}
     98
     99/* 2. Header and notices
     100   ========================================================================== */
     101
     102.chathearth-settings .chathearth-header {
     103        display: flex;
     104        flex-wrap: wrap;
     105        align-items: center;
     106        justify-content: space-between;
     107        gap: var(--chathearth-space-4);
     108        padding-block: var(--chathearth-space-5) var(--chathearth-space-4);
     109}
     110
     111.chathearth-settings .chathearth-header__brand {
     112        display: flex;
     113        align-items: center;
     114        gap: var(--chathearth-space-3);
     115        min-inline-size: 0;
     116}
     117
     118.chathearth-settings .chathearth-logo {
     119        display: grid;
     120        place-items: center;
     121        inline-size: 40px;
     122        block-size: 40px;
     123        border-radius: var(--chathearth-radius-card);
     124        background: var(--chathearth-accent);
     125        color: #fff;
     126}
     127
     128.chathearth-settings .chathearth-logo .chathearth-icon {
     129        inline-size: 24px;
     130        block-size: 24px;
     131}
     132
     133.chathearth-settings .chathearth-header__title {
     134        margin: 0;
     135        color: var(--chathearth-text);
     136        font-size: 23px;
     137        font-weight: 400;
     138        line-height: 1.2;
     139}
     140
     141.chathearth-settings .chathearth-header__title span {
     142        color: var(--chathearth-text-muted);
     143        font-size: 15px;
     144        font-weight: 400;
     145}
     146
     147.chathearth-settings .chathearth-header__tagline {
     148        margin: 2px 0 0;
     149        color: var(--chathearth-text-muted);
     150        font-size: 12px;
     151}
     152
     153.chathearth-settings .chathearth-header__actions {
     154        display: flex;
     155        align-items: center;
     156        gap: var(--chathearth-space-3);
     157}
     158
     159.chathearth-settings .chathearth-header__actions a {
     160        display: inline-flex;
     161        align-items: center;
     162        color: var(--chathearth-text-muted);
     163        font-size: 12px;
     164        text-decoration: none;
     165}
     166
     167.chathearth-settings .chathearth-header__actions a:hover {
     168        color: var(--chathearth-accent);
     169        text-decoration: underline;
     170}
     171
     172.chathearth-settings .chathearth-notices {
     173        margin-block-end: var(--chathearth-space-4);
     174}
     175
     176.chathearth-settings .chathearth-notices .notice {
     177        margin-block: 0 var(--chathearth-space-3);
     178}
     179
     180/* 3. Layout and tab navigation
     181   ========================================================================== */
     182
     183.chathearth-settings .chathearth-layout {
     184        display: grid;
     185        grid-template-columns: minmax(180px, 200px) minmax(0, 1fr);
     186        gap: var(--chathearth-space-5);
     187        align-items: start;
    3188}
    4189
    5190.chathearth-settings .chathearth-tabs {
    6         margin: 16px 0 0;
    7 }
    8 
    9 .chathearth-settings .chathearth-tab-panel {
    10         margin-top: 8px;
     191        position: sticky;
     192        inset-block-start: var(--chathearth-sticky-top);
     193        z-index: 10;
     194}
     195
     196.chathearth-settings .chathearth-tabs [role="tablist"] {
     197        display: flex;
     198        flex-direction: column;
     199        gap: 2px;
     200}
     201
     202.chathearth-settings .chathearth-tabs__tab {
     203        display: flex;
     204        align-items: center;
     205        gap: var(--chathearth-space-3);
     206        padding-block: 10px;
     207        padding-inline: 14px;
     208        border-radius: var(--chathearth-radius-control);
     209        color: var(--chathearth-text);
     210        font-size: 13px;
     211        font-weight: 500;
     212        text-decoration: none;
     213        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     214        cursor: pointer;
     215        user-select: none;
     216}
     217
     218.chathearth-settings .chathearth-tabs__tab:hover {
     219        background: var(--chathearth-surface);
     220        color: var(--chathearth-accent);
     221}
     222
     223.chathearth-settings .chathearth-tabs__tab.is-active {
     224        background: var(--chathearth-accent);
     225        color: #fff;
     226        font-weight: 600;
     227}
     228
     229.chathearth-settings .chathearth-tabs__tab .chathearth-icon {
     230        inline-size: 18px;
     231        block-size: 18px;
     232}
     233
     234.chathearth-settings .chathearth-tabs__dirty {
     235        display: inline-block;
     236        inline-size: 7px;
     237        block-size: 7px;
     238        margin-inline-start: auto;
     239        border-radius: 50%;
     240        background: var(--chathearth-warning);
     241}
     242
     243.chathearth-settings .chathearth-tabs__dirty[hidden] {
     244        display: none;
     245}
     246
     247.chathearth-settings .chathearth-subtabs__tab .chathearth-tabs__dirty {
     248        margin-inline-start: 6px;
     249}
     250
     251.chathearth-settings .chathearth-tabs__tab.is-active .chathearth-tabs__dirty,
     252.chathearth-settings .chathearth-subtabs__tab.is-active .chathearth-tabs__dirty {
    11253        background: #fff;
    12         border: 1px solid #c3c4c7;
    13         border-top: none;
    14         padding: 8px 16px 16px;
    15 }
    16 
    17 .chathearth-settings .chathearth-tab-panel[hidden] {
    18         display: none !important;
    19 }
    20 
    21 .chathearth-settings .nav-tab-wrapper {
    22         border-bottom: 1px solid #c3c4c7;
    23 }
    24 
    25 .chathearth-settings .chathearth-recaptcha-status {
    26         margin: 0 0 8px;
    27         border-left-color: #00a32a;
    28 }
    29 
    30 .chathearth-settings .chathearth-check-row {
     254}
     255
     256.chathearth-settings .chathearth-main {
     257        min-inline-size: 0;
     258}
     259
     260.chathearth-settings .chathearth-panel {
     261        max-inline-size: 880px;
     262}
     263
     264.chathearth-settings #chathearth-panel-appearance {
     265        max-inline-size: 1240px;
     266}
     267
     268/* 4. Cards and fields
     269   ========================================================================== */
     270
     271.chathearth-settings .chathearth-card {
     272        margin-block-end: var(--chathearth-space-5);
     273        border: 1px solid var(--chathearth-border);
     274        border-radius: var(--chathearth-radius-card);
     275        background: var(--chathearth-surface);
     276        box-shadow: var(--chathearth-shadow);
     277}
     278
     279.chathearth-settings .chathearth-card__header {
     280        display: flex;
     281        flex-wrap: wrap;
     282        align-items: center;
     283        justify-content: space-between;
     284        gap: var(--chathearth-space-3);
     285        padding: var(--chathearth-space-4) var(--chathearth-space-5);
     286        border-block-end: 1px solid var(--chathearth-border);
     287        background: var(--chathearth-surface-alt);
     288        border-start-start-radius: var(--chathearth-radius-card);
     289        border-start-end-radius: var(--chathearth-radius-card);
     290}
     291
     292.chathearth-settings .chathearth-card__title {
     293        margin: 0;
     294        color: var(--chathearth-text);
     295        font-size: 15px;
     296        font-weight: 600;
     297        line-height: 1.3;
     298}
     299
     300.chathearth-settings .chathearth-card__desc {
     301        margin: 3px 0 0;
     302        color: var(--chathearth-text-muted);
     303        font-size: 12px;
     304}
     305
     306.chathearth-settings .chathearth-card__body {
     307        padding: var(--chathearth-space-4) var(--chathearth-space-5);
     308}
     309
     310/* Field row: label column + control column (flex layout) */
     311.chathearth-settings .chathearth-field {
     312        display: flex;
     313        align-items: flex-start;
     314        gap: var(--chathearth-space-4);
     315        margin-block-end: var(--chathearth-space-4);
     316        padding-block-end: var(--chathearth-space-4);
     317        border-block-end: 1px solid var(--chathearth-surface-alt);
     318}
     319
     320.chathearth-settings .chathearth-field:last-child {
     321        margin-block-end: 0;
     322        padding-block-end: 0;
     323        border-block-end: none;
     324}
     325
     326.chathearth-settings .chathearth-field__label,
     327.chathearth-settings legend.chathearth-field__label {
    31328        display: block;
    32         margin: 0 0 6px;
    33 }
    34 
    35 .chathearth-settings .chathearth-inline-label {
    36         margin-left: 16px;
    37 }
     329        flex: 0 0 var(--chathearth-label-width);
     330        inline-size: var(--chathearth-label-width);
     331        max-inline-size: var(--chathearth-label-width);
     332        box-sizing: border-box;
     333        padding-block-start: 4px;
     334        color: var(--chathearth-text);
     335        font-size: 13px;
     336        font-weight: 600;
     337        line-height: 1.4;
     338        word-break: break-word;
     339}
     340
     341.chathearth-settings .chathearth-field__label label {
     342        display: inline-block;
     343        color: inherit;
     344        font-weight: inherit;
     345        cursor: pointer;
     346}
     347
     348.chathearth-settings .chathearth-field__control {
     349        flex: 1 1 0%;
     350        min-inline-size: 0;
     351}
     352
     353.chathearth-settings .chathearth-field__control :is(input, select, textarea) {
     354        max-inline-size: 100%;
     355}
     356
     357/* Field groups: a legend is laid out outside flex, so the group is a block */
     358.chathearth-settings fieldset.chathearth-field {
     359        display: block;
     360        margin: 0;
     361        margin-block-end: var(--chathearth-space-4);
     362        padding: 0;
     363        padding-block-end: var(--chathearth-space-4);
     364        border: 0;
     365        border-block-end: 1px solid var(--chathearth-surface-alt);
     366}
     367
     368.chathearth-settings fieldset.chathearth-field:last-child {
     369        margin-block-end: 0;
     370        padding-block-end: 0;
     371        border-block-end: none;
     372}
     373
     374.chathearth-settings fieldset.chathearth-field::after {
     375        content: "";
     376        display: table;
     377        clear: both;
     378}
     379
     380.chathearth-settings fieldset.chathearth-field > legend.chathearth-field__label {
     381        float: inline-start;
     382        inline-size: var(--chathearth-label-width);
     383        max-inline-size: var(--chathearth-label-width);
     384        margin: 0;
     385        padding: 0;
     386        padding-block-start: 4px;
     387}
     388
     389.chathearth-settings fieldset.chathearth-field > .chathearth-field__control {
     390        margin-inline-start: calc(var(--chathearth-label-width) + var(--chathearth-space-4));
     391}
     392
     393.chathearth-settings .chathearth-error {
     394        margin-block: 6px 0;
     395        margin-inline: 0;
     396        color: var(--chathearth-error-text);
     397        font-size: 12px;
     398        font-weight: 500;
     399}
     400
     401.chathearth-settings .chathearth-field--error input,
     402.chathearth-settings .chathearth-field--error select,
     403.chathearth-settings .chathearth-field--error textarea {
     404        border-color: var(--chathearth-error);
     405}
     406
     407/* 5. Controls
     408   ========================================================================== */
     409
     410/* Toggle Switch (checkbox with role="switch") */
     411.chathearth-settings .chathearth-switch {
     412        display: inline-flex;
     413        align-items: center;
     414        gap: var(--chathearth-space-2);
     415        min-block-size: 28px;
     416}
     417
     418.chathearth-settings .chathearth-toggle {
     419        -webkit-appearance: none;
     420        appearance: none;
     421        position: relative;
     422        flex: none;
     423        inline-size: 36px;
     424        min-inline-size: 36px;
     425        block-size: 20px;
     426        margin: 0;
     427        padding: 0;
     428        border: 0;
     429        border-radius: 10px;
     430        background: var(--chathearth-control-border);
     431        box-shadow: none;
     432        line-height: 1;
     433        cursor: pointer;
     434        transition: background-color var(--chathearth-motion);
     435}
     436
     437.chathearth-settings .chathearth-toggle::before,
     438.chathearth-settings .chathearth-toggle:checked::before {
     439        content: "";
     440        position: absolute;
     441        inset-block-start: 2px;
     442        inset-inline-start: 2px;
     443        inline-size: 16px;
     444        block-size: 16px;
     445        margin: 0;
     446        border-radius: 50%;
     447        background: #fff;
     448        line-height: 1;
     449        transition: inset-inline-start var(--chathearth-motion);
     450}
     451
     452.chathearth-settings .chathearth-toggle:checked {
     453        background: var(--chathearth-accent);
     454}
     455
     456.chathearth-settings .chathearth-toggle:checked::before {
     457        inset-inline-start: 18px;
     458}
     459
     460.chathearth-settings .chathearth-toggle:disabled {
     461        opacity: 0.5;
     462        cursor: not-allowed;
     463}
     464
     465.chathearth-settings .chathearth-switch__state {
     466        color: var(--chathearth-text-muted);
     467        font-size: 13px;
     468        user-select: none;
     469}
     470
     471/* Segmented Control */
     472.chathearth-settings .chathearth-segmented {
     473        position: relative;
     474        display: inline-flex;
     475        flex-wrap: wrap;
     476        max-inline-size: 100%;
     477}
     478
     479.chathearth-settings .chathearth-segmented input[type="radio"] {
     480        position: absolute;
     481        inline-size: 1px;
     482        block-size: 1px;
     483        margin: 0;
     484        opacity: 0;
     485        pointer-events: none;
     486}
     487
     488.chathearth-settings .chathearth-segmented label {
     489        display: inline-flex;
     490        align-items: center;
     491        gap: 6px;
     492        min-block-size: 32px;
     493        margin-inline-end: -1px;
     494        padding-block: 4px;
     495        padding-inline: 12px;
     496        border: 1px solid var(--chathearth-control-border);
     497        background: var(--chathearth-surface);
     498        color: var(--chathearth-text);
     499        font-size: 13px;
     500        cursor: pointer;
     501        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     502        user-select: none;
     503}
     504
     505.chathearth-settings .chathearth-checkgrid label {
     506        display: inline-flex;
     507        align-items: center;
     508        gap: var(--chathearth-space-2);
     509        color: var(--chathearth-text);
     510        font-size: 13px;
     511        cursor: pointer;
     512}
     513
     514.chathearth-settings .chathearth-segmented label:first-of-type {
     515        border-start-start-radius: var(--chathearth-radius-control);
     516        border-end-start-radius: var(--chathearth-radius-control);
     517}
     518
     519.chathearth-settings .chathearth-segmented label:last-of-type {
     520        margin-inline-end: 0;
     521        border-start-end-radius: var(--chathearth-radius-control);
     522        border-end-end-radius: var(--chathearth-radius-control);
     523}
     524
     525.chathearth-settings .chathearth-segmented input[type="radio"]:checked + label {
     526        z-index: 1;
     527        border-color: var(--chathearth-accent);
     528        background: var(--chathearth-accent);
     529        color: #fff;
     530        font-weight: 600;
     531}
     532
     533.chathearth-settings .chathearth-segmented input[type="radio"]:focus-visible + label {
     534        z-index: 2;
     535        box-shadow: 0 0 0 2px var(--chathearth-surface), 0 0 0 4px var(--chathearth-accent);
     536}
     537
     538/* Number + Unit and Range Sliders */
     539.chathearth-settings .chathearth-input-group {
     540        display: flex;
     541        flex-wrap: wrap;
     542        align-items: center;
     543        gap: var(--chathearth-space-2) var(--chathearth-space-3);
     544}
     545
     546.chathearth-settings .chathearth-input-group .small-text {
     547        inline-size: 6em;
     548}
     549
     550.chathearth-settings .chathearth-input-group input[type="range"] {
     551        flex: 0 1 150px;
     552        inline-size: 150px;
     553        min-inline-size: 90px;
     554        margin: 0;
     555        accent-color: var(--chathearth-accent);
     556}
     557
     558.chathearth-settings .chathearth-input-group__unit {
     559        color: var(--chathearth-text-muted);
     560        font-size: 13px;
     561}
     562
     563/* Colour Field */
     564.chathearth-settings .chathearth-color {
     565        display: inline-flex;
     566        align-items: center;
     567        gap: var(--chathearth-space-2);
     568}
     569
     570.chathearth-settings .chathearth-color input[type="color"] {
     571        inline-size: 32px;
     572        block-size: 32px;
     573        padding: 2px;
     574        border: 1px solid var(--chathearth-control-border);
     575        border-radius: var(--chathearth-radius-control);
     576        background: #fff;
     577        cursor: pointer;
     578}
     579
     580.chathearth-settings .chathearth-color__hex {
     581        inline-size: 9em;
     582        font-family: Consolas, Monaco, monospace;
     583        direction: ltr;
     584        text-align: start;
     585}
     586
     587/* Secret Field */
     588.chathearth-settings .chathearth-secret {
     589        display: flex;
     590        flex-direction: column;
     591        gap: var(--chathearth-space-2);
     592}
     593
     594.chathearth-settings .chathearth-secret__saved {
     595        display: flex;
     596        align-items: center;
     597        gap: var(--chathearth-space-3);
     598        color: var(--chathearth-text-muted);
     599        font-size: 13px;
     600}
     601
     602/* Checkbox Grid */
     603.chathearth-settings .chathearth-checkgrid {
     604        display: grid;
     605        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
     606        gap: var(--chathearth-space-2) var(--chathearth-space-4);
     607        margin: 0;
     608        padding: 0;
     609        border: 0;
     610}
     611
     612.chathearth-settings .chathearth-count {
     613        color: var(--chathearth-text-muted);
     614        font-size: 12px;
     615}
     616
     617.chathearth-settings .chathearth-code-input {
     618        font-family: Consolas, Monaco, monospace;
     619        font-size: 12px;
     620        direction: ltr;
     621        text-align: start;
     622}
     623
     624/* 6. Small components
     625   ========================================================================== */
     626
     627/* Status Pill */
     628.chathearth-settings .chathearth-pill {
     629        display: inline-flex;
     630        align-items: center;
     631        gap: 6px;
     632        padding-block: 2px;
     633        padding-inline: 8px;
     634        border-radius: 9999px;
     635        background: var(--chathearth-surface-alt);
     636        color: var(--chathearth-text);
     637        font-size: 11px;
     638        font-weight: 600;
     639        line-height: 1.4;
     640        white-space: nowrap;
     641}
     642
     643.chathearth-settings .chathearth-pill::before {
     644        content: "";
     645        inline-size: 6px;
     646        block-size: 6px;
     647        border-radius: 50%;
     648        background: currentcolor;
     649}
     650
     651.chathearth-settings .chathearth-pill--success {
     652        background: var(--chathearth-success-bg);
     653        color: var(--chathearth-success-text);
     654}
     655
     656.chathearth-settings .chathearth-pill--warning {
     657        background: var(--chathearth-warning-bg);
     658        color: var(--chathearth-warning-text);
     659}
     660
     661.chathearth-settings .chathearth-pill--error {
     662        background: var(--chathearth-error-bg);
     663        color: var(--chathearth-error-text);
     664}
     665
     666.chathearth-settings .chathearth-pill--neutral {
     667        background: var(--chathearth-surface-alt);
     668        color: var(--chathearth-text-muted);
     669}
     670
     671/* Badges */
     672.chathearth-settings .chathearth-badge {
     673        display: inline-block;
     674        padding-block: 2px;
     675        padding-inline: 6px;
     676        border: 1px solid var(--chathearth-border);
     677        border-radius: 3px;
     678        background: var(--chathearth-surface-alt);
     679        color: var(--chathearth-text-muted);
     680        font-size: 11px;
     681        font-weight: 500;
     682        line-height: 1.2;
     683}
     684
     685/* Callout Box */
     686.chathearth-settings .chathearth-callout {
     687        display: flex;
     688        align-items: flex-start;
     689        gap: var(--chathearth-space-3);
     690        margin-block: var(--chathearth-space-4);
     691        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     692        border: 1px solid var(--chathearth-info);
     693        border-inline-start-width: 4px;
     694        border-radius: var(--chathearth-radius-control);
     695        background: var(--chathearth-info-bg);
     696        color: var(--chathearth-text);
     697        font-size: 12px;
     698}
     699
     700.chathearth-settings .chathearth-callout .chathearth-icon {
     701        color: var(--chathearth-accent);
     702}
     703
     704/* Starter Suggestion Chips */
     705.chathearth-settings .chathearth-chips {
     706        display: flex;
     707        flex-wrap: wrap;
     708        gap: var(--chathearth-space-2);
     709        margin: var(--chathearth-space-2) 0 0;
     710        padding: 0;
     711        list-style: none;
     712}
     713
     714.chathearth-settings .chathearth-chip {
     715        padding-block: 3px;
     716        padding-inline: 10px;
     717        border: 1px solid var(--chathearth-border);
     718        border-radius: 9999px;
     719        background: var(--chathearth-surface-alt);
     720        color: var(--chathearth-text);
     721        font-size: 12px;
     722}
     723
     724/* Stat Tiles */
     725.chathearth-settings .chathearth-stats {
     726        display: grid;
     727        grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
     728        gap: var(--chathearth-space-3);
     729        margin-block-end: var(--chathearth-space-4);
     730}
     731
     732.chathearth-settings .chathearth-stat {
     733        padding: var(--chathearth-space-3);
     734        border: 1px solid var(--chathearth-border);
     735        border-radius: var(--chathearth-radius-control);
     736        background: var(--chathearth-surface-alt);
     737        text-align: center;
     738}
     739
     740.chathearth-settings .chathearth-stat__value {
     741        display: block;
     742        font-size: 20px;
     743        font-weight: 600;
     744        line-height: 1.2;
     745}
     746
     747.chathearth-settings .chathearth-stat__label {
     748        display: block;
     749        margin-block-start: 2px;
     750        color: var(--chathearth-text-muted);
     751        font-size: 11px;
     752}
     753
     754/* Progress Bar */
     755.chathearth-settings .chathearth-progress {
     756        inline-size: 100%;
     757        block-size: 8px;
     758        overflow: hidden;
     759        border-radius: 4px;
     760        background: var(--chathearth-border);
     761}
     762
     763.chathearth-settings .chathearth-progress__bar {
     764        block-size: 100%;
     765        background: var(--chathearth-accent);
     766        transition: inline-size 300ms ease;
     767}
     768
     769/* Empty State */
     770.chathearth-settings .chathearth-empty {
     771        padding-block: var(--chathearth-space-6);
     772        padding-inline: var(--chathearth-space-4);
     773        text-align: center;
     774}
     775
     776.chathearth-settings .chathearth-empty .chathearth-icon {
     777        inline-size: 40px;
     778        block-size: 40px;
     779        margin-block-end: var(--chathearth-space-3);
     780        color: var(--chathearth-text-muted);
     781}
     782
     783/* Toast Messages */
     784.chathearth-toasts {
     785        position: fixed;
     786        inset-block-end: 64px;
     787        inset-inline-end: 24px;
     788        z-index: 100;
     789        display: flex;
     790        flex-direction: column-reverse;
     791        gap: var(--chathearth-space-2);
     792        pointer-events: none;
     793}
     794
     795.chathearth-toast {
     796        display: flex;
     797        align-items: center;
     798        justify-content: space-between;
     799        gap: var(--chathearth-space-3);
     800        min-inline-size: 260px;
     801        max-inline-size: 380px;
     802        padding: 10px 14px;
     803        border-radius: var(--chathearth-radius-control);
     804        background: #1d2327;
     805        color: #fff;
     806        font-size: 13px;
     807        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
     808        pointer-events: auto;
     809        animation: chathearth-toast-in var(--chathearth-motion);
     810}
     811
     812@keyframes chathearth-toast-in {
     813
     814        from {
     815                opacity: 0;
     816                transform: translateY(8px);
     817        }
     818
     819        to {
     820                opacity: 1;
     821                transform: translateY(0);
     822        }
     823}
     824
     825.chathearth-toast__close {
     826        display: grid;
     827        place-items: center;
     828        padding: 0;
     829        border: 0;
     830        background: none;
     831        color: #c3c4c7;
     832        cursor: pointer;
     833}
     834
     835.chathearth-toast__close:hover {
     836        color: #fff;
     837}
     838
     839/* Native Dialog */
     840.chathearth-dialog {
     841        max-inline-size: 420px;
     842        padding: var(--chathearth-space-5);
     843        border: 0;
     844        border-radius: var(--chathearth-radius-card);
     845        background: var(--chathearth-surface);
     846        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
     847}
     848
     849.chathearth-dialog::backdrop {
     850        background: rgba(0, 0, 0, 0.4);
     851        backdrop-filter: blur(2px);
     852}
     853
     854.chathearth-dialog h2 {
     855        margin-block-start: 0;
     856        margin-block-end: var(--chathearth-space-2);
     857        font-size: 17px;
     858}
     859
     860.chathearth-dialog p {
     861        margin-block-start: 0;
     862        margin-block-end: var(--chathearth-space-5);
     863        color: var(--chathearth-text-muted);
     864        font-size: 13px;
     865}
     866
     867.chathearth-dialog__actions {
     868        display: flex;
     869        justify-content: flex-end;
     870        gap: var(--chathearth-space-3);
     871}
     872
     873.chathearth-button--danger {
     874        border-color: var(--chathearth-error) !important;
     875        background: var(--chathearth-error) !important;
     876        color: #fff !important;
     877}
     878
     879.chathearth-button--danger:hover {
     880        border-color: #b32d2e !important;
     881        background: #b32d2e !important;
     882}
     883
     884/* Disclosure (Built-in rules) */
     885.chathearth-disclosure {
     886        margin-block-start: var(--chathearth-space-4);
     887        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     888        border: 1px solid var(--chathearth-border);
     889        border-radius: var(--chathearth-radius-control);
     890        background: var(--chathearth-surface-alt);
     891}
     892
     893.chathearth-disclosure summary {
     894        color: var(--chathearth-accent);
     895        font-size: 13px;
     896        font-weight: 500;
     897        cursor: pointer;
     898        user-select: none;
     899}
     900
     901.chathearth-disclosure ol {
     902        margin-block: var(--chathearth-space-3) 0;
     903        margin-inline: 0;
     904        padding-inline-start: 20px;
     905        color: var(--chathearth-text);
     906        font-size: 12px;
     907        line-height: 1.6;
     908}
     909
     910/* 7. Protection sub-tabs and rate-limit groups
     911   ========================================================================== */
     912
     913.chathearth-subtabs {
     914        margin-block-end: var(--chathearth-space-4);
     915}
     916
     917.chathearth-settings .chathearth-subtabs > [role="tablist"] {
     918        display: flex;
     919        flex-wrap: wrap;
     920        gap: var(--chathearth-space-2);
     921}
     922
     923.chathearth-subtabs__tab {
     924        display: inline-flex;
     925        align-items: center;
     926        line-height: 1.4;
     927        padding-block: 6px;
     928        padding-inline: 12px;
     929        border: 1px solid var(--chathearth-border);
     930        border-radius: 9999px;
     931        background: var(--chathearth-surface);
     932        color: var(--chathearth-text);
     933        font-size: 12px;
     934        font-weight: 500;
     935        text-decoration: none;
     936        cursor: pointer;
     937        user-select: none;
     938        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     939}
     940
     941.chathearth-subtabs__tab:hover {
     942        border-color: var(--chathearth-accent);
     943        color: var(--chathearth-accent);
     944}
     945
     946.chathearth-subtabs__tab.is-active {
     947        border-color: var(--chathearth-accent);
     948        background: var(--chathearth-accent);
     949        color: #fff;
     950        font-weight: 600;
     951}
     952
     953.chathearth-subgroup-title {
     954        margin-block: var(--chathearth-space-4) var(--chathearth-space-2);
     955        color: var(--chathearth-text);
     956        font-size: 13px;
     957        font-weight: 600;
     958}
     959
     960/* Allowances Table */
     961.chathearth-allowances {
     962        inline-size: 100%;
     963        max-inline-size: 440px;
     964        border-collapse: collapse;
     965}
     966
     967.chathearth-allowances th,
     968.chathearth-allowances td {
     969        padding-block: 6px;
     970        padding-inline: 8px;
     971        border-block-end: 1px solid var(--chathearth-border);
     972}
     973
     974.chathearth-allowances th {
     975        text-align: start;
     976        font-weight: 400;
     977}
     978
     979.chathearth-allowances td {
     980        text-align: end;
     981}
     982
     983/* 8. Appearance: live preview, launcher, product cards
     984   ========================================================================== */
     985
     986.chathearth-settings .chathearth-appearance {
     987        display: grid;
     988        grid-template-columns: minmax(0, 1fr);
     989        gap: var(--chathearth-space-5);
     990        align-items: start;
     991}
     992
     993.chathearth-settings .chathearth-appearance__reset {
     994        margin-block-end: var(--chathearth-space-4);
     995}
     996
     997@media (min-width: 1100px) {
     998
     999        .chathearth-settings .chathearth-appearance {
     1000                grid-template-columns: minmax(0, 1fr) 360px;
     1001        }
     1002}
     1003
     1004/* Live widget preview aside */
     1005.chathearth-settings .chathearth-preview {
     1006        --chathearth-icon-bg: #0f172a;
     1007        --chathearth-icon-border: #1e293b;
     1008        --chathearth-icon-color: #fff;
     1009        --chathearth-icon-size: 56px;
     1010        --chathearth-user-bubble: #0f172a;
     1011        --chathearth-user-text: #fff;
     1012        --chathearth-assistant-bubble: #e2e8f0;
     1013        --chathearth-assistant-text: #1d2327;
     1014        --chathearth-product-card-bg: #fff;
     1015        --chathearth-product-card-border: #dcdcde;
     1016        --chathearth-product-card-text: #1d2327;
     1017        --chathearth-product-button-bg: #0f172a;
     1018        --chathearth-product-button-text: #fff;
     1019        --chathearth-product-button-radius: 2px;
     1020        --chathearth-product-card-radius: 4px;
     1021        --chathearth-product-card-width: 140px;
     1022
     1023        position: sticky;
     1024        inset-block-start: var(--chathearth-sticky-top);
     1025        display: flex;
     1026        flex-direction: column;
     1027        min-inline-size: 0;
     1028        max-block-size: calc(100vh - 120px);
     1029        padding: var(--chathearth-space-4);
     1030        border: 1px solid var(--chathearth-border);
     1031        border-radius: var(--chathearth-radius-card);
     1032        background: #e7eaed;
     1033}
     1034
     1035.chathearth-settings .chathearth-preview__caption {
     1036        display: flex;
     1037        justify-content: space-between;
     1038        gap: var(--chathearth-space-2);
     1039        color: var(--chathearth-text-muted);
     1040        font-size: 11px;
     1041        font-weight: 600;
     1042        text-transform: uppercase;
     1043        letter-spacing: 0.5px;
     1044}
     1045
     1046.chathearth-settings .chathearth-preview__window {
     1047        display: flex;
     1048        flex: 1 1 auto;
     1049        flex-direction: column;
     1050        min-block-size: 0;
     1051        margin-block-start: var(--chathearth-space-3);
     1052        overflow: hidden;
     1053        border-radius: 10px;
     1054        background: var(--chathearth-surface);
     1055        box-shadow: 0 8px 24px rgba(29, 35, 39, 0.12);
     1056}
     1057
     1058.chathearth-settings .chathearth-preview__header {
     1059        flex: none;
     1060        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     1061        background: var(--chathearth-icon-bg);
     1062        color: var(--chathearth-icon-color);
     1063        font-weight: 600;
     1064        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     1065}
     1066
     1067.chathearth-settings .chathearth-preview__conversation {
     1068        display: flex;
     1069        flex: 1 1 auto;
     1070        flex-direction: column;
     1071        gap: var(--chathearth-space-3);
     1072        min-block-size: 0;
     1073        padding: var(--chathearth-space-4);
     1074        overflow-y: auto;
     1075        overscroll-behavior: contain;
     1076}
     1077
     1078.chathearth-settings .chathearth-preview[data-size="small"] .chathearth-preview__conversation {
     1079        min-block-size: 200px;
     1080}
     1081
     1082.chathearth-settings .chathearth-preview[data-size="medium"] .chathearth-preview__conversation {
     1083        min-block-size: 260px;
     1084}
     1085
     1086.chathearth-settings .chathearth-preview[data-size="large"] .chathearth-preview__conversation {
     1087        min-block-size: 340px;
     1088}
     1089
     1090.chathearth-settings .chathearth-preview__bubble {
     1091        max-inline-size: 90%;
     1092        margin: 0;
     1093        padding: 9px 13px;
     1094        border-radius: 12px;
     1095        background: var(--chathearth-assistant-bubble);
     1096        color: var(--chathearth-assistant-text);
     1097        font-size: 13px;
     1098        line-height: 1.4;
     1099        transition: background-color var(--chathearth-motion), color var(--chathearth-motion);
     1100}
     1101
     1102.chathearth-settings .chathearth-preview__bubble--user {
     1103        align-self: flex-end;
     1104        background: var(--chathearth-user-bubble);
     1105        color: var(--chathearth-user-text);
     1106}
     1107
     1108.chathearth-settings .chathearth-preview__sources {
     1109        display: flex;
     1110        align-items: center;
     1111        gap: var(--chathearth-space-2);
     1112        margin-block-end: var(--chathearth-space-2);
     1113        color: var(--chathearth-text-muted);
     1114        font-size: 11px;
     1115}
     1116
     1117.chathearth-settings .chathearth-product-list {
     1118        display: flex;
     1119        gap: var(--chathearth-space-3);
     1120        overflow-x: auto;
     1121        padding-block-end: 6px;
     1122}
     1123
     1124.chathearth-settings .chathearth-product {
     1125        flex: none;
     1126        display: flex;
     1127        flex-direction: column;
     1128        inline-size: var(--chathearth-product-card-width);
     1129        border: 1px solid var(--chathearth-product-card-border);
     1130        border-radius: var(--chathearth-product-card-radius);
     1131        background: var(--chathearth-product-card-bg);
     1132        color: var(--chathearth-product-card-text);
     1133        overflow: hidden;
     1134        font-size: 12px;
     1135}
     1136
     1137.chathearth-settings .chathearth-product__image {
     1138        inline-size: 100%;
     1139        block-size: auto;
     1140        display: block;
     1141}
     1142
     1143.chathearth-settings .chathearth-product__details {
     1144        display: flex;
     1145        flex-direction: column;
     1146        gap: 4px;
     1147        padding: 8px;
     1148}
     1149
     1150.chathearth-settings .chathearth-product__button {
     1151        margin-block-start: 4px;
     1152        padding-block: 4px;
     1153        padding-inline: 8px;
     1154        border: 0;
     1155        border-radius: var(--chathearth-product-button-radius);
     1156        background: var(--chathearth-product-button-bg);
     1157        color: var(--chathearth-product-button-text);
     1158        font-size: 11px;
     1159        font-weight: 500;
     1160        cursor: pointer;
     1161}
     1162
     1163.chathearth-settings .chathearth-product-compare {
     1164        margin-block-start: var(--chathearth-space-2);
     1165        font-size: 11px;
     1166}
     1167
     1168.chathearth-settings .chathearth-preview__input {
     1169        flex: none;
     1170        display: flex;
     1171        justify-content: space-between;
     1172        align-items: center;
     1173        padding: var(--chathearth-space-3) var(--chathearth-space-4);
     1174        border-block-start: 1px solid var(--chathearth-page);
     1175        color: var(--chathearth-text-muted);
     1176        font-size: 12px;
     1177}
     1178
     1179.chathearth-settings .chathearth-preview__input-icon {
     1180        inline-size: 16px;
     1181        block-size: 16px;
     1182        color: var(--chathearth-text-muted);
     1183}
     1184
     1185/* The dock forces LTR so "Bottom right" always means physical right corner */
     1186.chathearth-settings .chathearth-preview__dock {
     1187        display: flex;
     1188        flex: none;
     1189        direction: ltr;
     1190        justify-content: flex-end;
     1191        margin-block-start: var(--chathearth-space-4);
     1192}
     1193
     1194.chathearth-settings .chathearth-preview[data-position="bottom-left"] .chathearth-preview__dock {
     1195        justify-content: flex-start;
     1196}
     1197
     1198.chathearth-settings .chathearth-preview[data-position="bottom-center"] .chathearth-preview__dock {
     1199        justify-content: center;
     1200}
     1201
     1202.chathearth-settings .chathearth-preview__launcher {
     1203        position: relative;
     1204        isolation: isolate;
     1205        display: grid;
     1206        place-items: center;
     1207        inline-size: var(--chathearth-icon-size);
     1208        block-size: var(--chathearth-icon-size);
     1209        max-inline-size: 100%;
     1210        margin: 0;
     1211        padding: 0;
     1212        border: 1px solid var(--chathearth-icon-border);
     1213        border-radius: 50%;
     1214        background: var(--chathearth-icon-bg);
     1215        color: var(--chathearth-icon-color);
     1216        font: inherit;
     1217        cursor: pointer;
     1218        transition: transform var(--chathearth-motion);
     1219}
     1220
     1221[dir="rtl"] .chathearth-settings .chathearth-preview__launcher {
     1222        direction: rtl;
     1223}
     1224
     1225.chathearth-settings .chathearth-preview[data-shape="square"] .chathearth-preview__launcher {
     1226        border-radius: 8px;
     1227}
     1228
     1229.chathearth-settings .chathearth-preview__launcher-inner {
     1230        position: relative;
     1231        z-index: 2;
     1232        display: flex;
     1233        align-items: center;
     1234        justify-content: center;
     1235        min-inline-size: 0;
     1236}
     1237
     1238.chathearth-settings .chathearth-preview__launcher-icon {
     1239        display: grid;
     1240        flex: none;
     1241        place-items: center;
     1242        line-height: 0;
     1243}
     1244
     1245.chathearth-settings .chathearth-preview__launcher-sparkle {
     1246        inline-size: 24px;
     1247        block-size: 24px;
     1248        fill: currentcolor;
     1249}
     1250
     1251.chathearth-settings .chathearth-preview__beam-track,
     1252.chathearth-settings .chathearth-preview__launcher-label {
     1253        display: none;
     1254}
     1255
     1256/* Pill Launcher ("Icon and text") */
     1257.chathearth-settings .chathearth-preview__launcher[data-style="pill"] {
     1258        display: block;
     1259        inline-size: auto;
     1260        block-size: auto;
     1261        border: 2px solid rgba(36, 36, 36, 0.2);
     1262        border-radius: 9999px;
     1263        background: transparent;
     1264        box-shadow: 0 2px 20px rgba(0, 0, 0, 0.25), 0 0 1px rgba(0, 0, 0, 0.25);
     1265        color: #242424;
     1266}
     1267
     1268.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-inner {
     1269        flex-direction: row-reverse;
     1270        gap: var(--chathearth-space-4);
     1271        max-inline-size: 100%;
     1272        padding: var(--chathearth-space-2);
     1273        border-radius: 9999px;
     1274        background: #fff;
     1275}
     1276
     1277[dir="rtl"] .chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-inner {
     1278        flex-direction: row;
     1279}
     1280
     1281.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-icon {
     1282        inline-size: calc(var(--chathearth-icon-size) - 12px);
     1283        block-size: calc(var(--chathearth-icon-size) - 12px);
     1284        border-radius: 50%;
     1285        background-color: var(--chathearth-icon-bg);
     1286        background-image: linear-gradient(135deg, color-mix(in srgb, var(--chathearth-icon-bg) 60%, #3d4555), var(--chathearth-icon-bg) 30%, color-mix(in srgb, var(--chathearth-icon-bg) 70%, #fff) 50%, var(--chathearth-icon-bg) 70%, color-mix(in srgb, var(--chathearth-icon-bg) 60%, #3d4555));
     1287        background-position: 0% 50%;
     1288        background-size: 400% 400%;
     1289        color: var(--chathearth-icon-color);
     1290}
     1291
     1292.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__launcher-label {
     1293        display: grid;
     1294        grid-template-columns: 1fr;
     1295        min-inline-size: 0;
     1296        overflow: hidden;
     1297}
     1298
     1299.chathearth-settings .chathearth-preview__launcher-text {
     1300        min-inline-size: 0;
     1301        padding-block-end: 2px;
     1302        padding-inline-end: var(--chathearth-space-2);
     1303        overflow: hidden;
     1304        color: #242424;
     1305        font-size: 15px;
     1306        font-weight: 500;
     1307        line-height: 22px;
     1308        text-overflow: ellipsis;
     1309        white-space: nowrap;
     1310}
     1311
     1312.chathearth-settings .chathearth-preview__launcher[data-style="pill"] .chathearth-preview__beam-track {
     1313        position: absolute;
     1314        inset: -3px;
     1315        z-index: 1;
     1316        display: block;
     1317        overflow: hidden;
     1318        border-radius: 9999px;
     1319        pointer-events: none;
     1320}
     1321
     1322.chathearth-settings .chathearth-preview__beam {
     1323        position: absolute;
     1324        inset-block-start: 0;
     1325        inset-inline-start: 0;
     1326        inline-size: 80px;
     1327        block-size: 80px;
     1328        background: radial-gradient(closest-side, #242424, transparent);
     1329        offset-anchor: center center;
     1330        offset-path: inset(0 round 9999px);
     1331        offset-rotate: 0deg;
     1332        opacity: 0;
     1333}
     1334
     1335/* Pill launcher animations */
     1336.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-entering {
     1337        animation: chathearth-pill-enter 0.45s cubic-bezier(0.34, 1.56, 0.64, 1) both;
     1338}
     1339
     1340.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-entering .chathearth-preview__launcher-label {
     1341        animation: chathearth-pill-label-enter 0.3s ease-out both;
     1342}
     1343
     1344.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__launcher-icon {
     1345        animation: chathearth-pill-gradient 8s forwards;
     1346}
     1347
     1348.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__launcher-sparkle {
     1349        animation: chathearth-pill-sparkle 12s ease-in-out forwards;
     1350}
     1351
     1352.chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__beam {
     1353        animation: chathearth-pill-beam 4s linear forwards;
     1354}
     1355
     1356@supports ((background-clip: text) or (-webkit-background-clip: text)) {
     1357
     1358        .chathearth-settings .chathearth-preview__launcher[data-style="pill"].is-animating .chathearth-preview__launcher-text {
     1359                background: linear-gradient(90deg, #242424 0%, #242424 30%, #707070 45%, #bdbdbd 50%, #707070 55%, #242424 70%, #242424 100%);
     1360                background-size: 300% 100%;
     1361                -webkit-background-clip: text;
     1362                background-clip: text;
     1363                color: transparent;
     1364                animation: chathearth-pill-shimmer 2s ease-in-out forwards;
     1365        }
     1366}
     1367
     1368@keyframes chathearth-pill-enter {
     1369
     1370        from {
     1371                opacity: 0;
     1372                transform: scale(0.625);
     1373        }
     1374
     1375        to {
     1376                opacity: 1;
     1377                transform: scale(1);
     1378        }
     1379}
     1380
     1381@keyframes chathearth-pill-label-enter {
     1382
     1383        from {
     1384                opacity: 0;
     1385                transform: scaleX(0.8);
     1386        }
     1387
     1388        to {
     1389                opacity: 1;
     1390                transform: scaleX(1);
     1391        }
     1392}
     1393
     1394@keyframes chathearth-pill-beam {
     1395
     1396        0% {
     1397                offset-distance: 0%;
     1398                opacity: 1;
     1399        }
     1400
     1401        100% {
     1402                offset-distance: 100%;
     1403                opacity: 1;
     1404        }
     1405}
     1406
     1407@keyframes chathearth-pill-gradient {
     1408
     1409        0% {
     1410                background-position: 0% 50%;
     1411        }
     1412
     1413        50% {
     1414                background-position: 100% 50%;
     1415        }
     1416
     1417        100% {
     1418                background-position: 0% 50%;
     1419        }
     1420}
     1421
     1422@keyframes chathearth-pill-sparkle {
     1423
     1424        0%,
     1425        100% {
     1426                transform: scale(1) rotate(0deg);
     1427        }
     1428
     1429        15% {
     1430                transform: scale(1.15) rotate(12deg);
     1431        }
     1432
     1433        30% {
     1434                transform: scale(0.95) rotate(-8deg);
     1435        }
     1436
     1437        45% {
     1438                transform: scale(1.08) rotate(4deg);
     1439        }
     1440
     1441        60% {
     1442                transform: scale(1) rotate(0deg);
     1443        }
     1444}
     1445
     1446@keyframes chathearth-pill-shimmer {
     1447
     1448        0% {
     1449                background-position: 100% 0%;
     1450        }
     1451
     1452        100% {
     1453                background-position: -100% 0%;
     1454        }
     1455}
     1456
     1457/* Contrast notice */
     1458.chathearth-contrast {
     1459        margin-block: 4px 0;
     1460        margin-inline: 0;
     1461        color: var(--chathearth-warning-text);
     1462        font-size: 12px;
     1463        font-weight: 500;
     1464}
     1465
     1466/* 9. Knowledge Base index
     1467   ========================================================================== */
    381468
    391469.chathearth-settings .chathearth-kb-toolbar {
    401470        display: flex;
    41         align-items: center;
    42         gap: 8px;
    43         margin: 12px 0;
    44 }
    45 
    46 .chathearth-settings .chathearth-kb-status {
    47         font-style: italic;
    48 }
    49 
    50 .chathearth-settings .chathearth-kb-entries-wrap {
    51         margin-top: 16px;
    52 }
    53 
    54 .chathearth-settings .chathearth-kb-pager {
    55         margin-top: 8px;
    56 }
     1471        flex-wrap: wrap;
     1472        align-items: center;
     1473        justify-content: space-between;
     1474        gap: var(--chathearth-space-3);
     1475        margin-block-end: var(--chathearth-space-4);
     1476}
     1477
     1478.chathearth-settings .chathearth-kb-filters {
     1479        display: flex;
     1480        flex-wrap: wrap;
     1481        align-items: center;
     1482        gap: var(--chathearth-space-2);
     1483}
     1484
     1485.chathearth-settings .chathearth-table-wrap {
     1486        overflow-x: auto;
     1487        border: 1px solid var(--chathearth-border);
     1488        border-radius: var(--chathearth-radius-control);
     1489}
     1490
     1491.chathearth-settings .chathearth-table {
     1492        inline-size: 100%;
     1493        border-collapse: collapse;
     1494        text-align: start;
     1495}
     1496
     1497.chathearth-settings .chathearth-table th,
     1498.chathearth-settings .chathearth-table td {
     1499        padding: 10px 12px;
     1500        border-block-end: 1px solid var(--chathearth-border);
     1501        vertical-align: middle;
     1502}
     1503
     1504.chathearth-settings .chathearth-table th {
     1505        background: var(--chathearth-surface-alt);
     1506        color: var(--chathearth-text-muted);
     1507        font-size: 12px;
     1508        font-weight: 600;
     1509}
     1510
     1511.chathearth-settings .chathearth-table tbody tr:last-child td {
     1512        border-block-end: 0;
     1513}
     1514
     1515.chathearth-settings .chathearth-table tbody tr:hover {
     1516        background: #fbfbfc;
     1517}
     1518
     1519.chathearth-settings .chathearth-table__error {
     1520        display: flex;
     1521        align-items: center;
     1522        gap: 6px;
     1523        margin-block: 4px 0;
     1524        margin-inline: 0;
     1525        color: var(--chathearth-error-text);
     1526        font-size: 12px;
     1527}
     1528
     1529.chathearth-settings .chathearth-table__error .chathearth-icon {
     1530        inline-size: 14px;
     1531        block-size: 14px;
     1532}
     1533
     1534.chathearth-settings .chathearth-kb-pagination {
     1535        display: flex;
     1536        align-items: center;
     1537        justify-content: flex-end;
     1538        gap: var(--chathearth-space-3);
     1539        margin-block-start: var(--chathearth-space-4);
     1540        font-size: 12px;
     1541        color: var(--chathearth-text-muted);
     1542}
     1543
     1544/* Index card: actions, busy buttons, sync progress, notices (feature 012) */
     1545
     1546.chathearth-settings .chathearth-card__actions {
     1547        display: flex;
     1548        flex-wrap: wrap;
     1549        gap: var(--chathearth-space-2);
     1550}
     1551
     1552.chathearth-settings .chathearth-card__actions .button,
     1553.chathearth-settings #chathearth-kb-empty .button {
     1554        display: inline-flex;
     1555        align-items: center;
     1556        gap: var(--chathearth-space-2);
     1557}
     1558
     1559.chathearth-settings .button .spinner {
     1560        display: none;
     1561        float: none;
     1562        margin: 0;
     1563}
     1564
     1565.chathearth-settings .button .spinner.is-active {
     1566        display: inline-block;
     1567        visibility: visible;
     1568}
     1569
     1570.chathearth-settings .button.is-busy {
     1571        cursor: progress;
     1572}
     1573
     1574.chathearth-settings #chathearth-sync-progress {
     1575        margin-block-end: var(--chathearth-space-4);
     1576}
     1577
     1578.chathearth-settings .chathearth-progress__text {
     1579        display: flex;
     1580        flex-wrap: wrap;
     1581        justify-content: space-between;
     1582        gap: var(--chathearth-space-2);
     1583        margin-block: var(--chathearth-space-1) 0;
     1584}
     1585
     1586.chathearth-settings .chathearth-progress.is-indeterminate {
     1587        position: relative;
     1588}
     1589
     1590.chathearth-settings .is-indeterminate .chathearth-progress__bar {
     1591        position: absolute;
     1592        inset-block: 0;
     1593        inset-inline-start: 0;
     1594        inline-size: 35%;
     1595        animation: chathearth-progress-sweep 1.4s ease-in-out infinite;
     1596}
     1597
     1598/* Reduced motion: the global rule stops the sweep after one pass. */
     1599@keyframes chathearth-progress-sweep {
     1600
     1601        from {
     1602                inset-inline-start: -35%;
     1603        }
     1604
     1605        to {
     1606                inset-inline-start: 100%;
     1607        }
     1608}
     1609
     1610.chathearth-settings #chathearth-kb-notice,
     1611.chathearth-settings #chathearth-kb-alert {
     1612        display: flex;
     1613        flex-wrap: wrap;
     1614        align-items: center;
     1615        gap: var(--chathearth-space-3);
     1616        margin-block: 0 var(--chathearth-space-4);
     1617        margin-inline: 0;
     1618}
     1619
     1620.chathearth-settings #chathearth-kb-notice p,
     1621.chathearth-settings #chathearth-kb-alert p {
     1622        margin: 0;
     1623}
     1624
     1625.chathearth-settings #chathearth-kb-sync-hint {
     1626        margin-block: 0 var(--chathearth-space-3);
     1627}
     1628
     1629/* Index card: list rows, the Included switch, narrow screens (feature 012) */
     1630
     1631.chathearth-settings .chathearth-table__title {
     1632        max-inline-size: 360px;
     1633        overflow: hidden;
     1634        text-overflow: ellipsis;
     1635        white-space: nowrap;
     1636}
     1637
     1638.chathearth-settings .chathearth-table__col-type,
     1639.chathearth-settings .chathearth-table__col-status,
     1640.chathearth-settings .chathearth-table__col-updated {
     1641        inline-size: 130px;
     1642}
     1643
     1644.chathearth-settings .chathearth-table__col-included {
     1645        inline-size: 90px;
     1646}
     1647
     1648.chathearth-settings .chathearth-table td .chathearth-table__error {
     1649        max-inline-size: 260px;
     1650        white-space: normal;
     1651}
     1652
     1653.chathearth-settings .chathearth-switch-button {
     1654        position: relative;
     1655        display: inline-block;
     1656        flex: none;
     1657        inline-size: 36px;
     1658        min-inline-size: 36px;
     1659        block-size: 20px;
     1660        margin: 0;
     1661        padding: 0;
     1662        border: 0;
     1663        border-radius: 10px;
     1664        background: var(--chathearth-control-border);
     1665        cursor: pointer;
     1666        transition: background-color var(--chathearth-motion);
     1667}
     1668
     1669.chathearth-settings .chathearth-switch-button::before {
     1670        content: "";
     1671        position: absolute;
     1672        inset-block-start: 2px;
     1673        inset-inline-start: 2px;
     1674        inline-size: 16px;
     1675        block-size: 16px;
     1676        border-radius: 50%;
     1677        background: #fff;
     1678        transition: inset-inline-start var(--chathearth-motion);
     1679}
     1680
     1681.chathearth-settings .chathearth-switch-button[aria-checked="true"] {
     1682        background: var(--chathearth-accent);
     1683}
     1684
     1685.chathearth-settings .chathearth-switch-button[aria-checked="true"]::before {
     1686        inset-inline-start: 18px;
     1687}
     1688
     1689.chathearth-settings .chathearth-switch-button:disabled {
     1690        opacity: 0.5;
     1691        cursor: progress;
     1692}
     1693
     1694.chathearth-settings #chathearth-kb-nomatch {
     1695        padding-block: var(--chathearth-space-5);
     1696}
     1697
     1698.chathearth-settings .chathearth-kb-pagination .button[disabled] {
     1699        cursor: not-allowed;
     1700}
     1701
     1702@media (max-width: 782px) {
     1703
     1704        .chathearth-settings .chathearth-table {
     1705                min-inline-size: 640px;
     1706        }
     1707
     1708        .chathearth-settings .chathearth-kb-toolbar,
     1709        .chathearth-settings .chathearth-kb-filters {
     1710                inline-size: 100%;
     1711        }
     1712
     1713        .chathearth-settings #chathearth-kb-search {
     1714                inline-size: 100%;
     1715                max-inline-size: none;
     1716        }
     1717}
     1718
     1719/* 10. Advanced: system status
     1720   ========================================================================== */
     1721
     1722.chathearth-settings .chathearth-status-list {
     1723        display: flex;
     1724        flex-direction: column;
     1725        gap: 0;
     1726        border: 1px solid var(--chathearth-border);
     1727        border-radius: var(--chathearth-radius-control);
     1728        overflow: hidden;
     1729        margin-block-end: var(--chathearth-space-4);
     1730}
     1731
     1732.chathearth-settings .chathearth-status {
     1733        display: flex;
     1734        flex-wrap: wrap;
     1735        align-items: center;
     1736        justify-content: space-between;
     1737        gap: var(--chathearth-space-3);
     1738        padding: 10px 14px;
     1739        border-block-end: 1px solid var(--chathearth-border);
     1740        background: var(--chathearth-surface);
     1741}
     1742
     1743.chathearth-settings .chathearth-status:last-child {
     1744        border-block-end: 0;
     1745}
     1746
     1747.chathearth-settings .chathearth-status__meta {
     1748        display: flex;
     1749        align-items: center;
     1750        gap: var(--chathearth-space-3);
     1751}
     1752
     1753.chathearth-settings .chathearth-status__label {
     1754        font-weight: 500;
     1755}
     1756
     1757.chathearth-settings .chathearth-status__result {
     1758        display: flex;
     1759        align-items: center;
     1760        gap: var(--chathearth-space-3);
     1761}
     1762
     1763.chathearth-settings .chathearth-status__fix {
     1764        font-size: 12px;
     1765}
     1766
     1767/* 11. Sticky save bar
     1768   ========================================================================== */
     1769
     1770.chathearth-settings .chathearth-savebar {
     1771        position: sticky;
     1772        inset-block-end: 0;
     1773        z-index: 30;
     1774        display: flex;
     1775        flex-wrap: wrap;
     1776        align-items: center;
     1777        justify-content: space-between;
     1778        gap: var(--chathearth-space-3);
     1779        margin-block-start: var(--chathearth-space-6);
     1780        padding: var(--chathearth-space-4) var(--chathearth-space-5);
     1781        border: 1px solid var(--chathearth-border);
     1782        border-radius: var(--chathearth-radius-card);
     1783        background: var(--chathearth-surface);
     1784        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
     1785}
     1786
     1787.chathearth-settings .chathearth-savebar__status {
     1788        display: flex;
     1789        align-items: center;
     1790        gap: var(--chathearth-space-2);
     1791        color: var(--chathearth-text-muted);
     1792        font-size: 13px;
     1793}
     1794
     1795.chathearth-settings #chathearth-dirty {
     1796        color: var(--chathearth-warning-text);
     1797        font-weight: 600;
     1798}
     1799
     1800.chathearth-settings #chathearth-dirty::before {
     1801        content: "";
     1802        display: inline-block;
     1803        inline-size: 8px;
     1804        block-size: 8px;
     1805        margin-inline-end: 6px;
     1806        border-radius: 50%;
     1807        background: var(--chathearth-warning);
     1808}
     1809
     1810.chathearth-settings .chathearth-savebar__actions {
     1811        display: flex;
     1812        align-items: center;
     1813        gap: var(--chathearth-space-3);
     1814}
     1815
     1816/* 12. Responsive breakpoints
     1817   ========================================================================== */
     1818
     1819@media (max-width: 782px) {
     1820
     1821        .chathearth-settings .chathearth-layout {
     1822                grid-template-columns: minmax(0, 1fr);
     1823        }
     1824
     1825        .chathearth-settings .chathearth-tabs {
     1826                position: static;
     1827                overflow-x: auto;
     1828                padding-block-end: 6px;
     1829        }
     1830
     1831        .chathearth-settings .chathearth-tabs [role="tablist"] {
     1832                flex-direction: row;
     1833                inline-size: max-content;
     1834        }
     1835
     1836        .chathearth-settings .chathearth-field {
     1837                flex-direction: column;
     1838                align-items: stretch;
     1839                gap: var(--chathearth-space-2);
     1840        }
     1841
     1842        .chathearth-settings .chathearth-field__label {
     1843                flex: none;
     1844                inline-size: auto;
     1845                max-inline-size: none;
     1846                padding-block-start: 0;
     1847        }
     1848
     1849        .chathearth-settings fieldset.chathearth-field > legend.chathearth-field__label {
     1850                float: none;
     1851                inline-size: auto;
     1852                max-inline-size: none;
     1853                padding-block-start: 0;
     1854                margin-block-end: var(--chathearth-space-2);
     1855        }
     1856
     1857        .chathearth-settings fieldset.chathearth-field > .chathearth-field__control {
     1858                margin-inline-start: 0;
     1859        }
     1860
     1861        .chathearth-settings .chathearth-savebar {
     1862                position: fixed;
     1863                inset-block-end: 0;
     1864                inset-inline: 0;
     1865                margin: 0;
     1866                border-radius: 0;
     1867                border-inline: 0;
     1868                border-block-end: 0;
     1869                box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
     1870        }
     1871}
     1872
     1873@media (max-width: 480px) {
     1874
     1875        .chathearth-settings .chathearth-header {
     1876                flex-direction: column;
     1877                align-items: flex-start;
     1878        }
     1879
     1880        .chathearth-settings .chathearth-savebar {
     1881                flex-direction: column;
     1882                align-items: stretch;
     1883                text-align: center;
     1884        }
     1885
     1886        .chathearth-settings .chathearth-savebar__actions {
     1887                justify-content: flex-end;
     1888        }
     1889}
     1890
     1891/* 13. Reduced motion
     1892   ========================================================================== */
     1893
     1894@media (prefers-reduced-motion: reduce) {
     1895
     1896        .chathearth-settings *,
     1897        .chathearth-settings *::before,
     1898        .chathearth-settings *::after {
     1899                animation-duration: 0.01ms !important;
     1900                animation-iteration-count: 1 !important;
     1901                transition-duration: 0.01ms !important;
     1902        }
     1903}
     1904
     1905/* Connection card */
     1906.chathearth-settings .chathearth-connection {
     1907        display: flex;
     1908        flex-wrap: wrap;
     1909        align-items: center;
     1910        gap: var(--chathearth-space-4);
     1911        padding-block: var(--chathearth-space-2);
     1912}
     1913
     1914.chathearth-settings .chathearth-connection > div {
     1915        flex: 1 1 260px;
     1916}
     1917
     1918.chathearth-settings .chathearth-connection .description {
     1919        margin-block: 4px 0;
     1920}
     1921
     1922/* Text buttons keep enough contrast on every admin colour scheme */
     1923.chathearth-settings .button-link {
     1924        color: color-mix(in srgb, var(--chathearth-accent) 65%, #000);
     1925        text-decoration: underline;
     1926}
     1927
     1928.chathearth-settings .button-link:hover,
     1929.chathearth-settings .button-link:focus {
     1930        color: color-mix(in srgb, var(--chathearth-accent) 50%, #000);
     1931}
  • chathearth/trunk/assets/css/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/assets/images/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/assets/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/assets/js/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/chathearth.php

    r3673790 r3833468  
    22/**
    33 * Plugin Name:       ChatHearth - AI Chatbot
    4  * Description:       Site-wide AI chatbot powered by WordPress Connectors (OpenAI in v1).
    5  * Version:           1.4.9
     4 * Description:       Site-wide AI chatbot for WordPress, powered by the AI Provider for OpenAI plugin.
     5 * Version:           2.0.0
    66 * Requires at least: 7.0
    77 * Requires PHP:      7.4
    88 * Requires Plugins:  ai-provider-for-openai
     9 * WC requires at least: 11.3
     10 * WC tested up to:  11.3
    911 * Author:            PalWP
    1012 * Author URI:        https://palwp.com/
    … …  
    1416 * Domain Path:       /languages
    1517 *
     18 * Until the version gate below, this file only uses syntax that PHP 5.6 can parse, so a site on an old
     19 * PHP sees the unsupported-version notice instead of a fatal error.
     20 *
    1621 * @package ChatHearth
    1722 */
    18 
    19 declare(strict_types=1);
    2023
    2124if ( ! defined( 'ABSPATH' ) ) {
    … …  
    2326}
    2427
    25 define( 'CHATHEARTH_VERSION', '1.4.9' );
     28define( 'CHATHEARTH_VERSION', '2.0.0' );
    2629define( 'CHATHEARTH_FILE', __FILE__ );
    2730define( 'CHATHEARTH_PATH', plugin_dir_path( __FILE__ ) );
    … …  
    2932define( 'CHATHEARTH_BASENAME', plugin_basename( __FILE__ ) );
    3033
    31 /** Fixed default OpenAI model for v1 (not exposed in settings). */
    32 define( 'CHATHEARTH_DEFAULT_MODEL', 'gpt-4.1' );
     34// The model used when the site has not chosen one; a site may define it first in wp-config.php.
     35if ( ! defined( 'CHATHEARTH_DEFAULT_MODEL' ) ) {
     36        define( 'CHATHEARTH_DEFAULT_MODEL', 'gpt-6.1-terra' );
     37}
     38
     39/**
     40 * Prints the notice for a site that runs an unsupported WordPress or PHP version (FR-001).
     41 *
     42 * Kept here, in plain PHP, so it works on any PHP version: nothing else of the plugin is loaded then.
     43 *
     44 * @param array<string, array{required: string, current: string}> $unmet Requirement name => versions, from ChatHearth\Requirements.
     45 * @return void
     46 */
     47function chathearth_render_unsupported_notice( $unmet ) {
     48        if ( ! current_user_can( 'manage_options' ) ) {
     49                return;
     50        }
     51
     52        $labels = array(
     53                'wordpress' => 'WordPress',
     54                'php'       => 'PHP',
     55        );
     56        $parts  = array();
     57        foreach ( $unmet as $name => $versions ) {
     58                $parts[] = sprintf(
     59                        /* translators: 1: software name (WordPress or PHP), 2: required version, 3: installed version. */
     60                        __( '%1$s %2$s or newer (this site runs %3$s)', 'chathearth' ),
     61                        isset( $labels[ $name ] ) ? $labels[ $name ] : $name,
     62                        $versions['required'],
     63                        $versions['current']
     64                );
     65        }
     66
     67        echo '<div class="notice notice-error"><p>';
     68        echo esc_html(
     69                sprintf(
     70                        /* translators: %s: the unmet requirements, for example "PHP 7.4 or newer (this site runs 7.3.33)". */
     71                        __( 'ChatHearth - AI Chatbot needs %s. The plugin stays inactive until the site is updated.', 'chathearth' ),
     72                        implode( ', ', $parts )
     73                )
     74        );
     75        echo '</p></div>';
     76}
     77
     78require_once CHATHEARTH_PATH . 'includes/class-requirements.php';
     79
     80$chathearth_unmet = ChatHearth\Requirements::unmet(
     81        isset( $GLOBALS['wp_version'] ) ? $GLOBALS['wp_version'] : '0',
     82        PHP_VERSION
     83);
     84
     85if ( ! empty( $chathearth_unmet ) ) {
     86        add_action(
     87                'admin_notices',
     88                function () use ( $chathearth_unmet ) {
     89                        chathearth_render_unsupported_notice( $chathearth_unmet );
     90                }
     91        );
     92        return;
     93}
    3394
    3495require_once CHATHEARTH_PATH . 'includes/class-autoloader.php';
    3596ChatHearth\Autoloader::register();
    3697
    37 register_activation_hook( __FILE__, array( 'ChatHearth\\Plugin', 'activate' ) );
     98register_activation_hook( __FILE__, array( 'ChatHearth\Lifecycle\Activator', 'activate' ) );
     99register_deactivation_hook( __FILE__, array( 'ChatHearth\Lifecycle\Deactivator', 'deactivate' ) );
    38100
    39101add_action(
    40102        'plugins_loaded',
    41         static function () {
    42                 ChatHearth\Plugin::instance()->init();
     103        function () {
     104                ChatHearth\Plugin::instance()->boot();
     105        },
     106        5
     107);
     108
     109// WooCommerce: this plugin reads no order and uses only the cart, so it works with the custom order tables (HPOS) and with
     110// the cart and checkout blocks. Without this declaration WooCommerce lists it as incompatible on a shop that uses them.
     111add_action(
     112        'before_woocommerce_init',
     113        function () {
     114                if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
     115                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', CHATHEARTH_FILE, true );
     116                        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', CHATHEARTH_FILE, true );
     117                }
    43118        }
    44119);
  • chathearth/trunk/includes/Admin/class-admin-notices.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Admin notices (dependencies + abuse escalation).
     3 * Admin notices: readiness (FR-004) and, from the upgrade runner, upgrade failure (FR-016).
     4 *
     5 * The unsupported-version notice lives in chathearth.php, because this class cannot be loaded on a PHP
     6 * version below the plugin's minimum (research R11, R12).
    47 *
    58 * @package ChatHearth
    … …  
    1417}
    1518
    16 use ChatHearth\Plugin;
    17 use ChatHearth\Security\Rate_Limiter;
     19use ChatHearth\Migrations\Migration_Runner;
     20use ChatHearth\Admin\Settings\Abuse_Alert_Actions;
     21use ChatHearth\Admin\Settings\Settings_Page;
     22use ChatHearth\Readiness\Readiness_Checker;
    1823
    1924/**
    20  * Shows admin notices when OpenAI / Connectors are not ready, or abuse escalation fired.
     25 * Shows notices to administrators. Every string is translatable and escaped.
    2126 */
    2227final class Admin_Notices {
    2328
    2429        /**
     30         * @var Readiness_Checker
     31         */
     32        private $checker;
     33
     34        /**
     35         * @param Readiness_Checker $checker Readiness checker.
     36         */
     37        public function __construct( Readiness_Checker $checker ) {
     38                $this->checker = $checker;
     39        }
     40
     41        /**
    2542         * Register hooks.
    2643         */
    2744        public function register(): void {
    2845                add_action( 'admin_notices', array( $this, 'render' ) );
    29                 add_action( 'admin_post_chathearth_dismiss_abuse_alert', array( $this, 'dismiss_abuse_alert' ) );
    30         }
    31 
    32         /**
    33          * Render notices.
     46        }
     47
     48        /**
     49         * Render the notices for the current screen.
    3450         */
    3551        public function render(): void {
    … …  
    3854                }
    3955
     56                $this->render_upgrade_failure();
     57                $this->render_readiness();
    4058                $this->render_abuse_alert();
    41                 $this->render_dependency_notice();
    42         }
    43 
    44         /**
    45          * Notice when OpenAI / Connectors are missing.
    46          */
    47         private function render_dependency_notice(): void {
    48                 if ( Plugin::is_openai_ready() ) {
    49                         return;
    50                 }
    51 
    52                 $connectors_url = admin_url( 'options-connectors.php' );
    53 
    54                 echo '<div class="notice notice-warning"><p>';
    55                 echo esc_html__(
    56                         'ChatHearth - AI Chatbot needs WordPress AI support, the “AI Provider for OpenAI” plugin, and an OpenAI API key under Connectors. The chat icon stays hidden on the site until OpenAI is ready.',
    57                         'chathearth'
     59                $this->render_reenable_outcome();
     60                $this->render_cleared_notice();
     61        }
     62
     63        /** Confirm a counter reset on the plugin's settings screen. The flag only selects this fixed text. */
     64        private function render_cleared_notice(): void {
     65                $screen = get_current_screen();
     66                if ( null === $screen || Settings_Page::HOOK_SUFFIX !== $screen->id || is_network_admin() ) {
     67                        return;
     68                }
     69
     70                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The flag only selects fixed notice text.
     71                $flag = isset( $_GET['chathearth_cleared'] ) && is_string( $_GET['chathearth_cleared'] ) ? sanitize_key( wp_unslash( $_GET['chathearth_cleared'] ) ) : '';
     72                if ( '1' !== $flag ) {
     73                        return;
     74                }
     75
     76                echo '<div class="notice notice-success"><p>' . esc_html__( 'Rate-limit counters cleared.', 'chathearth' ) . '</p></div>';
     77        }
     78
     79        /** Display a fixed recovery message on the plugin's settings screen. */
     80        private function render_reenable_outcome(): void {
     81                $screen = get_current_screen();
     82                if ( null === $screen || Settings_Page::HOOK_SUFFIX !== $screen->id || is_network_admin() ) {
     83                        return;
     84                }
     85
     86                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- The flag only selects fixed notice text.
     87                $flag = isset( $_GET['chathearth_reenable'] ) && is_string( $_GET['chathearth_reenable'] ) ? sanitize_key( wp_unslash( $_GET['chathearth_reenable'] ) ) : '';
     88                switch ( $flag ) {
     89                        case 'done':
     90                                $type    = 'success';
     91                                $message = __( 'The chat is switched back on.', 'chathearth' );
     92                                break;
     93                        case 'already':
     94                                $type    = 'info';
     95                                $message = __( 'The chat is already on.', 'chathearth' );
     96                                break;
     97                        case 'invalid':
     98                                $type    = 'warning';
     99                                $message = __( 'This link has expired or was already used. Switch the chat on in the Protection settings.', 'chathearth' );
     100                                break;
     101                        default:
     102                                return;
     103                }
     104
     105                echo '<div class="notice notice-' . esc_attr( $type ) . '"><p>' . esc_html( $message ) . '</p></div>';
     106        }
     107
     108        /**
     109         * Tell administrators that the settings upgrade could not finish (FR-016). The site keeps working.
     110         */
     111        private function render_upgrade_failure(): void {
     112                if ( ! is_array( get_option( Migration_Runner::ERROR_OPTION, false ) ) ) {
     113                        return;
     114                }
     115
     116                echo '<div class="notice notice-error"><p>' . esc_html__( 'ChatHearth - AI Chatbot could not finish updating its settings. Your site keeps working with your current settings, and the update will be tried again automatically.', 'chathearth' ) . '</p></div>';
     117        }
     118
     119        /**
     120         * Warn when ChatHearth is not ready, naming the missing item. Not shown on network-admin screens.
     121         */
     122        private function render_readiness(): void {
     123                if ( is_network_admin() ) {
     124                        return;
     125                }
     126
     127                $status = $this->checker->status();
     128                if ( $status->is_ready() || array() === $status->missing() ) {
     129                        return;
     130                }
     131
     132                $missing = $status->missing()[0];
     133                $link    = null;
     134                switch ( $missing ) {
     135                        case 'ai_support':
     136                                $message = __( 'ChatHearth - AI Chatbot needs WordPress AI support, which is turned off or unavailable on this site. The chat icon stays hidden until it is available.', 'chathearth' );
     137                                break;
     138                        case 'provider_plugin':
     139                                $message = __( 'ChatHearth - AI Chatbot needs the “AI Provider for OpenAI” plugin to be installed and active. The chat icon stays hidden until it is.', 'chathearth' );
     140                                $link    = array( admin_url( 'plugins.php' ), __( 'Open Plugins', 'chathearth' ) );
     141                                break;
     142                        case 'connector':
     143                                $message = __( 'ChatHearth - AI Chatbot cannot find the OpenAI connector. The chat icon stays hidden until it is available.', 'chathearth' );
     144                                $link    = array( admin_url( 'options-connectors.php' ), __( 'Open Connectors settings', 'chathearth' ) );
     145                                break;
     146                        default:
     147                                $message = __( 'ChatHearth - AI Chatbot needs an OpenAI API key under Connectors. The chat icon stays hidden until one is added.', 'chathearth' );
     148                                $link    = array( admin_url( 'options-connectors.php' ), __( 'Open Connectors settings', 'chathearth' ) );
     149                }
     150
     151                echo '<div class="notice notice-warning"><p>' . esc_html( $message );
     152                if ( null !== $link ) {
     153                        echo ' <a href="' . esc_url( $link[0] ) . '">' . esc_html( $link[1] ) . '</a>';
     154                }
     155                echo '</p></div>';
     156        }
     157
     158        /**
     159         * The abuse alert written by the rate limiter (the 1.4.9 option): hits and, when the chat was switched off
     160         * automatically, a link to switch it back on. A missing or `time`-less alert shows nothing; values are cast and
     161         * escaped, so a hostile alert can only produce plain text. Not shown on network-admin screens.
     162         */
     163        private function render_abuse_alert(): void {
     164                if ( is_network_admin() ) {
     165                        return;
     166                }
     167                $alert = get_option( Settings_Page::ABUSE_ALERT, false );
     168                if ( ! is_array( $alert ) || ! isset( $alert['time'] ) ) {
     169                        return;
     170                }
     171
     172                $hits = isset( $alert['incidents'] ) && is_numeric( $alert['incidents'] ) ? max( 0, (int) $alert['incidents'] ) : 0;
     173                $auto = ! empty( $alert['auto_disabled'] );
     174
     175                $review  = add_query_arg(
     176                        array(
     177                                'page'    => Settings_Page::SLUG,
     178                                'tab'     => 'protection',
     179                                'section' => 'escalation',
     180                        ),
     181                        admin_url( 'options-general.php' )
    58182                );
    59                 echo ' <a href="' . esc_url( $connectors_url ) . '">' . esc_html__( 'Open Connectors settings', 'chathearth' ) . '</a>';
    60                 echo '</p></div>';
    61         }
    62 
    63         /**
    64          * Notice after global rate-limit escalation.
    65          */
    66         private function render_abuse_alert(): void {
    67                 $alert = get_option( Rate_Limiter::ABUSE_ALERT_OPTION, null );
    68                 if ( ! is_array( $alert ) || empty( $alert['time'] ) ) {
    69                         return;
    70                 }
    71 
    72                 $settings_url = admin_url( 'options-general.php?page=chathearth&tab=protection' );
    73                 $dismiss_url  = wp_nonce_url(
    74                         admin_url( 'admin-post.php?action=chathearth_dismiss_abuse_alert' ),
    75                         'chathearth_dismiss_abuse_alert'
    76                 );
    77 
    78                 $incidents = isset( $alert['incidents'] ) ? (int) $alert['incidents'] : 0;
    79 
    80                 echo '<div class="notice notice-error"><p>';
    81                 echo esc_html__(
    82                         'ChatHearth - AI Chatbot: global rate limits were hit repeatedly (possible multi-IP abuse).',
    83                         'chathearth'
    84                 );
    85                 if ( $incidents > 0 ) {
    86                         echo ' ';
    87                         echo esc_html(
    88                                 sprintf(
    89                                         /* translators: %d: number of hits */
    90                                         __( 'Recorded hits in the window: %d.', 'chathearth' ),
    91                                         $incidents
    92                                 )
    93                         );
    94                 }
    95                 if ( ! empty( $alert['auto_disabled'] ) ) {
    96                         echo ' ';
    97                         echo esc_html__( 'The chatbot was automatically disabled.', 'chathearth' );
    98                 }
    99                 echo ' <a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Open Protection settings', 'chathearth' ) . '</a>';
    100                 echo ' | <a href="' . esc_url( $dismiss_url ) . '">' . esc_html__( 'Dismiss', 'chathearth' ) . '</a>';
    101                 echo '</p></div>';
    102         }
    103 
    104         /**
    105          * Dismiss the abuse alert notice.
    106          */
    107         public function dismiss_abuse_alert(): void {
    108                 if ( ! current_user_can( 'manage_options' ) ) {
    109                         wp_die( esc_html__( 'Sorry, you are not allowed to do that.', 'chathearth' ) );
    110                 }
    111 
    112                 check_admin_referer( 'chathearth_dismiss_abuse_alert' );
    113                 delete_option( Rate_Limiter::ABUSE_ALERT_OPTION );
    114 
    115                 $redirect = wp_get_referer();
    116                 if ( ! is_string( $redirect ) || '' === $redirect ) {
    117                         $redirect = admin_url( 'options-general.php?page=chathearth&tab=protection' );
    118                 }
    119 
    120                 wp_safe_redirect( $redirect );
    121                 exit;
     183                $action  = static function ( string $name ): string {
     184                        return wp_nonce_url( admin_url( 'admin-post.php?action=' . $name ), $name );
     185                };
     186                $message = esc_html__( 'Site-wide rate limits were hit repeatedly (possible abuse).', 'chathearth' ) . ' '
     187                        /* translators: %s: number of recorded rate-limit hits. */
     188                        . esc_html( sprintf( _n( 'Recorded hit: %s.', 'Recorded hits: %s.', $hits, 'chathearth' ), number_format_i18n( $hits ) ) );
     189                if ( $auto ) {
     190                        $message .= ' ' . esc_html__( 'The chat was switched off automatically.', 'chathearth' );
     191                }
     192
     193                $links = array();
     194                if ( $auto ) {
     195                        $links[] = '<a href="' . esc_url( $action( Abuse_Alert_Actions::ENABLE ) ) . '">' . esc_html__( 'Switch chat back on', 'chathearth' ) . '</a>';
     196                }
     197                $links[] = '<a href="' . esc_url( $review ) . '">' . esc_html__( 'Review protection settings', 'chathearth' ) . '</a>';
     198                $links[] = '<a href="' . esc_url( $action( Abuse_Alert_Actions::DISMISS ) ) . '">' . esc_html__( 'Dismiss', 'chathearth' ) . '</a>';
     199
     200                echo '<div class="notice notice-error"><p>' . $message . '</p><p>' . implode( ' · ', $links ) . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Every part is escaped above.
    122201        }
    123202}
  • chathearth/trunk/includes/Admin/class-privacy.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Privacy Policy suggested content.
     3 * Suggested text for Settings → Privacy Policy (interface layer; research R12, FR-033).
     4 *
     5 * Ported from 1.4.9 and extended for the 2.0 data flows. Every item starts by saying when it applies.
    46 *
    57 * @package ChatHearth
    … …  
    1517
    1618/**
    17  * Registers suggested text for Settings → Privacy Policy.
     19 * Registers the suggested privacy-policy text.
    1820 */
    1921final class Privacy {
    2022
    2123        /**
    22          * Register hooks.
     24         * Hooks the registration to `admin_init`, where WordPress expects it.
    2325         */
    2426        public function register(): void {
    … …  
    2729
    2830        /**
    29          * Suggest privacy policy text describing chatbot data flows.
     31         * The suggested items, one per data flow.
     32         *
     33         * @return string[]
     34         */
     35        private function items(): array {
     36                $items = array(
     37                        __( 'Always, when a visitor sends a message: the message and the recent conversation history of that chat are sent to OpenAI, through the AI provider set up in WordPress (Connectors), so a reply can be generated.', 'chathearth' ),
     38                        __( 'Always, when a visitor sends a message: a short summary of this site’s public pages (and, with WooCommerce, the store and its product categories) and the public content of the page the visitor is on are sent to the AI provider together with the instructions, so the answer is about this site. Drafts, private and password-protected content are never sent, and the page is read as a guest sees it.', 'chathearth' ),
     39                        __( 'Always: the conversation history of the chat is kept in the visitor’s browser (local storage) and removed after 24 hours without a new message, or sooner when the visitor clears the chat. The plugin does not store chat transcripts in the WordPress database.', 'chathearth' ),
     40                        __( 'Always: the visitor’s IP address is used for a short time for rate limits, for blocking the addresses you list and for abuse protection. IPv6 visitors are counted per network block. Visitors behind a proxy share a limit until trusted proxies are set up. The counters are short-lived and are not a chat log.', 'chathearth' ),
     41                        __( 'When you list blocked addresses: the addresses and ranges you enter are stored in the plugin’s settings and compared with each visitor’s address. Visitors’ addresses are not stored.', 'chathearth' ),
     42                        __( 'When “Separate limits for logged-in users” is on: the visitor’s WordPress user account is used to count their messages, so the limits follow the person and not their network.', 'chathearth' ),
     43                        __( 'When the bot trap is on: an invisible form field is added to the chat. Only automated programs fill it in, and the result is used to refuse their requests. Visitors never see it.', 'chathearth' ),
     44                        __( 'When content moderation uses OpenAI: the new message and up to two earlier visitor messages of the same chat (never the assistant’s replies) are also sent to OpenAI’s moderation service before a reply is generated, so harmful or disallowed content can be blocked. Only texts not checked in the last 24 hours are sent. The result is remembered for 24 hours as a salted hash, never as text.', 'chathearth' ),
     45                        __( 'When both Google reCAPTCHA v3 keys are set: Google is contacted only after the visitor presses Continue. Google processes a score-based check and related technical data such as the IP address, under Google’s privacy policy. The HTTP-only chathearth_human cookie lasts at most 60 minutes and is used only to skip repeated checks.', 'chathearth' ),
     46                        __( 'When the Knowledge Base is on and OpenAI is connected: the public content selected in the Knowledge Base settings is sent to the OpenAI embeddings service when it is indexed and when it changes, and each visitor question is sent to the OpenAI embeddings service to find matching passages. ChatHearth does not store the question for this. The index holds only this public site content and its numeric representations (embeddings), stored in the WordPress database of this site, with no visitor or account data, so there is nothing in it to export or erase for a person. Markdown copies of the selected content can be kept in the uploads folder of this site.', 'chathearth' ),
     47                        __( 'Always: ChatHearth does not track visitors. It sets no tracking cookies and sends no analytics.', 'chathearth' ),
     48                        __( 'Always: ChatHearth does not store the AI provider key. That credential is managed by WordPress Connectors or the server environment.', 'chathearth' ),
     49                        __( 'Always: the summary of this site’s public pages that goes with a message is kept on this site for up to 12 hours, so the next messages do not rebuild it.', 'chathearth' ),
     50                        __( 'Always: the rate-limit counters of a visitor’s network or account are kept only for the length of the limit window and are not a chat log.', 'chathearth' ),
     51                        __( 'When the Knowledge Base is on: the index stays in the WordPress database of this site until you delete an item, turn the Knowledge Base off or delete the plugin, and the markdown copies in the uploads folder are removed when you turn the setting off or delete the plugin.', 'chathearth' ),
     52                        __( 'When site-wide rate limits are hit repeatedly: the plugin keeps an abuse alert in this site’s options, with the number of hits and whether the chat was switched off, and shows it to administrators until you dismiss it. It holds no visitor data.', 'chathearth' ),
     53                        __( 'When WP_DEBUG_LOG is already on in your site’s configuration: the plugin writes short failure codes to the PHP error log, and never message text, addresses or keys.', 'chathearth' ),
     54                        __( 'Always: the plugin sets no tracking or analytics cookie, sends no analytics or telemetry request and keeps no visitor identifier beyond the stores described here.', 'chathearth' ),
     55                );
     56
     57                // The shop item only appears on a site that has a shop (feature 013, FR-025): the Add to cart sentence of feature 009
     58                // and the one about the product facts that go to the AI provider with the question.
     59                if ( class_exists( 'WooCommerce' ) ) {
     60                        array_splice(
     61                                $items,
     62                                10,
     63                                0,
     64                                array(
     65                                        __( 'When WooCommerce is active and the assistant shows product cards: the Add to cart button of a product card in the chat uses the WooCommerce cart on this site. Payment still happens at the store checkout.', 'chathearth' ) . ' ' .
     66                                        __( 'The facts of the products named in a message or found in the knowledge base (name, price, stock, categories, attributes and short description) are sent to the AI provider with the question.', 'chathearth' ),
     67                                )
     68                        );
     69                }
     70
     71                return $items;
     72        }
     73
     74        /**
     75         * Suggests the privacy-policy text.
    3076         */
    3177        public function add_privacy_policy_content(): void {
    … …  
    3480                }
    3581
    36                 $content = '<p>' . esc_html__(
    37                         'ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this site. When someone uses the chatbot, the following may apply:',
    38                         'chathearth'
    39                 ) . '</p>';
     82                $content = '<p>' . esc_html__( 'ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this site. Depending on how the chatbot is set up, the following may apply:', 'chathearth' ) . '</p><ul>';
     83                foreach ( $this->items() as $item ) {
     84                        $content .= '<li>' . esc_html( $item ) . '</li>';
     85                }
     86                $content .= '</ul><p>' . esc_html__( 'Site owners should read the privacy policy of their AI provider (and of Google, if reCAPTCHA is used) and make sure this section matches how the chatbot is set up on their site.', 'chathearth' ) . '</p>';
    4087
    41                 $content .= '<ul>';
    42                 $content .= '<li>' . esc_html__(
    43                         'Message text and recent conversation history from the chat session are sent to a third-party AI provider (OpenAI in the current version) through WordPress Connectors / the site’s configured AI provider, so a reply can be generated.',
    44                         'chathearth'
    45                 ) . '</li>';
    46                 $content .= '<li>' . esc_html__(
    47                         'Conversation history for the widget is stored in the visitor’s browser (local storage). The plugin does not store chat transcripts in the WordPress database in the current version.',
    48                         'chathearth'
    49                 ) . '</li>';
    50                 $content .= '<li>' . esc_html__(
    51                         'The visitor’s IP address may be used temporarily for rate limiting and abuse protection. Related counters are short-lived and are not kept as a chat log.',
    52                         'chathearth'
    53                 ) . '</li>';
    54                 $content .= '<li>' . esc_html__(
    55                         'If content moderation is enabled, message text (and prior user turns from the chat session) may also be sent to OpenAI’s Moderations API before a chat reply is generated, so harmful or disallowed content can be blocked.',
    56                         'chathearth'
    57                 ) . '</li>';
    58                 $content .= '<li>' . esc_html__(
    59                         'If Google reCAPTCHA v3 is enabled in the chatbot settings, Google may process a score-based challenge (and related technical data such as IP address) according to Google’s privacy policy. Visitors see a verification overlay on the chat window until Google accepts the request.',
    60                         'chathearth'
    61                 ) . '</li>';
    62                 $content .= '<li>' . esc_html__(
    63                         'If knowledge retrieval (RAG) is enabled, visitor questions are embedded and compared to indexed website content. Generated markdown copies of selected pages, posts, products, and taxonomies are stored on this site. Embeddings are stored in the WordPress database. The OpenAI Embeddings API may be used (via the Connectors key) to create those vectors.',
    64                         'chathearth'
    65                 ) . '</li>';
    66                 $content .= '<li>' . esc_html__(
    67                         'If a visitor adds a product to the cart from the chat widget, that action uses the WooCommerce cart on this site. Payment still happens on the store checkout.',
    68                         'chathearth'
    69                 ) . '</li>';
    70                 $content .= '<li>' . esc_html__(
    71                         'This plugin does not store the AI provider API key; that credential is managed through WordPress Connectors or the server environment.',
    72                         'chathearth'
    73                 ) . '</li>';
    74                 $content .= '</ul>';
    75 
    76                 $content .= '<p>' . esc_html__(
    77                         'Site owners should review the privacy policy of their chosen AI provider (and Google, if reCAPTCHA is used) and ensure this section matches how the chatbot is configured on their site.',
    78                         'chathearth'
    79                 ) . '</p>';
    80 
    81                 wp_add_privacy_policy_content(
    82                         __( 'ChatHearth - AI Chatbot', 'chathearth' ),
    83                         wp_kses_post( $content )
    84                 );
     88                wp_add_privacy_policy_content( __( 'ChatHearth - AI Chatbot', 'chathearth' ), wp_kses_post( $content ) );
    8589        }
    8690}
  • chathearth/trunk/includes/Admin/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/includes/Ai/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/includes/Commerce/class-cart-service.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Add WooCommerce products to the visitor cart from chat.
     3 * Adds a product to the shop's cart for the chat (feature 013, research R7, R8; FR-013 to FR-017).
     4 *
     5 * It keeps the 1.4.9 error codes and texts and closes the 1.4.9 gaps: only published, public products count, an option
     6 * must belong to its product and be one the chat offers, and a refused attempt leaves the cart and the shop's notices as
     7 * they were. The shop's session starts only after a successful add. Nothing is logged but the class of an exception: never a
     8 * product name, a cart key or an address.
    49 *
    510 * @package ChatHearth
    … …  
    1419}
    1520
    16 use WP_Error;
     21use ChatHearth\Logger;
    1722
    1823/**
    19  * Thin wrapper around WC()->cart.
     24 * Checks and adds. It holds services only, never request state.
    2025 */
    2126final class Cart_Service {
    2227
    2328        /**
    24          * Whether cart operations can run.
    25          */
    26         public static function is_available(): bool {
    27                 return class_exists( 'WooCommerce' ) && function_exists( 'WC' ) && function_exists( 'wc_get_product' );
    28         }
    29 
    30         /**
    31          * Cart URL when WooCommerce is active.
    32          */
    33         public static function cart_url(): string {
    34                 if ( function_exists( 'wc_get_cart_url' ) ) {
    35                         return (string) wc_get_cart_url();
    36                 }
    37 
    38                 return home_url( '/' );
    39         }
    40 
    41         /**
    42          * Checkout URL when WooCommerce is active.
    43          */
    44         public static function checkout_url(): string {
    45                 if ( function_exists( 'wc_get_checkout_url' ) ) {
    46                         return (string) wc_get_checkout_url();
    47                 }
    48 
    49                 return home_url( '/' );
    50         }
    51 
    52         /**
    53          * Add a product to the current visitor cart.
     29         * Most units of a product one request adds.
     30         */
     31        public const MAX_QUANTITY = 99;
     32
     33        /**
     34         * @var Product_Catalog
     35         */
     36        private $catalog;
     37
     38        /**
     39         * @var Product_Card
     40         */
     41        private $card;
     42
     43        /**
     44         * @param Product_Catalog $catalog Says whether WooCommerce is active.
     45         * @param Product_Card    $card    The card the reply carries, and the options the chat offers.
     46         */
     47        public function __construct( Product_Catalog $catalog, Product_Card $card ) {
     48                $this->catalog = $catalog;
     49                $this->card    = $card;
     50        }
     51
     52        /**
     53         * Whether WooCommerce is active and its cart could be loaded for this request. Loading the cart starts no shop session
     54         * cookie for a guest.
     55         */
     56        public function load(): bool {
     57                if ( ! $this->catalog->is_available() || ! function_exists( 'wc_load_cart' ) ) {
     58                        return false;
     59                }
     60
     61                try {
     62                        wc_load_cart();
     63                } catch ( \Throwable $e ) {
     64                        Logger::warning( 'cart_unavailable', array( 'exception' => get_class( $e ) ) );
     65
     66                        return false;
     67                }
     68
     69                if ( ! function_exists( 'WC' ) || ! is_object( WC()->cart ) ) {
     70                        return false;
     71                }
     72
     73                // A REST request runs after the shop has loaded carts from sessions, so the saved cart is read here: without this the
     74                // cart is empty in memory and an add would replace what the guest already had.
     75                WC()->cart->get_cart();
     76
     77                return true;
     78        }
     79
     80        /**
     81         * Add one product, or one option of a variable product.
    5482         *
    5583         * @param int $product_id   Product id.
    56          * @param int $quantity     Quantity.
    57          * @param int $variation_id Optional variation.
    58          * @return array<string, mixed>|WP_Error
    59          */
    60         public function add( int $product_id, int $quantity = 1, int $variation_id = 0 ) {
    61                 if ( ! self::is_available() ) {
    62                         return new WP_Error(
    63                                 'chathearth_cart_unavailable',
    64                                 __( 'The store cart is not available.', 'chathearth' ),
    65                                 array( 'status' => 400 )
    66                         );
    67                 }
    68 
    69                 $quantity = max( 1, min( 99, $quantity ) );
    70                 $product  = wc_get_product( $variation_id > 0 ? $variation_id : $product_id );
    71                 if ( ! is_object( $product ) || ! method_exists( $product, 'is_purchasable' ) ) {
    72                         return new WP_Error(
    73                                 'chathearth_cart_product',
    74                                 __( 'That product is not available.', 'chathearth' ),
    75                                 array( 'status' => 404 )
    76                         );
    77                 }
    78 
    79                 if ( ! $product->is_purchasable() || ( method_exists( $product, 'is_in_stock' ) && ! $product->is_in_stock() ) ) {
    80                         return new WP_Error(
    81                                 'chathearth_cart_product',
    82                                 __( 'That product cannot be added to the cart.', 'chathearth' ),
    83                                 array( 'status' => 400 )
    84                         );
    85                 }
    86 
    87                 if ( function_exists( 'wc_load_cart' ) ) {
    88                         wc_load_cart();
    89                 }
    90 
    91                 if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
    92                         return new WP_Error(
    93                                 'chathearth_cart_unavailable',
    94                                 __( 'The store cart is not available.', 'chathearth' ),
    95                                 array( 'status' => 400 )
    96                         );
    97                 }
    98 
    99                 $added = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id );
    100                 if ( ! $added ) {
    101                         return new WP_Error(
     84         * @param int $quantity     Units; kept between 1 and 99.
     85         * @param int $variation_id Option id, or 0.
     86         * @return array<string, mixed>|\WP_Error The 1.4.9 reply, or the refusal.
     87         */
     88        public function add( int $product_id, int $quantity, int $variation_id ) {
     89                $quantity = max( 1, min( self::MAX_QUANTITY, $quantity ) );
     90
     91                $post = get_post( $product_id );
     92                if ( ! $post instanceof \WP_Post || 'product' !== $post->post_type || 'publish' !== $post->post_status || '' !== $post->post_password ) {
     93                        return $this->not_available();
     94                }
     95                $card = $this->card->for_product( $product_id, true );
     96                if ( null === $card ) {
     97                        return $this->not_available();
     98                }
     99                if ( $variation_id > 0 && ! $this->is_option_of( $variation_id, $product_id ) ) {
     100                        return $this->not_available();
     101                }
     102
     103                if ( empty( $card['purchasable'] ) || ! $this->is_offered( $card, $variation_id ) ) {
     104                        return $this->cannot_add();
     105                }
     106
     107                $attributes = $variation_id > 0 ? wc_get_product_variation_attributes( $variation_id ) : array();
     108                $key        = $this->shop_add( $product_id, $quantity, $variation_id, $attributes );
     109                if ( '' === $key ) {
     110                        if ( function_exists( 'wc_clear_notices' ) ) {
     111                                wc_clear_notices();
     112                        }
     113
     114                        return new \WP_Error(
    102115                                'chathearth_cart_failed',
    103116                                __( 'Could not add that product to the cart.', 'chathearth' ),
    … …  
    106119                }
    107120
     121                $this->start_guest_session();
     122
    108123                return array(
    109124                        'added'        => true,
    110                         'key'          => (string) $added,
     125                        'key'          => $key,
    111126                        'cart_count'   => (int) WC()->cart->get_cart_contents_count(),
    112                         'cart_url'     => self::cart_url(),
    113                         'checkout_url' => self::checkout_url(),
     127                        'cart_url'     => (string) wc_get_cart_url(),
     128                        'checkout_url' => (string) wc_get_checkout_url(),
    114129                        'product_id'   => $product_id,
    115130                        'variation_id' => $variation_id,
    116131                        'quantity'     => $quantity,
     132                        'product'      => $card,
    117133                );
    118134        }
     135
     136        /**
     137         * Whether an option is a published option of the product.
     138         *
     139         * @param int $variation_id Option id.
     140         * @param int $product_id   Product id.
     141         */
     142        private function is_option_of( int $variation_id, int $product_id ): bool {
     143                $variation = wc_get_product( $variation_id );
     144
     145                return is_object( $variation )
     146                        && 'variation' === $variation->get_type()
     147                        && (int) $variation->get_parent_id() === $product_id
     148                        && 'publish' === get_post_status( $variation_id );
     149        }
     150
     151        /**
     152         * Whether the chat offers what was asked: a simple product as it is, a variable product only through an option it
     153         * lists that is in stock.
     154         *
     155         * @param array<string, mixed> $card         The product's card.
     156         * @param int                  $variation_id Option id, or 0.
     157         */
     158        private function is_offered( array $card, int $variation_id ): bool {
     159                if ( 'variable' !== ( $card['type'] ?? '' ) ) {
     160                        return 0 === $variation_id;
     161                }
     162
     163                foreach ( (array) ( $card['variations'] ?? array() ) as $option ) {
     164                        if ( (int) $option['id'] === $variation_id ) {
     165                                return ! empty( $option['is_in_stock'] );
     166                        }
     167                }
     168
     169                return false;
     170        }
     171
     172        /**
     173         * The shop's own add. Any exception, and any refusal, gives an empty key.
     174         *
     175         * @param int                  $product_id   Product id.
     176         * @param int                  $quantity     Units.
     177         * @param int                  $variation_id Option id, or 0.
     178         * @param array<string,string> $attributes   Attributes of the option.
     179         * @return string The cart key, or an empty string.
     180         */
     181        private function shop_add( int $product_id, int $quantity, int $variation_id, array $attributes ): string {
     182                try {
     183                        // The shop's own validation hook, as its add-to-cart form runs it, so a store's rules (minimum quantity, one per
     184                        // customer and so on) apply here too. WooCommerce's cart does not run it by itself.
     185                        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- A WooCommerce hook.
     186                        if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $attributes ) ) {
     187                                Logger::warning( 'cart_failed' );
     188
     189                                return '';
     190                        }
     191
     192                        $key = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $attributes );
     193                } catch ( \Throwable $e ) {
     194                        Logger::warning( 'cart_failed', array( 'exception' => get_class( $e ) ) );
     195
     196                        return '';
     197                }
     198                if ( ! is_string( $key ) || '' === $key ) {
     199                        Logger::warning( 'cart_failed' );
     200
     201                        return '';
     202                }
     203
     204                return $key;
     205        }
     206
     207        /**
     208         * Gives the guest a shop session, in this request. The shop sets its cookies on `wp` or at shutdown, which is too late
     209         * for a REST reply, so a guest's first add would be lost.
     210         */
     211        private function start_guest_session(): void {
     212                if ( is_object( WC()->session ) && method_exists( WC()->session, 'set_customer_session_cookie' ) ) {
     213                        WC()->session->set_customer_session_cookie( true );
     214                }
     215                WC()->cart->maybe_set_cart_cookies();
     216        }
     217
     218        /**
     219         * The 1.4.9 404.
     220         */
     221        private function not_available(): \WP_Error {
     222                return new \WP_Error(
     223                        'chathearth_cart_product',
     224                        __( 'That product is not available.', 'chathearth' ),
     225                        array( 'status' => 404 )
     226                );
     227        }
     228
     229        /**
     230         * The 1.4.9 400 for a product that exists but cannot be added.
     231         */
     232        private function cannot_add(): \WP_Error {
     233                return new \WP_Error(
     234                        'chathearth_cart_product',
     235                        __( 'That product cannot be added to the cart.', 'chathearth' ),
     236                        array( 'status' => 400 )
     237                );
     238        }
    119239}
  • chathearth/trunk/includes/Commerce/class-product-catalog.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Public product payload for chat cards and cart.
     3 * What the chat knows about shop products (feature 013, research R1, R3, R6).
     4 *
     5 * It keeps nothing between calls (Constitution V): the stage calls `cards_for()` once per message and keeps the cards on the
     6 * `Catalog_Result` of the request. Every WooCommerce call in the feature sits behind `is_available()`.
    47 *
    58 * @package ChatHearth
    … …  
    1417}
    1518
     19use ChatHearth\Rag\Retrieval_Result;
     20
    1621/**
    17  * Read-only product helper (WooCommerce when present).
     22 * Product cards, retrieved product ids and catalogue facts.
    1823 */
    1924final class Product_Catalog {
    2025
    2126        /**
    22          * Whether WooCommerce product APIs are available.
    23          */
    24         public static function is_available(): bool {
    25                 return class_exists( 'WooCommerce' ) && function_exists( 'wc_get_product' );
    26         }
    27 
    28         /**
    29          * Public catalog card, or null.
    30          *
    31          * @param int $product_id Product id.
    32          * @return array<string, mixed>|null
    33          */
    34         public function get_public_product( int $product_id ): ?array {
    35                 if ( $product_id <= 0 || ! self::is_available() ) {
    36                         return null;
    37                 }
    38 
    39                 $product = wc_get_product( $product_id );
    40                 if ( ! is_object( $product ) || ! method_exists( $product, 'get_id' ) ) {
    41                         return null;
    42                 }
    43 
    44                 $status = get_post_status( $product_id );
    45                 if ( 'publish' !== $status ) {
    46                         return null;
    47                 }
    48 
    49                 $name        = method_exists( $product, 'get_name' ) ? (string) $product->get_name() : get_the_title( $product_id );
    50                 $url         = (string) get_permalink( $product_id );
    51                 $price       = $this->format_amount( method_exists( $product, 'get_price' ) ? $product->get_price() : '' );
    52                 $regular     = $this->regular_price_if_on_sale( $product );
    53                 $media       = $this->public_image( $product_id, $product );
    54                 $purchasable = method_exists( $product, 'is_purchasable' ) && method_exists( $product, 'is_in_stock' )
    55                         ? ( $product->is_purchasable() && $product->is_in_stock() )
    56                         : false;
    57 
    58                 $variations = array();
    59                 if ( method_exists( $product, 'is_type' ) && $product->is_type( 'variable' ) && method_exists( $product, 'get_available_variations' ) ) {
    60                         $raw = $product->get_available_variations();
    61                         if ( is_array( $raw ) ) {
    62                                 foreach ( array_slice( $raw, 0, 30 ) as $row ) {
    63                                         if ( ! is_array( $row ) ) {
    64                                                 continue;
    65                                         }
    66                                         $variations[] = array(
    67                                                 'id'          => isset( $row['variation_id'] ) ? (int) $row['variation_id'] : 0,
    68                                                 'price'       => isset( $row['display_price'] ) ? (string) $row['display_price'] : '',
    69                                                 'is_in_stock' => ! empty( $row['is_in_stock'] ),
    70                                                 'attributes'  => isset( $row['attributes'] ) && is_array( $row['attributes'] ) ? $row['attributes'] : array(),
    71                                         );
     27         * Longest short description kept for the assistant.
     28         */
     29        public const MAX_DESCRIPTION = 300;
     30
     31        /**
     32         * @var Product_Card
     33         */
     34        private $card;
     35
     36        /**
     37         * @param Product_Card $card The card builder.
     38         */
     39        public function __construct( Product_Card $card ) {
     40                $this->card = $card;
     41        }
     42
     43        /**
     44         * Whether WooCommerce is active and usable.
     45         */
     46        public function is_available(): bool {
     47                return class_exists( 'WooCommerce' ) && function_exists( 'WC' ) && function_exists( 'wc_get_product' );
     48        }
     49
     50        /**
     51         * The cards of products, in the order given. A product that is not published and public, or cannot be loaded, has no
     52         * card and is left out.
     53         *
     54         * @param int[] $ids Product ids.
     55         * @return array<int, array<string, mixed>>
     56         */
     57        public function cards_for( array $ids ): array {
     58                if ( ! $this->is_available() ) {
     59                        return array();
     60                }
     61
     62                $cards = array();
     63                foreach ( $ids as $id ) {
     64                        $card = $this->card->for_product( (int) $id );
     65                        if ( null !== $card ) {
     66                                $cards[] = $card;
     67                        }
     68                }
     69
     70                return $cards;
     71        }
     72
     73        /**
     74         * The published, password-free products among the retrieved passages, in rank order.
     75         *
     76         * @param Retrieval_Result $result What the search found.
     77         * @return int[]
     78         */
     79        public function retrieved_ids( Retrieval_Result $result ): array {
     80                if ( ! $this->is_available() ) {
     81                        return array();
     82                }
     83
     84                $ids = array();
     85                foreach ( $result->product_ids() as $id ) {
     86                        $post = get_post( $id );
     87                        if ( $post instanceof \WP_Post && 'product' === $post->post_type && 'publish' === $post->post_status && '' === $post->post_password ) {
     88                                $ids[] = (int) $id;
     89                        }
     90                }
     91
     92                return $ids;
     93        }
     94
     95        /**
     96         * The facts of a published product that the catalogue block adds to its card: category names, visible attributes
     97         * (`Name: value, value`) and the short description as plain text. Nothing for a product that is not published.
     98         *
     99         * @param int $id Product id.
     100         * @return array{categories: string[], attributes: string[], short_description: string}
     101         */
     102        public function facts( int $id ): array {
     103                $none = array(
     104                        'categories'        => array(),
     105                        'attributes'        => array(),
     106                        'short_description' => '',
     107                );
     108                if ( ! $this->is_available() ) {
     109                        return $none;
     110                }
     111
     112                $post = get_post( $id );
     113                if ( ! $post instanceof \WP_Post || 'product' !== $post->post_type || 'publish' !== $post->post_status || '' !== $post->post_password ) {
     114                        return $none;
     115                }
     116                $product = function_exists( 'wc_get_product' ) ? wc_get_product( $id ) : null;
     117                if ( ! is_object( $product ) ) {
     118                        return $none;
     119                }
     120
     121                return array(
     122                        'categories'        => $this->categories( $id ),
     123                        'attributes'        => $this->attributes( $product ),
     124                        'short_description' => $this->description( $product ),
     125                );
     126        }
     127
     128        /**
     129         * Category names of a product.
     130         *
     131         * @param int $id Product id.
     132         * @return string[]
     133         */
     134        private function categories( int $id ): array {
     135                $terms = get_the_terms( $id, 'product_cat' );
     136                if ( ! is_array( $terms ) ) {
     137                        return array();
     138                }
     139
     140                $names = array();
     141                foreach ( $terms as $term ) {
     142                        $names[] = html_entity_decode( $term->name, ENT_QUOTES, 'UTF-8' );
     143                }
     144
     145                return $names;
     146        }
     147
     148        /**
     149         * The attributes that are visible on the product page, as `Name: value, value`.
     150         *
     151         * @param object $product WooCommerce product.
     152         * @return string[]
     153         */
     154        private function attributes( $product ): array {
     155                if ( ! method_exists( $product, 'get_attributes' ) ) {
     156                        return array();
     157                }
     158
     159                $lines = array();
     160                foreach ( (array) $product->get_attributes() as $attribute ) {
     161                        if ( ! is_object( $attribute ) || ! method_exists( $attribute, 'get_visible' ) || ! $attribute->get_visible() ) {
     162                                continue;
     163                        }
     164
     165                        $name = (string) $attribute->get_name();
     166                        if ( $attribute->is_taxonomy() ) {
     167                                $values = function_exists( 'wc_get_product_terms' ) ? wc_get_product_terms( (int) $product->get_id(), $name, array( 'fields' => 'names' ) ) : array();
     168                        } else {
     169                                $values = $attribute->get_options();
     170                        }
     171                        $values = array_filter(
     172                                array_map( 'strval', (array) $values ),
     173                                static function ( string $value ): bool {
     174                                        return '' !== $value;
    72175                                }
    73                         }
    74                 }
    75 
    76                 return array(
    77                         'id'            => (int) $product->get_id(),
    78                         'name'          => $name,
    79                         'url'           => $url,
    80                         'image'         => $media['url'],
    81                         'image_alt'     => $media['alt'],
    82                         'price'         => $price,
    83                         'regular_price' => $regular,
    84                         'on_sale'       => '' !== $regular,
    85                         'purchasable'   => $purchasable,
    86                         'in_stock'      => method_exists( $product, 'is_in_stock' ) ? (bool) $product->is_in_stock() : false,
    87                         'type'          => method_exists( $product, 'get_type' ) ? (string) $product->get_type() : 'simple',
    88                         'variations'    => $variations,
    89                 );
    90         }
    91 
    92         /**
    93          * Previous (regular) price when the product is on sale.
     176                        );
     177                        if ( array() === $values ) {
     178                                continue;
     179                        }
     180
     181                        $label   = function_exists( 'wc_attribute_label' ) ? (string) wc_attribute_label( $name, $product ) : $name;
     182                        $lines[] = html_entity_decode( $label, ENT_QUOTES, 'UTF-8' ) . ': ' . html_entity_decode( implode( ', ', $values ), ENT_QUOTES, 'UTF-8' );
     183                }
     184
     185                return $lines;
     186        }
     187
     188        /**
     189         * The short description as plain text on one line, cut to 300 characters.
    94190         *
    95191         * @param object $product WooCommerce product.
    96192         */
    97         private function regular_price_if_on_sale( $product ): string {
    98                 if ( ! method_exists( $product, 'is_on_sale' ) || ! $product->is_on_sale() ) {
     193        private function description( $product ): string {
     194                if ( ! method_exists( $product, 'get_short_description' ) ) {
    99195                        return '';
    100196                }
    101                 if ( ! method_exists( $product, 'get_regular_price' ) ) {
    102                         return '';
    103                 }
    104 
    105                 $regular = $product->get_regular_price();
    106                 $current = method_exists( $product, 'get_price' ) ? $product->get_price() : '';
    107                 if ( '' === (string) $regular || (string) $regular === (string) $current ) {
    108                         return '';
    109                 }
    110 
    111                 return $this->format_amount( $regular );
    112         }
    113 
    114         /**
    115          * Catalog image URL and alt text.
    116          *
    117          * @param int    $product_id Product id.
    118          * @param object $product    WooCommerce product.
    119          * @return array{url:string,alt:string}
    120          */
    121         private function public_image( int $product_id, $product ): array {
    122                 $url = get_the_post_thumbnail_url( $product_id, 'woocommerce_thumbnail' );
    123                 if ( ! is_string( $url ) || '' === $url ) {
    124                         $url = get_the_post_thumbnail_url( $product_id, 'medium' );
    125                 }
    126                 if ( ( ! is_string( $url ) || '' === $url ) && method_exists( $product, 'get_image_id' ) ) {
    127                         $image_id = (int) $product->get_image_id();
    128                         if ( $image_id > 0 ) {
    129                                 $maybe = wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' );
    130                                 $url   = is_string( $maybe ) ? $maybe : '';
    131                         }
    132                 }
    133                 if ( ( ! is_string( $url ) || '' === $url ) && function_exists( 'wc_placeholder_img_src' ) ) {
    134                         $url = (string) wc_placeholder_img_src( 'woocommerce_thumbnail' );
    135                 }
    136 
    137                 $alt      = '';
    138                 $thumb_id = get_post_thumbnail_id( $product_id );
    139                 if ( $thumb_id ) {
    140                         $alt = (string) get_post_meta( (int) $thumb_id, '_wp_attachment_image_alt', true );
    141                 }
    142                 if ( '' === $alt ) {
    143                         $alt = method_exists( $product, 'get_name' ) ? (string) $product->get_name() : '';
    144                 }
    145 
    146                 return array(
    147                         'url' => is_string( $url ) ? $url : '',
    148                         'alt' => $alt,
    149                 );
    150         }
    151 
    152         /**
    153          * Plain-text money for chat cards.
    154          *
    155          * @param mixed $amount Raw amount.
    156          */
    157         private function format_amount( $amount ): string {
    158                 if ( ! is_scalar( $amount ) || '' === (string) $amount ) {
    159                         return '';
    160                 }
    161 
    162                 if ( function_exists( 'wc_price' ) ) {
    163                         $html      = (string) wc_price( $amount );
    164                         $plain     = html_entity_decode( wp_strip_all_tags( $html ), ENT_QUOTES, 'UTF-8' );
    165                         $collapsed = preg_replace( '/\s+/', ' ', $plain );
    166                         if ( ! is_string( $collapsed ) ) {
    167                                 $collapsed = $plain;
    168                         }
    169 
    170                         return trim( $collapsed );
    171                 }
    172 
    173                 return (string) $amount;
    174         }
    175 
    176         /**
    177          * Public products whose names appear in a visitor message.
    178          *
    179          * Used so comparison and add-to-cart cards can appear even when RAG is off
    180          * or retrieval did not return product chunks.
    181          *
    182          * @param string $message Visitor message.
    183          * @param int    $limit   Max products.
    184          * @return list<array<string, mixed>>
    185          */
    186         public function find_mentioned( string $message, int $limit = 6 ): array {
    187                 if ( ! self::is_available() || ! function_exists( 'wc_get_products' ) ) {
    188                         return array();
    189                 }
    190 
    191                 $message = trim( $message );
    192                 if ( '' === $message ) {
    193                         return array();
    194                 }
    195 
    196                 $limit = max( 1, min( 12, $limit ) );
    197                 $ids   = wc_get_products(
    198                         array(
    199                                 'status' => 'publish',
    200                                 'limit'  => 80,
    201                                 'return' => 'ids',
    202                         )
    203                 );
    204 
    205                 $found = array();
    206                 foreach ( $ids as $id ) {
    207                         $card = $this->get_public_product( (int) $id );
    208                         if ( ! is_array( $card ) ) {
    209                                 continue;
    210                         }
    211                         $name = isset( $card['name'] ) ? (string) $card['name'] : '';
    212                         if ( ! self::message_mentions_name( $message, $name ) ) {
    213                                 continue;
    214                         }
    215                         $found[ (int) $id ] = $card;
    216                         if ( count( $found ) >= $limit ) {
    217                                 break;
    218                         }
    219                 }
    220 
    221                 return array_values( $found );
    222         }
    223 
    224         /**
    225          * Whether a product name appears as a whole token in the message.
    226          *
    227          * @param string $message Visitor message.
    228          * @param string $name    Product name.
    229          */
    230         public static function message_mentions_name( string $message, string $name ): bool {
    231                 $name = trim( $name );
    232                 if ( mb_strlen( $name, 'UTF-8' ) < 3 ) {
    233                         return false;
    234                 }
    235 
    236                 $pattern = '/(?<!\p{L})' . preg_quote( $name, '/' ) . '(?!\p{L})/iu';
    237                 return (bool) preg_match( $pattern, $message );
     197
     198                $text = html_entity_decode( wp_strip_all_tags( strip_shortcodes( (string) $product->get_short_description() ) ), ENT_QUOTES, 'UTF-8' );
     199                $text = trim( (string) preg_replace( '/\s+/u', ' ', $text ) );
     200
     201                return mb_substr( $text, 0, self::MAX_DESCRIPTION, 'UTF-8' );
    238202        }
    239203}
  • chathearth/trunk/includes/Commerce/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/includes/Frontend/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/includes/Rag/class-builtin-vector-store.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * In-WordPress cosine-similarity vector store.
     3 * The built-in vector store: the passages table of feature 010, searched in two stages (feature 011, research R3-R5,
     4 * R20; FR-004, FR-005, FR-010, FR-011, FR-021).
     5 *
     6 * 1. Coarse: the first 256 numbers of every vector are read in batches of 2,000 rows and scored; the best 256 are kept
     7 *    in a bounded heap. This only runs for the OpenAI `text-embedding-3` models, whose leading numbers form a smaller
     8 *    embedding of the same text, and for vectors of at least 512 numbers.
     9 * 2. Exact: the full vectors of those candidates are read by id and scored by full cosine.
     10 * Any other model gets the exact scan in batches: correct and bounded in memory, only slower. Every search, in
     11 * either way, stops reading new batches after 2 seconds, uses the best passages found so far and logs `scan_budget`.
     12 * Passages of 1.4.9 that still hold their vector as JSON are scored exactly in a pass of their own.
     13 *
     14 * Database rules: every statement goes through `$wpdb->prepare()`, and each table is the `%i` identifier placeholder with
     15 * the raw name from `Schema` as its value. The question's vector never reaches SQL. The batch queries name the primary key as their index
     16 * (`FORCE INDEX (PRIMARY)`): with the table's statistics known, the optimizer otherwise starts from the entries and sorts
     17 * a temporary table, about seven times slower at 10,000 passages (measured 2026-11-23). Each direct query is annotated with its reason: it
     18 * reads this plugin's own table live, and WordPress never caches it.
    419 *
    520 * @package ChatHearth
    … …  
    1429}
    1530
     31use ChatHearth\Ai\Openai_Embedding_Client;
     32use ChatHearth\Kb\Passage_Repository;
     33use ChatHearth\Logger;
     34
    1635/**
    17  * Uses chunk rows already written by the indexer.
     36 * Searches this plugin's own passages.
    1837 */
    1938final class Builtin_Vector_Store implements Vector_Store_Interface {
    2039
    2140        /**
    22          * Repository.
    23          *
    24          * @var Kb_Repository
    25          */
    26         private $repository;
    27 
    28         /**
    29          * Constructor.
    30          *
    31          * @param Kb_Repository|null $repository Repository.
    32          */
    33         public function __construct( ?Kb_Repository $repository = null ) {
    34                 $this->repository = $repository instanceof Kb_Repository ? $repository : new Kb_Repository();
    35         }
    36 
    37         /**
    38          * Insert or replace records.
    39          *
    40          * @param array $records Records.
     41         * Numbers of each vector read in the coarse stage.
     42         */
     43        public const COARSE_DIMS = 256;
     44
     45        /**
     46         * Passages kept after the coarse stage.
     47         */
     48        public const CANDIDATES = 256;
     49
     50        /**
     51         * Rows of one coarse batch.
     52         */
     53        public const BATCH = 2000;
     54
     55        /**
     56         * Most passages a search returns (as 1.4.9).
     57         */
     58        public const MAX_LIMIT = 20;
     59
     60        /**
     61         * Rows of one batch of the exact scan and of the 1.4.9 JSON pass (their rows are read in full).
     62         */
     63        private const EXACT_BATCH = 500;
     64
     65        /**
     66         * Seconds after which the exact scan stops reading new batches.
     67         */
     68        private const SCAN_BUDGET = 2.0;
     69
     70        /**
     71         * The shortest vector and the model family for which the coarse stage is used.
     72         */
     73        private const COARSE_MIN_DIMS = 512;
     74        private const COARSE_MODELS   = 'text-embedding-3-';
     75
     76        /**
     77         * Returns the time in seconds (replaced in tests).
     78         *
     79         * @var callable
     80         */
     81        private $clock;
     82
     83        /**
     84         * @param callable|null $clock Returns the time in seconds as a float; default: `microtime( true )`.
     85         */
     86        public function __construct( ?callable $clock = null ) {
     87                $this->clock = $clock ?? static function (): float {
     88                        return microtime( true );
     89                };
     90        }
     91
     92        /**
     93         * The sync writes the tables itself (as in 1.4.9), so there is nothing to do.
     94         *
     95         * @param list<array{id:string,embedding:list<float>,content:string,meta:array<string,mixed>}> $records Records.
    4196         */
    4297        public function upsert( array $records ): bool {
    4398                unset( $records );
    44                 // Chunks + embeddings are persisted by the indexer via Kb_Repository::replace_chunks().
     99
    45100                return true;
    46101        }
    47102
    48103        /**
    49          * Delete records by id.
    50          *
    51          * @param array $ids Vector ids.
     104         * The sync writes the tables itself (as in 1.4.9), so there is nothing to do.
     105         *
     106         * @param array<int, string> $ids Ids.
    52107         */
    53108        public function delete( array $ids ): bool {
    54109                unset( $ids );
     110
    55111                return true;
    56112        }
    57113
    58114        /**
    59          * Nearest neighbours.
    60          *
    61          * @param array $embedding Query vector.
    62          * @param int   $limit     Max hits.
    63          * @return array
     115         * Whether the tables are at the current version (FR-021).
     116         */
     117        public function ping(): bool {
     118                return Schema::is_current();
     119        }
     120
     121        /**
     122         * The passages nearest to a question, best first.
     123         *
     124         * @param array<int, float> $embedding The question's vector.
     125         * @param int               $limit     Most passages; 1 to 20.
     126         * @return list<array{id:string,score:float,content:string,meta:array<string,mixed>}>
     127         * @throws \RuntimeException With the message `db_error` when the database fails.
    64128         */
    65129        public function query( array $embedding, int $limit = 5 ): array {
    66                 $limit  = max( 1, min( 20, $limit ) );
    67                 $rows   = $this->repository->all_chunk_embeddings();
    68                 $scored = array();
    69 
     130                $limit = max( 1, min( self::MAX_LIMIT, $limit ) );
     131                $dims  = count( $embedding );
     132                if ( 0 === $dims ) {
     133                        return array();
     134                }
     135
     136                // The question as a list that starts at 1, like the result of unpack().
     137                $question = array();
     138                $norm     = 0.0;
     139                $position = 0;
     140                foreach ( $embedding as $number ) {
     141                        $value = (float) $number;
     142                        if ( ! is_finite( $value ) ) {
     143                                return array();
     144                        }
     145                        $question[ ++$position ] = $value;
     146                        $norm                   += $value * $value;
     147                }
     148                $norm = sqrt( $norm );
     149                if ( $norm <= 0.0 ) {
     150                        return array();
     151                }
     152
     153                $model  = Openai_Embedding_Client::resolve_model();
     154                $legacy = Openai_Embedding_Client::DEFAULT_MODEL === $model;
     155                $final  = new Top_K_Heap( $limit );
     156
     157                if ( $dims >= self::COARSE_MIN_DIMS && 0 === strpos( $model, self::COARSE_MODELS ) ) {
     158                        $candidates = $this->coarse_candidates( $question, $dims, $model, $legacy );
     159                        $this->score_exact( $this->vectors_of( $candidates ), $question, $norm, $dims, $final );
     160                } else {
     161                        $this->scan( $question, $norm, $dims, $model, $legacy, $final );
     162                }
     163
     164                if ( $legacy ) {
     165                        $this->score_json_rows( $question, $norm, $dims, $final );
     166                }
     167
     168                return $this->hits( $final->best_first() );
     169        }
     170
     171        /**
     172         * The coarse stage: ids of the best 256 passages by the first 256 numbers.
     173         *
     174         * @param array<int, float> $question The question, indexed from 1.
     175         * @param int               $dims     Vector length.
     176         * @param string            $model    Current model.
     177         * @param bool              $legacy   Whether rows without a model (1.4.9) count.
     178         * @return int[]
     179         */
     180        private function coarse_candidates( array $question, int $dims, string $model, bool $legacy ): array {
     181                $head      = array_slice( $question, 0, self::COARSE_DIMS, true );
     182                $head_norm = 0.0;
     183                foreach ( $head as $number ) {
     184                        $head_norm += $number * $number;
     185                }
     186                $head_norm = sqrt( $head_norm );
     187                $heap      = new Top_K_Heap( self::CANDIDATES );
     188                if ( $head_norm <= 0.0 ) {
     189                        // The question has no weight in the leading numbers: the coarse scores would all be zero.
     190                        return array();
     191                }
     192
     193                $after   = 0;
     194                $cached  = wp_using_ext_object_cache();
     195                $version = $cached ? Passage_Repository::index_version() : 0;
     196                $started = (float) call_user_func( $this->clock );
     197
     198                do {
     199                        $key  = 'heads:' . $version . ':' . $model . ':' . $dims . ':' . $after;
     200                        $rows = $cached ? wp_cache_get( $key, Passage_Repository::CACHE_GROUP ) : false;
     201                        if ( is_array( $rows ) ) {
     202                                $count = count( $rows );
     203                                $this->score_heads( $rows, $head, $head_norm, $heap, $after );
     204                                unset( $rows );
     205                                if ( $this->budget_is_used( $count, self::BATCH, $started ) ) {
     206                                        break;
     207                                }
     208                                continue;
     209                        }
     210
     211                        $rows = $this->read(
     212                                static function ( $db ) use ( $legacy, $dims, $model, $after ) {
     213                                        if ( $legacy ) {
     214                                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     215                                                        $db->prepare(
     216                                                                "SELECT c.id, SUBSTRING(c.embedding_bin, 1, 1024) FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model IN (%s, '') AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     217                                                                Schema::chunks_table(),
     218                                                                Schema::entries_table(),
     219                                                                $dims,
     220                                                                $model,
     221                                                                $after,
     222                                                                self::BATCH
     223                                                        ),
     224                                                        ARRAY_N
     225                                                );
     226                                        }
     227
     228                                        return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     229                                                $db->prepare(
     230                                                        "SELECT c.id, SUBSTRING(c.embedding_bin, 1, 1024) FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model = %s AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     231                                                        Schema::chunks_table(),
     232                                                        Schema::entries_table(),
     233                                                        $dims,
     234                                                        $model,
     235                                                        $after,
     236                                                        self::BATCH
     237                                                ),
     238                                                ARRAY_N
     239                                        );
     240                                }
     241                        );
     242                        if ( $cached ) {
     243                                // One hour; the version in the key makes it unused as soon as the index changes.
     244                                wp_cache_set( $key, $rows, Passage_Repository::CACHE_GROUP, HOUR_IN_SECONDS );
     245                        }
     246                        $count = count( $rows );
     247                        $this->score_heads( $rows, $head, $head_norm, $heap, $after );
     248                        unset( $rows );
     249                        if ( $this->budget_is_used( $count, self::BATCH, $started ) ) {
     250                                break;
     251                        }
     252                } while ( self::BATCH === $count );
     253
     254                return array_map(
     255                        static function ( array $entry ): int {
     256                                return $entry[1];
     257                        },
     258                        $heap->best_first()
     259                );
     260        }
     261
     262        /**
     263         * Whether the 2 second budget of a search is used up while rows are left to read. The search then stops reading new
     264         * batches and works with the best passages found so far (lower ids first); one log line holds only the code.
     265         *
     266         * @param int   $count   Rows of the batch just read.
     267         * @param int   $size    Rows a full batch holds (a short batch is the last one).
     268         * @param float $started Start of the search.
     269         */
     270        private function budget_is_used( int $count, int $size, float $started ): bool {
     271                if ( $size !== $count || (float) call_user_func( $this->clock ) - $started < self::SCAN_BUDGET ) {
     272                        return false;
     273                }
     274                Logger::warning( 'knowledge base search failed', array( 'code' => 'scan_budget' ) );
     275
     276                return true;
     277        }
     278
     279        /**
     280         * Score one coarse batch against the question's first 256 numbers and offer the scores to the heap.
     281         *
     282         * @param array<int, array<int, mixed>> $rows      Rows of row id and the first 1,024 bytes of the vector.
     283         * @param array<int, float>             $head      The question's first 256 numbers, indexed from 1.
     284         * @param float                         $head_norm Length of that part.
     285         * @param Top_K_Heap                    $heap      Receives the scores.
     286         * @param int                           $after     Set to the last row id of the batch.
     287         */
     288        private function score_heads( array $rows, array $head, float $head_norm, Top_K_Heap $heap, int &$after ): void {
    70289                foreach ( $rows as $row ) {
    71                         $stored = isset( $row['embedding'] ) ? json_decode( (string) $row['embedding'], true ) : null;
    72                         if ( ! is_array( $stored ) || empty( $stored ) ) {
     290                        $id     = (int) $row[0];
     291                        $after  = $id;
     292                        $values = unpack( 'g' . self::COARSE_DIMS, (string) $row[1] );
     293                        if ( ! is_array( $values ) || count( $values ) !== self::COARSE_DIMS ) {
    73294                                continue;
    74295                        }
    75                         $vector   = array_map( 'floatval', $stored );
    76                         $score    = self::cosine( $embedding, $vector );
    77                         $scored[] = array(
    78                                 'id'      => (string) $row['chunk_id'],
    79                                 'score'   => $score,
    80                                 'content' => (string) $row['content'],
     296                        $dot  = 0.0;
     297                        $size = 0.0;
     298                        foreach ( $values as $i => $number ) {
     299                                $dot  += $number * $head[ $i ];
     300                                $size += $number * $number;
     301                        }
     302                        $heap->offer( $size > 0.0 ? $dot / ( sqrt( $size ) * $head_norm ) : 0.0, $id );
     303                }
     304        }
     305
     306        /**
     307         * The full vectors of passages, by row id.
     308         *
     309         * @param int[] $ids Row ids (at most 256).
     310         * @return array<int, array{0: int, 1: string, 2: float}> Id, binary vector and stored norm.
     311         */
     312        private function vectors_of( array $ids ): array {
     313                if ( array() === $ids ) {
     314                        return array();
     315                }
     316
     317                $rows = $this->read(
     318                        static function ( $db ) use ( $ids ) {
     319                                // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- One placeholder per id, counted by the `array_fill()` call.
     320                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     321                                        $db->prepare(
     322                                                "SELECT c.id, c.embedding_bin, c.norm FROM %i c INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.id IN ( " . implode( ', ', array_fill( 0, count( $ids ), '%d' ) ) . ' )',
     323                                                array_merge( array( Schema::chunks_table(), Schema::entries_table() ), $ids )
     324                                        ),
     325                                        ARRAY_N
     326                                );
     327                                // phpcs:enable
     328                        }
     329                );
     330
     331                $vectors = array();
     332                foreach ( $rows as $row ) {
     333                        $vectors[] = array( (int) $row[0], (string) $row[1], (float) $row[2] );
     334                }
     335
     336                return $vectors;
     337        }
     338
     339        /**
     340         * Score full vectors by cosine and offer them to the heap.
     341         *
     342         * @param array<int, array{0: int, 1: string, 2: float}> $vectors  Id, binary vector and stored norm.
     343         * @param array<int, float>                              $question The question, indexed from 1.
     344         * @param float                                          $norm     Length of the question.
     345         * @param int                                            $dims     Vector length.
     346         * @param Top_K_Heap                                     $heap     Receives the scores.
     347         */
     348        private function score_exact( array $vectors, array $question, float $norm, int $dims, Top_K_Heap $heap ): void {
     349                foreach ( $vectors as $vector ) {
     350                        if ( $vector[2] <= 0.0 || strlen( $vector[1] ) !== $dims * 4 ) {
     351                                continue;
     352                        }
     353                        $values = unpack( 'g' . $dims, $vector[1] );
     354                        if ( ! is_array( $values ) ) {
     355                                continue;
     356                        }
     357                        $dot = 0.0;
     358                        foreach ( $values as $i => $number ) {
     359                                $dot += $number * $question[ $i ];
     360                        }
     361                        $heap->offer( $dot / ( $norm * $vector[2] ), $vector[0] );
     362                }
     363        }
     364
     365        /**
     366         * The exact scan in batches (models outside the `text-embedding-3` family, and short vectors). It stops reading new
     367         * batches after two seconds and logs `scan_budget`.
     368         *
     369         * @param array<int, float> $question The question, indexed from 1.
     370         * @param float             $norm     Length of the question.
     371         * @param int               $dims     Vector length.
     372         * @param string            $model    Current model.
     373         * @param bool              $legacy   Whether rows without a model (1.4.9) count.
     374         * @param Top_K_Heap        $heap     Receives the scores.
     375         */
     376        private function scan( array $question, float $norm, int $dims, string $model, bool $legacy, Top_K_Heap $heap ): void {
     377                $started = (float) call_user_func( $this->clock );
     378                $after   = 0;
     379
     380                do {
     381                        $rows    = $this->read(
     382                                static function ( $db ) use ( $legacy, $dims, $model, $after ) {
     383                                        if ( $legacy ) {
     384                                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     385                                                        $db->prepare(
     386                                                                "SELECT c.id, c.embedding_bin, c.norm FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model IN (%s, '') AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     387                                                                Schema::chunks_table(),
     388                                                                Schema::entries_table(),
     389                                                                $dims,
     390                                                                $model,
     391                                                                $after,
     392                                                                self::EXACT_BATCH
     393                                                        ),
     394                                                        ARRAY_N
     395                                                );
     396                                        }
     397
     398                                        return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     399                                                $db->prepare(
     400                                                        "SELECT c.id, c.embedding_bin, c.norm FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NOT NULL AND c.norm > 0 AND c.dims = %d AND c.model = %s AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     401                                                        Schema::chunks_table(),
     402                                                        Schema::entries_table(),
     403                                                        $dims,
     404                                                        $model,
     405                                                        $after,
     406                                                        self::EXACT_BATCH
     407                                                ),
     408                                                ARRAY_N
     409                                        );
     410                                }
     411                        );
     412                        $vectors = array();
     413                        foreach ( $rows as $row ) {
     414                                $vectors[] = array( (int) $row[0], (string) $row[1], (float) $row[2] );
     415                                $after     = (int) $row[0];
     416                        }
     417                        $count = count( $rows );
     418                        unset( $rows );
     419                        $this->score_exact( $vectors, $question, $norm, $dims, $heap );
     420                        unset( $vectors );
     421
     422                        if ( $this->budget_is_used( $count, self::EXACT_BATCH, $started ) ) {
     423                                break;
     424                        }
     425                } while ( self::EXACT_BATCH === $count );
     426        }
     427
     428        /**
     429         * Passages of 1.4.9 that still hold their vector as JSON text, scored exactly. Once the conversion of feature 010
     430         * has finished there are none.
     431         *
     432         * @param array<int, float> $question The question, indexed from 1.
     433         * @param float             $norm     Length of the question.
     434         * @param int               $dims     Vector length.
     435         * @param Top_K_Heap        $heap     Receives the scores.
     436         */
     437        private function score_json_rows( array $question, float $norm, int $dims, Top_K_Heap $heap ): void {
     438                $after = 0;
     439
     440                do {
     441                        $rows = $this->read(
     442                                static function ( $db ) use ( $after ) {
     443                                        return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     444                                                $db->prepare(
     445                                                        "SELECT c.id, c.embedding FROM %i c FORCE INDEX (PRIMARY) INNER JOIN %i e ON e.id = c.entry_id WHERE e.included = 1 AND e.status = 'indexed' AND c.embedding_bin IS NULL AND c.embedding IS NOT NULL AND c.model = '' AND c.id > %d ORDER BY c.id ASC LIMIT %d",
     446                                                        Schema::chunks_table(),
     447                                                        Schema::entries_table(),
     448                                                        $after,
     449                                                        self::EXACT_BATCH
     450                                                ),
     451                                                ARRAY_N
     452                                        );
     453                                }
     454                        );
     455                        foreach ( $rows as $row ) {
     456                                $after  = (int) $row[0];
     457                                $vector = Vector_Codec::read_row( array( 'embedding' => (string) $row[1] ) );
     458                                if ( null === $vector || count( $vector ) !== $dims ) {
     459                                        continue;
     460                                }
     461                                $length = Vector_Codec::norm( $vector );
     462                                if ( $length <= 0.0 ) {
     463                                        continue;
     464                                }
     465                                $dot = 0.0;
     466                                foreach ( $vector as $i => $number ) {
     467                                        $dot += $number * $question[ $i + 1 ];
     468                                }
     469                                $heap->offer( $dot / ( $norm * $length ), $after );
     470                        }
     471                        $count = count( $rows );
     472                        unset( $rows );
     473                } while ( self::EXACT_BATCH === $count );
     474        }
     475
     476        /**
     477         * The 1.4.9 hits of the winning passages.
     478         *
     479         * @param array<int, array{0: float, 1: int}> $best Score and row id, best first.
     480         * @return list<array{id:string,score:float,content:string,meta:array<string,mixed>}>
     481         */
     482        private function hits( array $best ): array {
     483                if ( array() === $best ) {
     484                        return array();
     485                }
     486
     487                $ids   = array_column( $best, 1 );
     488                $rows  = $this->read(
     489                        static function ( $db ) use ( $ids ) {
     490                                // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- One placeholder per id, counted by the `array_fill()` call.
     491                                return $db->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- The index is this plugin's own table, read live.
     492                                        $db->prepare(
     493                                                'SELECT c.id, c.chunk_id, c.entry_id, e.source_id FROM %i c INNER JOIN %i e ON e.id = c.entry_id WHERE c.id IN ( ' . implode( ', ', array_fill( 0, count( $ids ), '%d' ) ) . ' )',
     494                                                array_merge( array( Schema::chunks_table(), Schema::entries_table() ), $ids )
     495                                        ),
     496                                        ARRAY_N
     497                                );
     498                                // phpcs:enable
     499                        }
     500                );
     501                $by_id = array();
     502                foreach ( $rows as $row ) {
     503                        $by_id[ (int) $row[0] ] = $row;
     504                }
     505
     506                $hits = array();
     507                foreach ( $best as $entry ) {
     508                        if ( ! isset( $by_id[ $entry[1] ] ) ) {
     509                                continue;
     510                        }
     511                        $row    = $by_id[ $entry[1] ];
     512                        $hits[] = array(
     513                                'id'      => (string) $row[1],
     514                                'score'   => $entry[0],
     515                                'content' => '',
    81516                                'meta'    => array(
    82                                         'source_id'   => (string) $row['source_id'],
    83                                         'title'       => (string) $row['title'],
    84                                         'url'         => (string) $row['url'],
    85                                         'post_type'   => (string) $row['post_type'],
    86                                         'object_type' => (string) $row['object_type'],
    87                                         'object_id'   => (int) $row['object_id'],
     517                                        'entry_id'  => (int) $row[2],
     518                                        'source_id' => (string) $row[3],
    88519                                ),
    89520                        );
    90521                }
    91522
    92                 usort(
    93                         $scored,
    94                         static function ( array $a, array $b ): int {
    95                                 if ( $a['score'] === $b['score'] ) {
    96                                         return 0;
    97                                 }
    98                                 return ( $a['score'] < $b['score'] ) ? 1 : -1;
    99                         }
    100                 );
    101 
    102                 return array_slice( $scored, 0, $limit );
    103         }
    104 
    105         /**
    106          * {@inheritdoc}
    107          */
    108         public function ping(): bool {
    109                 return true;
    110         }
    111 
    112         /**
    113          * Cosine similarity.
    114          *
    115          * @param array $a Vector a.
    116          * @param array $b Vector b.
    117          */
    118         public static function cosine( array $a, array $b ): float {
    119                 $n   = min( count( $a ), count( $b ) );
    120                 $dot = 0.0;
    121                 $na  = 0.0;
    122                 $nb  = 0.0;
    123                 for ( $i = 0; $i < $n; $i++ ) {
    124                         $va   = (float) $a[ $i ];
    125                         $vb   = (float) $b[ $i ];
    126                         $dot += $va * $vb;
    127                         $na  += $va * $va;
    128                         $nb  += $vb * $vb;
    129                 }
    130                 $den = sqrt( $na ) * sqrt( $nb );
    131                 if ( $den <= 0.0 ) {
    132                         return 0.0;
    133                 }
    134 
    135                 return $dot / $den;
     523                return $hits;
     524        }
     525
     526        /**
     527         * Run a SELECT and return its rows as lists. A database error never prints: it becomes an exception that the
     528         * retriever turns into "no matching passages".
     529         *
     530         * @param callable $query Receives `$wpdb` and returns the rows of one prepared statement (`ARRAY_N`), or null.
     531         * @return array<int, array<int, mixed>>
     532         * @throws \RuntimeException With the message `db_error`.
     533         */
     534        private function read( callable $query ): array {
     535                global $wpdb;
     536
     537                $previous = $wpdb->suppress_errors( true );
     538                try {
     539                        $rows = $query( $wpdb );
     540                } finally {
     541                        $wpdb->suppress_errors( $previous );
     542                }
     543                if ( ! is_array( $rows ) || '' !== $wpdb->last_error ) {
     544                        throw new \RuntimeException( 'db_error' );
     545                }
     546
     547                return $rows;
    136548        }
    137549}
  • chathearth/trunk/includes/Rag/class-retriever.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Retrieve KB chunks and inject them into the system prompt.
     3 * Finds the passages that answer a question (feature 011, research R2, R8, R9, R13, R15; FR-001 to FR-006, FR-016,
     4 * FR-017, FR-019).
     5 *
     6 * It embeds the question once, asks the vector store for the best passages, checks every hit, drops the items that are
     7 * no longer public (the gate) and reads the text of the chosen passages from the local index. It never throws: every
     8 * failure becomes a `Retrieval_Result` with an error code, and the assistant then gets the "no matching passages"
     9 * instruction. The question, the passages and any message of a store are never logged.
    410 *
    511 * @package ChatHearth
    … …  
    1420}
    1521
    16 use ChatHearth\Commerce\Product_Catalog;
    17 use ChatHearth\Options;
     22use ChatHearth\Ai\Embedding_Client;
     23use ChatHearth\Ai\Openai_Embedding_Client;
     24use ChatHearth\Kb\Entry_Repository;
     25use ChatHearth\Kb\Passage_Repository;
     26use ChatHearth\Logger;
    1827
    1928/**
    20  * Query-time RAG.
     29 * Question to passages.
    2130 */
    2231final class Retriever {
    2332
    2433        /**
    25          * Shared instance (so the REST controller can read last hits).
    26          *
    27          * @var self|null
    28          */
    29         private static $instance = null;
    30 
    31         /**
    32          * Last citation list.
    33          *
    34          * @var list<array<string, mixed>>
    35          */
    36         private $last_sources = array();
    37 
    38         /**
    39          * Last matched products.
    40          *
    41          * @var list<array<string, mixed>>
    42          */
    43         private $last_products = array();
    44 
    45         /**
    46          * Instance.
    47          */
    48         public static function instance(): self {
    49                 if ( null === self::$instance ) {
    50                         self::$instance = new self();
    51                 }
    52 
    53                 return self::$instance;
    54         }
    55 
    56         /**
    57          * Register filter.
    58          */
    59         public function register(): void {
    60                 add_filter( 'chathearth_system_prompt', array( $this, 'inject' ), 20, 3 );
    61         }
    62 
    63         /**
    64          * Sources from the last generate call.
    65          *
    66          * @return list<array<string, mixed>>
    67          */
    68         public function last_sources(): array {
    69                 return $this->last_sources;
    70         }
    71 
    72         /**
    73          * Products from the last generate call.
    74          *
    75          * @return list<array<string, mixed>>
    76          */
    77         public function last_products(): array {
    78                 return $this->last_products;
    79         }
    80 
    81         /**
    82          * Inject retrieved context and matching catalog products.
    83          *
    84          * @param string               $prompt  System prompt.
    85          * @param string               $message User message.
    86          * @param array<string, mixed> $history History.
    87          */
    88         public function inject( string $prompt, string $message, array $history ): string {
    89                 unset( $history );
    90                 $catalog             = new Product_Catalog();
    91                 $products            = array();
    92                 $mentioned           = array();
    93                 $this->last_sources  = array();
    94                 $this->last_products = array();
    95 
    96                 foreach ( $catalog->find_mentioned( $message ) as $card ) {
    97                         $mentioned[ (int) $card['id'] ] = $card;
    98                         $products[ (int) $card['id'] ]  = $card;
    99                 }
    100 
    101                 if ( Options::is_rag_enabled() ) {
    102                         $hits = $this->search( $message );
    103                         if ( empty( $hits ) ) {
    104                                 $prompt .= "\n\n## Retrieved knowledge\nNo matching knowledge-base passages were found. Stay within the website context above. If you cannot answer from that context, say so.\n";
    105                         } else {
    106                                 $blocks  = array();
    107                                 $sources = array();
    108 
    109                                 foreach ( $hits as $hit ) {
    110                                         $meta  = $hit['meta'];
    111                                         $title = isset( $meta['title'] ) ? (string) $meta['title'] : '';
    112                                         $url   = isset( $meta['url'] ) ? (string) $meta['url'] : '';
    113                                         $type  = isset( $meta['post_type'] ) && '' !== (string) $meta['post_type'] ? (string) $meta['post_type'] : (string) ( $meta['object_type'] ?? 'content' );
    114 
    115                                         if ( '' !== $url && ! isset( $sources[ $url ] ) ) {
    116                                                 $sources[ $url ] = array(
    117                                                         'title' => $title,
    118                                                         'url'   => $url,
    119                                                         'type'  => $type,
    120                                                 );
    121                                         }
    122 
    123                                         $object_id = isset( $meta['object_id'] ) ? (int) $meta['object_id'] : 0;
    124                                         if ( $object_id > 0 && ( 'product' === $type || ( isset( $meta['post_type'] ) && 'product' === $meta['post_type'] ) ) ) {
    125                                                 $product = $catalog->get_public_product( $object_id );
    126                                                 if ( is_array( $product ) ) {
    127                                                         $products[ $object_id ] = $product;
    128                                                 }
    129                                         }
    130 
    131                                         $blocks[] = '### ' . ( '' !== $title ? $title : 'Source' ) . "\n" . ( '' !== $url ? 'URL: ' . $url . "\n" : '' ) . trim( (string) $hit['content'] );
    132                                 }
    133 
    134                                 $this->last_sources = array_values( $sources );
    135 
    136                                 $joined = implode( "\n\n---\n\n", $blocks );
    137                                 if ( mb_strlen( $joined, 'UTF-8' ) > 12000 ) {
    138                                         $joined = mb_substr( $joined, 0, 12000, 'UTF-8' );
    139                                 }
    140 
    141                                 $prompt .= "\n\n## Retrieved knowledge\nUse the following passages from this website. Cite them with Markdown links. If they are not enough, say you do not have that information.\n\n" . $joined . "\n";
    142                         }
    143                 }
    144 
    145                 if ( count( $mentioned ) >= 2 && $this->looks_like_comparison( $message ) ) {
    146                         $this->last_products = array_values( $mentioned );
    147                 } else {
    148                         $this->last_products = array_slice( array_values( $products ), 0, 6 );
    149                 }
    150                 $prompt .= $this->catalog_prompt( $this->last_products );
    151 
    152                 return $prompt;
    153         }
    154 
    155         /**
    156          * Compact catalog facts for comparison and cart.
    157          *
    158          * @param list<array<string, mixed>> $products Products.
    159          */
    160         private function catalog_prompt( array $products ): string {
    161                 if ( empty( $products ) ) {
    162                         return '';
    163                 }
    164 
    165                 $lines = array(
    166                         "\n\n## Matching catalog products",
    167                         'Use these facts for comparisons and cart actions. Include Markdown links. Do not invent prices or stock.',
    168                 );
    169                 foreach ( $products as $product ) {
    170                         $name    = isset( $product['name'] ) ? (string) $product['name'] : 'Product';
    171                         $url     = isset( $product['url'] ) ? (string) $product['url'] : '';
    172                         $price   = isset( $product['price'] ) ? (string) $product['price'] : '';
    173                         $stock   = ! empty( $product['in_stock'] ) ? 'in stock' : 'out of stock';
    174                         $buy     = ! empty( $product['purchasable'] ) ? 'can be added to cart' : 'cannot be added to cart from chat';
    175                         $label   = '' !== $url ? '[' . $name . '](' . $url . ')' : $name;
    176                         $lines[] = '- ' . $label . ' — ' . $price . ' — ' . $stock . ' — ' . $buy;
    177                 }
    178 
    179                 return implode( "\n", $lines ) . "\n";
    180         }
    181 
    182         /**
    183          * Embed the query and search the configured store.
    184          *
    185          * @param string $message User message.
    186          * @return list<array{id:string,score:float,content:string,meta:array<string, mixed>}>
    187          */
    188         public function search( string $message ): array {
    189                 $embedder = new Embedding_Client();
    190                 $vector   = $embedder->embed( $message );
    191                 if ( is_wp_error( $vector ) ) {
     34         * Most hits of a store that are read (as the 1.4.9 built-in limit).
     35         */
     36        private const MAX_HITS = 20;
     37
     38        /**
     39         * Extra hits asked for, so a few dropped items do not shorten the list.
     40         */
     41        private const SPARE_HITS = 8;
     42
     43        /**
     44         * Most passages ever used.
     45         */
     46        private const MAX_COUNT = 12;
     47
     48        /**
     49         * @var Embedding_Client
     50         */
     51        private $client;
     52
     53        /**
     54         * @var Passage_Repository
     55         */
     56        private $passages;
     57
     58        /**
     59         * @var Entry_Repository
     60         */
     61        private $entries;
     62
     63        /**
     64         * @var Source_Gate
     65         */
     66        private $gate;
     67
     68        /**
     69         * @var Comparison_Detector
     70         */
     71        private $detector;
     72
     73        /**
     74         * @param Embedding_Client    $client   Turns the question into a vector.
     75         * @param Passage_Repository  $passages Local passages.
     76         * @param Entry_Repository    $entries  Local entries (the text of an item).
     77         * @param Source_Gate         $gate     Drops items that stopped being public.
     78         * @param Comparison_Detector $detector Recognises a comparison question.
     79         */
     80        public function __construct( Embedding_Client $client, Passage_Repository $passages, Entry_Repository $entries, Source_Gate $gate, Comparison_Detector $detector ) {
     81                $this->client   = $client;
     82                $this->passages = $passages;
     83                $this->entries  = $entries;
     84                $this->gate     = $gate;
     85                $this->detector = $detector;
     86        }
     87
     88        /**
     89         * Embed, search, check the hits, gate, and read the texts.
     90         *
     91         * @param string $question The visitor's question.
     92         * @param int    $top_k    The setting `rag_top_k`; a comparison asks for twice as many, at most 12.
     93         */
     94        public function retrieve( string $question, int $top_k ): Retrieval_Result {
     95                $top_k = max( 1, min( self::MAX_COUNT, $top_k ) );
     96
     97                try {
     98                        $comparison = $this->detector->is_comparison( $question );
     99                } catch ( \Throwable $e ) {
     100                        $comparison = false;
     101                }
     102                $count = $comparison ? min( self::MAX_COUNT, 2 * $top_k ) : $top_k;
     103
     104                try {
     105                        $vectors = $this->client->embed( array( $question ), Openai_Embedding_Client::resolve_model() );
     106                } catch ( \Throwable $e ) {
     107                        return $this->failed( 'embed_error', $count, $comparison, $e );
     108                }
     109                if ( $vectors instanceof \WP_Error ) {
     110                        return $this->failed( 'embed_' . (string) preg_replace( '/[^a-z0-9_]/', '', strtolower( (string) $vectors->get_error_code() ) ), $count, $comparison );
     111                }
     112                $vector = $this->first_vector( $vectors );
     113                if ( null === $vector ) {
     114                        return $this->failed( 'embed_invalid_vector', $count, $comparison );
     115                }
     116
     117                $store = Vector_Store_Factory::make();
     118                try {
     119                        $hits = $this->as_list( $store->query( $vector, min( self::MAX_HITS, $count + self::SPARE_HITS ) ) );
     120                } catch ( \Throwable $e ) {
     121                        $code = Vector_Store_Factory::is_builtin( $store ) && 'db_error' === $e->getMessage() ? 'db_error' : 'store_error';
     122
     123                        return $this->failed( $code, $count, $comparison, $e );
     124                }
     125                if ( null === $hits ) {
     126                        return $this->failed( 'store_error', $count, $comparison );
     127                }
     128
     129                try {
     130                        return Retrieval_Result::found( $this->choose( $this->valid_hits( $hits ), $count ), $count, $comparison );
     131                } catch ( \Throwable $e ) {
     132                        return $this->failed( 'db_error', $count, $comparison, $e );
     133                }
     134        }
     135
     136        /**
     137         * The vector of the question from an embedding client's answer, or null when there is none.
     138         *
     139         * @param mixed $vectors What the client returned.
     140         * @return array<int, float>|null
     141         */
     142        private function first_vector( $vectors ): ?array {
     143                return is_array( $vectors ) && isset( $vectors[0] ) && is_array( $vectors[0] ) ? $vectors[0] : null;
     144        }
     145
     146        /**
     147         * An answer of a store as a list, or null. The interface promises a list, but a replacement store may answer with
     148         * anything.
     149         *
     150         * @param mixed $answer What the store returned.
     151         * @return array<mixed>|null
     152         */
     153        private function as_list( $answer ): ?array {
     154                return is_array( $answer ) ? $answer : null;
     155        }
     156
     157        /**
     158         * The first 20 hits that have the shape of a 1.4.9 hit, each passage once.
     159         *
     160         * @param array<mixed> $hits What the store answered.
     161         * @return array<int, array{id: string, score: float}>
     162         */
     163        private function valid_hits( array $hits ): array {
     164                $valid = array();
     165                $seen  = array();
     166                foreach ( array_slice( array_values( $hits ), 0, self::MAX_HITS ) as $hit ) {
     167                        if ( ! is_array( $hit ) || ! isset( $hit['id'], $hit['score'], $hit['content'], $hit['meta'] ) ) {
     168                                continue;
     169                        }
     170                        if ( ! is_string( $hit['id'] ) || '' === $hit['id'] || isset( $seen[ $hit['id'] ] ) ) {
     171                                continue;
     172                        }
     173                        if ( ( ! is_int( $hit['score'] ) && ! is_float( $hit['score'] ) ) || ! is_finite( (float) $hit['score'] ) ) {
     174                                continue;
     175                        }
     176                        if ( ! is_string( $hit['content'] ) || ! is_array( $hit['meta'] ) ) {
     177                                continue;
     178                        }
     179                        $seen[ $hit['id'] ] = true;
     180                        $valid[]            = array(
     181                                'id'    => $hit['id'],
     182                                'score' => (float) $hit['score'],
     183                        );
     184                }
     185
     186                return $valid;
     187        }
     188
     189        /**
     190         * The chosen passages: local rows by id, the gate in rank order, and the text of each from the local index.
     191         *
     192         * @param array<int, array{id: string, score: float}> $hits  Checked hits, best first.
     193         * @param int                                         $count Passages wanted.
     194         * @return Retrieved_Passage[]
     195         */
     196        private function choose( array $hits, int $count ): array {
     197                global $wpdb;
     198
     199                if ( array() === $hits ) {
    192200                        return array();
    193201                }
    194202
    195                 $limit = (int) Options::get( 'rag_top_k', 6 );
    196                 $limit = max( 1, min( 12, $limit ) );
    197                 if ( $this->looks_like_comparison( $message ) ) {
    198                         $limit = min( 12, max( $limit, $limit * 2 ) );
    199                 }
    200 
    201                 $hits = Vector_Store_Factory::make()->query( $vector, $limit );
    202                 $repo = new Kb_Repository();
    203 
    204                 foreach ( $hits as $i => $hit ) {
    205                         $local = $repo->get_chunk( (string) $hit['id'] );
    206                         if ( is_array( $local ) && ! empty( $local['content'] ) ) {
    207                                 $hits[ $i ]['content'] = (string) $local['content'];
    208                         }
    209                 }
    210 
    211                 return $hits;
    212         }
    213 
    214         /**
    215          * Whether the user is asking for a comparison.
    216          *
    217          * @param string $message Message.
    218          */
    219         private function looks_like_comparison( string $message ): bool {
    220                 return (bool) preg_match( '/\b(compar(?:e|ison)|vs\.?|versus|difference|better|which (?:one|product))\b/i', $message );
     203                $rows = $this->passages->find_by_chunk_ids( array_column( $hits, 'id' ) );
     204                if ( '' !== (string) $wpdb->last_error ) {
     205                        throw new \RuntimeException( 'db_error' );
     206                }
     207
     208                $allowed   = array();
     209                $markdowns = array();
     210                $chosen    = array();
     211                foreach ( $hits as $hit ) {
     212                        if ( count( $chosen ) >= $count ) {
     213                                break;
     214                        }
     215                        if ( ! isset( $rows[ $hit['id'] ] ) ) {
     216                                continue; // The passage is not in the local index: the hit is stale.
     217                        }
     218                        $row      = $rows[ $hit['id'] ];
     219                        $entry_id = (int) $row['entry_id'];
     220                        if ( ! isset( $allowed[ $entry_id ] ) ) {
     221                                $allowed[ $entry_id ] = $this->gate->allows( $row );
     222                        }
     223                        if ( ! $allowed[ $entry_id ] ) {
     224                                continue;
     225                        }
     226                        if ( ! isset( $markdowns[ $entry_id ] ) ) {
     227                                $markdowns[ $entry_id ] = $this->entries->markdown( $entry_id );
     228                        }
     229                        $text = $this->passages->text( $row, $markdowns[ $entry_id ] );
     230                        if ( '' === trim( $text ) ) {
     231                                continue;
     232                        }
     233
     234                        $object_type = (string) $row['object_type'];
     235                        $post_type   = (string) $row['post_type'];
     236                        $chosen[]    = new Retrieved_Passage(
     237                                (string) $row['chunk_id'],
     238                                (string) $row['source_id'],
     239                                (string) $row['title'],
     240                                (string) $row['url'],
     241                                '' !== $post_type ? $post_type : $object_type,
     242                                $object_type,
     243                                (int) $row['object_id'],
     244                                $post_type,
     245                                $text,
     246                                $hit['score']
     247                        );
     248                }
     249
     250                return $chosen;
     251        }
     252
     253        /**
     254         * A failed search: one log line with the code (and the exception class), never the question or any content.
     255         *
     256         * @param string          $code       Error code.
     257         * @param int             $count      Passages that were asked for.
     258         * @param bool            $comparison Whether the question was a comparison.
     259         * @param \Throwable|null $error      The exception, when there was one.
     260         */
     261        private function failed( string $code, int $count, bool $comparison, ?\Throwable $error = null ): Retrieval_Result {
     262                $context = array( 'code' => $code );
     263                if ( null !== $error ) {
     264                        $context['exception'] = get_class( $error );
     265                }
     266                Logger::warning( 'knowledge base search failed', $context );
     267
     268                return Retrieval_Result::failed( $code, $count, $comparison );
    221269        }
    222270}
  • chathearth/trunk/includes/Rag/class-schema.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Knowledge-base table installer.
     3 * Knowledge-base tables (feature 002 ported from 1.4.9; version 2 from feature 010, research R10).
     4 *
     5 * Version 1 is the 1.4.9 structure. Version 2 only adds columns and keys and makes `chunks.content` nullable: no
     6 * column is dropped and no row is rewritten by the upgrade itself (the 1.4.9 vector conversion runs later, in steps).
     7 * An upgrade that does not complete leaves the stored version as it was, and is tried again on the next load.
    48 *
    59 * @package ChatHearth
    … …  
    1418}
    1519
     20use ChatHearth\Logger;
     21
    1622/**
    17  * Creates and upgrades custom tables used by RAG.
     23 * Creates and upgrades the custom tables used by the knowledge base.
    1824 */
    1925final class Schema {
    2026
    21         public const DB_VERSION     = 1;
     27        public const DB_VERSION     = 2;
    2228        public const VERSION_OPTION = 'chathearth_kb_db_version';
    2329
    … …  
    3238
    3339        /**
    34          * Chunks table name.
     40         * Chunks (passages) table name.
    3541         */
    3642        public static function chunks_table(): string {
    … …  
    4147
    4248        /**
    43          * Install or upgrade tables when the schema version changes.
     49         * Whether this site's tables are at the current version. No sync step runs while this is false (FR-024).
     50         */
     51        public static function is_current(): bool {
     52                return (int) get_option( self::VERSION_OPTION, 0 ) >= self::DB_VERSION;
     53        }
     54
     55        /**
     56         * Install or upgrade the tables when this site's stored version is lower. One option read.
    4457         */
    4558        public static function maybe_install(): void {
    46                 $installed = (int) get_option( self::VERSION_OPTION, 0 );
    47                 if ( self::DB_VERSION === $installed ) {
     59                if ( self::is_current() ) {
    4860                        return;
    4961                }
    … …  
    5365
    5466        /**
    55          * Create tables and the markdown upload directory.
     67         * Create or upgrade the tables (dbDelta is safe to repeat) and store the schema version once everything is in
     68         * place. When something is missing afterwards, the stored version stays and the next load tries again.
    5669         */
    5770        public static function install(): void {
    … …  
    8093                        updated_gmt datetime NOT NULL,
    8194                        indexed_gmt datetime NULL,
     95                        needs_export tinyint(1) NOT NULL DEFAULT 0,
     96                        generation int(10) unsigned NOT NULL DEFAULT 0,
     97                        attempts tinyint(3) unsigned NOT NULL DEFAULT 0,
     98                        retry_at datetime NULL,
    8299                        PRIMARY KEY  (id),
    83100                        UNIQUE KEY source_id (source_id),
    84101                        KEY status (status),
    85                         KEY object_lookup (object_type,object_id)
     102                        KEY object_lookup (object_type,object_id),
     103                        KEY pending_work (status,retry_at),
     104                        KEY generation (generation)
    86105                ) {$charset_collate};";
    87106
    … …  
    91110                        chunk_id varchar(191) NOT NULL,
    92111                        chunk_index int(10) unsigned NOT NULL DEFAULT 0,
    93                         content longtext NOT NULL,
     112                        start_offset int(10) unsigned NULL,
     113                        length int(10) unsigned NULL,
     114                        content longtext NULL,
    94115                        embedding longtext NULL,
     116                        embedding_bin mediumblob NULL,
     117                        norm float NULL,
     118                        dims smallint(5) unsigned NULL,
     119                        model varchar(64) NOT NULL DEFAULT '',
    95120                        PRIMARY KEY  (id),
    96121                        UNIQUE KEY chunk_id (chunk_id),
    97                         KEY entry_id (entry_id)
     122                        KEY entry_id (entry_id),
     123                        KEY model (model)
    98124                ) {$charset_collate};";
    99125
    100126                dbDelta( $sql_entries );
    101127                dbDelta( $sql_chunks );
     128                self::make_content_nullable();
     129
     130                if ( ! self::is_complete() ) {
     131                        Logger::error( 'knowledge base schema upgrade incomplete', array( 'version' => self::DB_VERSION ) );
     132                        return;
     133                }
    102134
    103135                update_option( self::VERSION_OPTION, self::DB_VERSION, true );
    104                 self::ensure_upload_dir();
    105136        }
    106137
    107138        /**
    108          * Plugin-owned uploads root for generated markdown.
     139         * Let `chunks.content` hold NULL (dbDelta does not change whether a column accepts NULL).
    109140         */
    110         public static function plugin_upload_dir(): string {
    111                 $uploads = wp_upload_dir();
    112                 $base    = (string) $uploads['basedir'];
     141        private static function make_content_nullable(): void {
     142                global $wpdb;
    113143
    114                 return trailingslashit( $base ) . 'chathearth';
    115         }
    116 
    117         /**
    118          * Absolute directory for generated markdown files.
    119          */
    120         public static function upload_dir(): string {
    121                 return trailingslashit( self::plugin_upload_dir() ) . 'kb';
    122         }
    123 
    124         /**
    125          * Create the markdown directory and deny public listing.
    126          */
    127         public static function ensure_upload_dir(): void {
    128                 self::protect_dir( self::plugin_upload_dir() );
    129                 self::protect_dir( self::upload_dir() );
    130         }
    131 
    132         /**
    133          * Create a directory and deny public HTTP access.
    134          *
    135          * @param string $dir Absolute path.
    136          */
    137         private static function protect_dir( string $dir ): void {
    138                 if ( '' === $dir || '/' === $dir ) {
    139                         return;
    140                 }
    141 
    142                 if ( ! is_dir( $dir ) ) {
    143                         wp_mkdir_p( $dir );
    144                 }
    145 
    146                 $index = trailingslashit( $dir ) . 'index.php';
    147                 if ( ! file_exists( $index ) ) {
    148                         // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- private uploads guard file.
    149                         file_put_contents( $index, "<?php\n// Silence is golden.\n" );
    150                 }
    151 
    152                 $htaccess = trailingslashit( $dir ) . '.htaccess';
    153                 if ( ! file_exists( $htaccess ) ) {
    154                         $rules = "<IfModule mod_authz_core.c>\nRequire all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\nDeny from all\n</IfModule>\n";
    155                         // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- private uploads guard file.
    156                         file_put_contents( $htaccess, $rules );
     144                $chunks = esc_sql( self::chunks_table() );
     145                $column = $wpdb->get_row( "SHOW COLUMNS FROM `{$chunks}` LIKE 'content'", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reads this plugin's own table definition; the name is internally generated.
     146                if ( is_array( $column ) && 'NO' === $column['Null'] ) {
     147                        $wpdb->query( "ALTER TABLE `{$chunks}` MODIFY content longtext NULL" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Version 2 upgrade of this plugin's own table; the name is internally generated.
    157148                }
    158149        }
    159150
    160151        /**
    161          * Markdown file path for a source id.
    162          *
    163          * @param string $source_id Source id such as post:123.
     152         * Whether every version 2 column is there and `content` accepts NULL.
    164153         */
    165         public static function markdown_path( string $source_id ): string {
    166                 $safe = strtolower( preg_replace( '/[^a-zA-Z0-9._-]+/', '-', $source_id ) ?? $source_id );
    167                 $safe = trim( $safe, '-' );
    168                 if ( '' === $safe ) {
    169                         $safe = 'entry';
     154        private static function is_complete(): bool {
     155                global $wpdb;
     156
     157                $required = array(
     158                        self::entries_table() => array( 'needs_export', 'generation', 'attempts', 'retry_at' ),
     159                        self::chunks_table()  => array( 'start_offset', 'length', 'content', 'embedding', 'embedding_bin', 'norm', 'dims', 'model' ),
     160                );
     161                foreach ( $required as $table => $columns ) {
     162                        $name  = esc_sql( $table );
     163                        $found = $wpdb->get_results( "SHOW COLUMNS FROM `{$name}`", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reads this plugin's own table definition; the name is internally generated.
     164                        if ( ! is_array( $found ) || array() === $found ) {
     165                                return false;
     166                        }
     167                        $nullable = array();
     168                        foreach ( $found as $column ) {
     169                                $nullable[ (string) $column['Field'] ] = 'YES' === $column['Null'];
     170                        }
     171                        foreach ( $columns as $column ) {
     172                                if ( ! isset( $nullable[ $column ] ) ) {
     173                                        return false;
     174                                }
     175                        }
     176                        if ( self::chunks_table() === $table && empty( $nullable['content'] ) ) {
     177                                return false;
     178                        }
    170179                }
    171180
    172                 return trailingslashit( self::upload_dir() ) . $safe . '.md';
    173         }
    174 
    175         /**
    176          * Drop tables, cron, files, and version option (uninstall).
    177          */
    178         public static function uninstall(): void {
    179                 global $wpdb;
    180 
    181                 $chunks  = esc_sql( self::chunks_table() );
    182                 $entries = esc_sql( self::entries_table() );
    183 
    184                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- uninstall drop of plugin table.
    185                 $wpdb->query( "DROP TABLE IF EXISTS {$chunks}" );
    186                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- uninstall drop of plugin table.
    187                 $wpdb->query( "DROP TABLE IF EXISTS {$entries}" );
    188 
    189                 delete_option( self::VERSION_OPTION );
    190                 delete_option( 'chathearth_kb_sync_state' );
    191                 wp_clear_scheduled_hook( 'chathearth_process_kb_queue' );
    192 
    193                 $dir = self::upload_dir();
    194                 if ( is_dir( $dir ) ) {
    195                         $files = glob( trailingslashit( $dir ) . '*' );
    196                         if ( is_array( $files ) ) {
    197                                 foreach ( $files as $file ) {
    198                                         if ( is_file( $file ) ) {
    199                                                 wp_delete_file( $file );
    200                                         }
    201                                 }
    202                         }
    203                 }
     181                return true;
    204182        }
    205183}
  • chathearth/trunk/includes/Rag/class-vector-store-factory.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Build the WordPress-database vector store.
     3 * Chooses the vector store for a request (feature 011, research R13, FR-014; Constitution III).
     4 *
     5 * The built-in store is offered to the 1.4.9 filter `chathearth_vector_store` with its 1.4.9 arguments. Only a value
     6 * that implements `Vector_Store_Interface` replaces it. Anything else is ignored with one warning per request, and the
     7 * warning never holds the value.
    48 *
    59 * @package ChatHearth
    … …  
    1418}
    1519
     20use ChatHearth\Hooks;
     21use ChatHearth\Logger;
     22
    1623/**
    17  * Factory for Vector_Store_Interface implementations.
    18  *
    19  * ChatHearth stores embeddings in this site's WordPress database. Extra
    20  * processes (Python, Chroma) and third-party indexes (Pinecone) are not used.
     24 * The store factory.
    2125 */
    2226final class Vector_Store_Factory {
    2327
    2428        /**
    25          * Create the in-WordPress store.
     29         * Whether the warning about an ignored value was written during this request.
     30         *
     31         * @var bool
     32         */
     33        private static $warned = false;
     34
     35        /**
     36         * The store to use now.
    2637         */
    2738        public static function make(): Vector_Store_Interface {
    28                 $store    = new Builtin_Vector_Store();
    29                 $filtered = apply_filters( 'chathearth_vector_store', $store, 'builtin' );
    30                 if ( $filtered instanceof Vector_Store_Interface ) {
    31                         return $filtered;
     39                $builtin = new Builtin_Vector_Store();
     40
     41                try {
     42                        /**
     43                         * Replace the vector store (kept from 1.4.9).
     44                         *
     45                         * The value must implement `ChatHearth\Rag\Vector_Store_Interface`; anything else is ignored. A replacement
     46                         * store receives the passage text, titles and addresses of public content through `upsert()`, and
     47                         * answers searches through `query()`. Its privacy is the responsibility of the developer who adds it.
     48                         *
     49                         * @since 1.4.9
     50                         *
     51                         * @param Vector_Store_Interface $store Built-in store.
     52                         * @param string                 $id    `builtin`.
     53                         */
     54                        $store = apply_filters( Hooks::VECTOR_STORE, $builtin, 'builtin' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- Every Hooks constant starts with chathearth_.
     55                } catch ( \Throwable $e ) {
     56                        $store = null;
    3257                }
    3358
    34                 return $store;
     59                if ( $store instanceof Vector_Store_Interface ) {
     60                        return $store;
     61                }
     62
     63                if ( ! self::$warned ) {
     64                        self::$warned = true;
     65                        Logger::warning( 'vector store filter ignored' );
     66                }
     67
     68                return $builtin;
    3569        }
    3670
    3771        /**
    38          * Ping the WordPress-database store.
     72         * Whether a store is the built-in one.
    3973         *
    40          * @return array<string, mixed>
     74         * @param Vector_Store_Interface $store Store.
    4175         */
    42         public static function ping_status(): array {
    43                 $ok = self::make()->ping();
     76        public static function is_builtin( Vector_Store_Interface $store ): bool {
     77                return $store instanceof Builtin_Vector_Store;
     78        }
    4479
    45                 return array(
    46                         'ok'      => $ok,
    47                         'store'   => 'builtin',
    48                         'url'     => '',
    49                         'api'     => '',
    50                         'message' => $ok
    51                                 ? __( 'The knowledge base is stored in this WordPress database. No extra server is required.', 'chathearth' )
    52                                 : __( 'The knowledge base tables are not available.', 'chathearth' ),
    53                 );
     80        /**
     81         * Forget that a warning was written (tests, and the start of a request that shares the process).
     82         */
     83        public static function reset(): void {
     84                self::$warned = false;
    5485        }
    5586}
  • chathearth/trunk/includes/Rag/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/includes/Rest/class-cart-controller.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Cart REST route for the chat widget.
     3 * `POST chathearth/v1/cart` (feature 013, contracts/rest-api.md, research R7, R9; FR-013 to FR-017).
     4 *
     5 * The 1.4.9 route, arguments, reply and error codes are kept. Checks come in a fixed order and each refusal changes
     6 * nothing: the token (the permission callback, shared with the chat), the chat switch, the ban list, the shop, the add
     7 * limit, then the product. Every reply, errors included, is marked `no-store`.
    48 *
    59 * @package ChatHearth
    … …  
    1519
    1620use ChatHearth\Commerce\Cart_Service;
    17 use ChatHearth\Commerce\Product_Catalog;
    18 use ChatHearth\Options;
    19 use WP_Error;
     21use ChatHearth\Security\Access_Check;
     22use ChatHearth\Security\Client_Address;
     23use ChatHearth\Security\Counters;
     24use ChatHearth\Settings\Settings_Repository;
    2025use WP_REST_Request;
    2126use WP_REST_Response;
    … …  
    2328
    2429/**
    25  * Guest-accessible add-to-cart using the same REST nonce as chat.
     30 * Cart REST controller. Holds services only, never request state.
    2631 */
    2732final class Cart_Controller {
    2833
    29         public const REST_NAMESPACE = 'chathearth/v1';
    30 
    31         public const NONCE_ACTION = 'wp_rest';
    32 
    33         /**
    34          * Register routes.
     34        /**
     35         * Successful adds one visitor network may make in one window.
     36         */
     37        public const LIMIT = 30;
     38
     39        /**
     40         * The window of the add limit, in seconds.
     41         */
     42        public const WINDOW = 600;
     43
     44        /**
     45         * The route, as the REST server names it.
     46         */
     47        private const ROUTE = '/chathearth/v1/cart';
     48
     49        /**
     50         * @var Settings_Repository
     51         */
     52        private $settings;
     53
     54        /**
     55         * @var Chat_Controller
     56         */
     57        private $chat;
     58
     59        /**
     60         * @var Access_Check
     61         */
     62        private $access;
     63
     64        /**
     65         * @var Client_Address
     66         */
     67        private $address;
     68
     69        /**
     70         * @var Counters
     71         */
     72        private $counters;
     73
     74        /**
     75         * @var Cart_Service
     76         */
     77        private $cart;
     78
     79        /**
     80         * @param Settings_Repository $settings Settings.
     81         * @param Chat_Controller     $chat     Shares the token rule of the chat.
     82         * @param Access_Check        $access   The ban list.
     83         * @param Client_Address      $address  The visitor's network.
     84         * @param Counters            $counters The add counter.
     85         * @param Cart_Service        $cart     Checks and adds.
     86         */
     87        public function __construct( Settings_Repository $settings, Chat_Controller $chat, Access_Check $access, Client_Address $address, Counters $counters, Cart_Service $cart ) {
     88                $this->settings = $settings;
     89                $this->chat     = $chat;
     90                $this->access   = $access;
     91                $this->address  = $address;
     92                $this->counters = $counters;
     93                $this->cart     = $cart;
     94        }
     95
     96        /**
     97         * Hook the route and the cache header.
     98         */
     99        public function register(): void {
     100                add_action( 'rest_api_init', array( $this, 'register_routes' ) );
     101                add_filter( 'rest_post_dispatch', array( $this, 'mark_uncacheable' ), 10, 3 );
     102        }
     103
     104        /**
     105         * Register the route. It is registered with or without WooCommerce, so the contract does not depend on the shop.
    35106         */
    36107        public function register_routes(): void {
    37108                register_rest_route(
    38                         self::REST_NAMESPACE,
     109                        Chat_Controller::REST_NAMESPACE,
    39110                        '/cart',
    40111                        array(
    41112                                'methods'             => WP_REST_Server::CREATABLE,
    42                                 'callback'            => array( $this, 'handle_add' ),
    43                                 'permission_callback' => array( $this, 'permission_check' ),
     113                                'callback'            => array( $this, 'add' ),
     114                                'permission_callback' => array( $this->chat, 'permission_check' ),
    44115                                'args'                => array(
    45116                                        'product_id'   => array(
    … …  
    66137
    67138        /**
    68          * Same nonce gate as chat.
     139         * Mark every reply of the route as not to be cached: a result, a refusal or a missing route for another method.
    69140         *
    70          * @param WP_REST_Request $request Request.
    71          * @return true|WP_Error
    72          */
    73         public function permission_check( WP_REST_Request $request ) {
    74                 $nonce = $request->get_header( 'X-WP-Nonce' );
    75                 if ( ! $nonce ) {
    76                         $nonce = $request->get_param( '_wpnonce' );
    77                 }
    78 
    79                 if ( ! $nonce || ! wp_verify_nonce( (string) $nonce, self::NONCE_ACTION ) ) {
    80                         return new WP_Error(
    81                                 'chathearth_invalid_nonce',
    82                                 __( 'Invalid security token. Please refresh the page and try again.', 'chathearth' ),
    83                                 array( 'status' => 403 )
    84                         );
    85                 }
    86 
    87                 return true;
    88         }
    89 
    90         /**
    91          * Add to cart.
     141         * @param mixed            $response Response.
     142         * @param \WP_REST_Server  $server   Server.
     143         * @param \WP_REST_Request $request  Request.
     144         * @return mixed
     145         */
     146        public function mark_uncacheable( $response, $server, $request ) {
     147                unset( $server );
     148                if ( $response instanceof \WP_HTTP_Response && self::ROUTE === $request->get_route() ) {
     149                        $response->header( 'Cache-Control', 'no-store' );
     150                }
     151
     152                return $response;
     153        }
     154
     155        /**
     156         * Handle an add, after the token has been checked.
    92157         *
    93          * @param WP_REST_Request $request Request.
    94          * @return WP_REST_Response|WP_Error
    95          */
    96         public function handle_add( WP_REST_Request $request ) {
    97                 if ( ! Options::is_chat_enabled() ) {
    98                         return new WP_Error(
     158         * @param WP_REST_Request $request Request, after the argument checks.
     159         * @return WP_REST_Response|\WP_Error
     160         */
     161        public function add( WP_REST_Request $request ) {
     162                $settings = $this->settings->all();
     163                if ( ! (bool) ( $settings['chat_enabled'] ?? true ) ) {
     164                        return new \WP_Error(
    99165                                'chathearth_disabled',
    100166                                __( 'The chatbot is currently disabled.', 'chathearth' ),
    … …  
    103169                }
    104170
    105                 if ( ! Cart_Service::is_available() ) {
    106                         return new WP_Error(
     171                $refusal = $this->access->refusal( $settings );
     172                if ( null !== $refusal ) {
     173                        return $refusal;
     174                }
     175
     176                if ( ! $this->cart->load() ) {
     177                        return new \WP_Error(
    107178                                'chathearth_cart_unavailable',
    108179                                __( 'The store cart is not available.', 'chathearth' ),
    … …  
    111182                }
    112183
    113                 $product_id   = (int) $request->get_param( 'product_id' );
    114                 $quantity     = (int) $request->get_param( 'quantity' );
    115                 $variation_id = (int) $request->get_param( 'variation_id' );
    116 
    117                 $result = ( new Cart_Service() )->add( $product_id, $quantity, $variation_id );
     184                // Look before adding and count only after a success, so a refused add never counts; a counter that cannot be read
     185                // refuses, as the chat's own limits do.
     186                $counter = 'chathearth_cart_' . $this->address->key();
     187                $count   = $this->counters->peek( $counter );
     188                if ( null === $count ) {
     189                        return new \WP_Error(
     190                                'chathearth_rate_busy',
     191                                __( 'Too many requests. Please wait a moment and try again.', 'chathearth' ),
     192                                array( 'status' => 429 )
     193                        );
     194                }
     195                if ( $count >= self::LIMIT ) {
     196                        return new \WP_Error(
     197                                'chathearth_rate_limited',
     198                                __( 'Too many cart requests. Please wait a few minutes and try again.', 'chathearth' ),
     199                                array( 'status' => 429 )
     200                        );
     201                }
     202
     203                $result = $this->cart->add( (int) $request->get_param( 'product_id' ), (int) $request->get_param( 'quantity' ), (int) $request->get_param( 'variation_id' ) );
    118204                if ( is_wp_error( $result ) ) {
    119205                        return $result;
    120206                }
    121207
    122                 $product           = ( new Product_Catalog() )->get_public_product( $product_id );
    123                 $result['product'] = is_array( $product ) ? $product : null;
     208                $this->counters->bump( $counter, self::WINDOW, 'cartadd' );
    124209
    125210                return new WP_REST_Response( $result, 200 );
  • chathearth/trunk/includes/Rest/class-chat-controller.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * REST chat endpoint.
     3 * `POST chathearth/v1/chat` (interface layer; contracts/rest-api.md).
     4 *
     5 * The 1.4.9 route, parameters, response keys, error codes and messages are kept. The controller only translates
     6 * the request into a per-request context and the context into the response; the flow lives in the pipeline.
    47 *
    58 * @package ChatHearth
    … …  
    1417}
    1518
    16 use ChatHearth\Ai\Ai_Gateway;
    17 use ChatHearth\Commerce\Cart_Service;
    18 use ChatHearth\Options;
    19 use ChatHearth\Rag\Current_Page;
    20 use ChatHearth\Rag\Retriever;
    21 use ChatHearth\Security\Content_Moderation;
    22 use ChatHearth\Security\Rate_Limiter;
    23 use ChatHearth\Security\Recaptcha;
    24 use WP_Error;
     19use ChatHearth\Chat\Chat_Context;
     20use ChatHearth\Chat\Chat_Pipeline;
     21use ChatHearth\Settings\Settings_Repository;
    2522use WP_REST_Request;
    2623use WP_REST_Response;
    … …  
    2825
    2926/**
    30  * Chat REST controller.
     27 * Chat REST controller. Holds services only, never request state.
    3128 */
    3229final class Chat_Controller {
    … …  
    3431        public const REST_NAMESPACE = 'chathearth/v1';
    3532
    36         /** Must be `wp_rest` — WordPress REST cookie auth validates X-WP-Nonce against this action. */
     33        /**
     34         * The REST token action. It must be `wp_rest`: WordPress's cookie authentication checks `X-WP-Nonce` against it.
     35         */
    3736        public const NONCE_ACTION = 'wp_rest';
    3837
    3938        /**
    40          * Register routes.
     39         * Most history turns accepted in one request.
     40         */
     41        public const MAX_HISTORY_TURNS = 100;
     42
     43        /**
     44         * @var Settings_Repository
     45         */
     46        private $settings;
     47
     48        /**
     49         * @var Chat_Pipeline
     50         */
     51        private $pipeline;
     52
     53        /**
     54         * @param Settings_Repository $settings Settings.
     55         * @param Chat_Pipeline       $pipeline The stages.
     56         */
     57        public function __construct( Settings_Repository $settings, Chat_Pipeline $pipeline ) {
     58                $this->settings = $settings;
     59                $this->pipeline = $pipeline;
     60        }
     61
     62        /**
     63         * Hook the route registration.
     64         */
     65        public function register(): void {
     66                add_action( 'rest_api_init', array( $this, 'register_routes' ) );
     67        }
     68
     69        /**
     70         * Register the route.
    4171         */
    4272        public function register_routes(): void {
    … …  
    5282                                                'required'          => true,
    5383                                                'type'              => 'string',
    54                                                 'sanitize_callback' => 'sanitize_textarea_field',
     84                                                'sanitize_callback' => array( self::class, 'sanitize_text' ),
    5585                                        ),
    5686                                        'history'         => array(
    … …  
    5888                                                'type'              => 'array',
    5989                                                'default'           => array(),
     90                                                'validate_callback' => array( $this, 'validate_history' ),
    6091                                                'sanitize_callback' => array( $this, 'sanitize_history' ),
    6192                                        ),
    6293                                        'recaptcha_token' => array(
     94                                                'required'          => false,
     95                                                'type'              => 'string',
     96                                                'default'           => '',
     97                                                'sanitize_callback' => 'sanitize_text_field',
     98                                        ),
     99                                        'chathearth_hp'   => array(
    63100                                                'required'          => false,
    64101                                                'type'              => 'string',
    … …  
    93130                        )
    94131                );
    95 
    96                 register_rest_route(
    97                         self::REST_NAMESPACE,
    98                         '/recaptcha',
    99                         array(
    100                                 'methods'             => WP_REST_Server::CREATABLE,
    101                                 'callback'            => array( $this, 'handle_recaptcha' ),
    102                                 'permission_callback' => array( $this, 'permission_check' ),
    103                                 'args'                => array(
    104                                         'recaptcha_token' => array(
    105                                                 'required'          => true,
    106                                                 'type'              => 'string',
    107                                                 'sanitize_callback' => 'sanitize_text_field',
    108                                         ),
    109                                 ),
    110                         )
    111                 );
    112         }
    113 
    114         /**
    115          * Sanitize chat history turns from the REST request.
    116          *
    117          * @param mixed           $history History param.
     132        }
     133
     134        /**
     135         * Clean visitor text: markup is removed (`sanitize_textarea_field`), and so are control characters, except
     136         * line breaks and tabs.
     137         *
     138         * @param mixed $value Text as received.
     139         */
     140        public static function sanitize_text( $value ): string {
     141                $text = sanitize_textarea_field( is_scalar( $value ) ? (string) $value : '' );
     142
     143                return (string) preg_replace( '/[\x00-\x08\x0B-\x1F\x7F]/', '', $text );
     144        }
     145
     146        /**
     147         * Accepts a history that is a list of at most 100 entries.
     148         *
     149         * @param mixed $history History as received.
     150         * @return true|\WP_Error
     151         */
     152        public function validate_history( $history ) {
     153                if ( ! is_array( $history ) || count( $history ) > self::MAX_HISTORY_TURNS || ! self::is_list( $history ) ) {
     154                        return new \WP_Error(
     155                                'rest_invalid_param',
     156                                __( 'The conversation history is not valid.', 'chathearth' ),
     157                                array( 'status' => 400 )
     158                        );
     159                }
     160
     161                return true;
     162        }
     163
     164        /**
     165         * Whether an array is a list (keys 0, 1, 2, ...).
     166         *
     167         * @param array<mixed> $values Values.
     168         */
     169        private static function is_list( array $values ): bool {
     170                return array() === $values || array_keys( $values ) === range( 0, count( $values ) - 1 );
     171        }
     172
     173        /**
     174         * Clean the turns: only `user` and `assistant` turns with text remain (as in 1.4.9).
     175         *
     176         * @param mixed           $history History as received.
    118177         * @param WP_REST_Request $request Request.
    119          * @param string          $param   Param name.
    120          * @return list<array{role:string,content:string}>
     178         * @param string          $param   Parameter name.
     179         * @return array<int, array{role: string, content: string}>
    121180         */
    122181        public function sanitize_history( $history, $request, string $param ): array {
    … …  
    127186                }
    128187
    129                 $out = array();
     188                $clean = array();
    130189                foreach ( $history as $turn ) {
    131190                        if ( ! is_array( $turn ) ) {
    … …  
    133192                        }
    134193
    135                         $role    = isset( $turn['role'] ) ? sanitize_key( (string) $turn['role'] ) : '';
    136                         $content = isset( $turn['content'] ) ? sanitize_textarea_field( (string) $turn['content'] ) : '';
     194                        $role    = isset( $turn['role'] ) && is_scalar( $turn['role'] ) ? sanitize_key( (string) $turn['role'] ) : '';
     195                        $content = isset( $turn['content'] ) && is_scalar( $turn['content'] ) ? self::sanitize_text( (string) $turn['content'] ) : '';
    137196
    138197                        if ( ! in_array( $role, array( 'user', 'assistant' ), true ) || '' === $content ) {
    … …  
    140199                        }
    141200
    142                         $out[] = array(
     201                        $clean[] = array(
    143202                                'role'    => $role,
    144203                                'content' => $content,
    … …  
    146205                }
    147206
    148                 return $out;
    149         }
    150 
    151         /**
    152          * Allow guests and logged-in users when a valid REST nonce is present.
    153          *
    154          * WordPress already rejects invalid X-WP-Nonce values via rest_cookie_check_errors
    155          * before this runs (when the header is sent). We still verify here for clarity.
     207                return $clean;
     208        }
     209
     210        /**
     211         * Allow a request that carries a valid REST token (the `X-WP-Nonce` header or `_wpnonce`).
    156212         *
    157213         * @param WP_REST_Request $request Request.
    158          * @return true|WP_Error
     214         * @return true|\WP_Error
    159215         */
    160216        public function permission_check( WP_REST_Request $request ) {
    … …  
    165221
    166222                if ( ! $nonce || ! wp_verify_nonce( (string) $nonce, self::NONCE_ACTION ) ) {
    167                         return new WP_Error(
     223                        return new \WP_Error(
    168224                                'chathearth_invalid_nonce',
    169225                                __( 'Invalid security token. Please refresh the page and try again.', 'chathearth' ),
    … …  
    176232
    177233        /**
    178          * Unlock the chat overlay after a successful reCAPTCHA v3 check.
     234         * Builds the per-request state from the request and one read of the settings.
     235         *
     236         * @param WP_REST_Request $request Request, after the argument checks.
     237         */
     238        public function build_context( WP_REST_Request $request ): Chat_Context {
     239                $context = new Chat_Context( $this->settings->all() );
     240
     241                $history = $request->get_param( 'history' );
     242
     243                $context->set_message( (string) $request->get_param( 'message' ) );
     244                $context->set_history( is_array( $history ) ? $history : array() );
     245                $context->set_extra(
     246                        array(
     247                                'recaptcha_token' => (string) $request->get_param( 'recaptcha_token' ),
     248                                'chathearth_hp'   => (string) $request->get_param( 'chathearth_hp' ),
     249                                'page_id'         => (int) $request->get_param( 'page_id' ),
     250                                'page_type'       => (string) $request->get_param( 'page_type' ),
     251                                'page_taxonomy'   => (string) $request->get_param( 'page_taxonomy' ),
     252                                'page_url'        => (string) $request->get_param( 'page_url' ),
     253                        )
     254                );
     255
     256                return $context;
     257        }
     258
     259        /**
     260         * Handle a chat request.
    179261         *
    180262         * @param WP_REST_Request $request Request.
    181          * @return WP_REST_Response|WP_Error
    182          */
    183         public function handle_recaptcha( WP_REST_Request $request ) {
    184                 if ( ! Options::is_chat_enabled() ) {
    185                         return new WP_Error(
     263         * @return WP_REST_Response|\WP_Error
     264         */
     265        public function handle_chat( WP_REST_Request $request ) {
     266                $context = $this->build_context( $request );
     267
     268                if ( ! $context->setting( 'chat_enabled', true ) ) {
     269                        return new \WP_Error(
    186270                                'chathearth_disabled',
    187271                                __( 'The chatbot is currently disabled.', 'chathearth' ),
    … …  
    190274                }
    191275
    192                 $captcha = ( new Recaptcha() )->verify_or_error( (string) $request->get_param( 'recaptcha_token' ) );
    193                 if ( is_wp_error( $captcha ) ) {
    194                         return $captcha;
    195                 }
    196 
    197                 return new WP_REST_Response(
    198                         array(
    199                                 'ok' => true,
    200                         ),
    201                         200
    202                 );
    203         }
    204 
    205         /**
    206          * Handle chat request.
    207          *
    208          * @param WP_REST_Request $request Request.
    209          * @return WP_REST_Response|WP_Error
    210          */
    211         public function handle_chat( WP_REST_Request $request ) {
    212                 if ( ! Options::is_chat_enabled() ) {
    213                         return new WP_Error(
    214                                 'chathearth_disabled',
    215                                 __( 'The chatbot is currently disabled.', 'chathearth' ),
    216                                 array( 'status' => 403 )
    217                         );
    218                 }
    219 
    220                 $captcha = ( new Recaptcha() )->verify_or_error( (string) $request->get_param( 'recaptcha_token' ) );
    221                 if ( is_wp_error( $captcha ) ) {
    222                         return $captcha;
    223                 }
    224 
    225                 $rate = ( new Rate_Limiter() )->allow_or_error();
    226                 if ( is_wp_error( $rate ) ) {
    227                         return $rate;
    228                 }
    229 
    230                 $message = trim( (string) $request->get_param( 'message' ) );
    231                 $max_len = (int) Options::get( 'max_message_length', 2000 );
    232 
    233                 if ( '' === $message ) {
    234                         return new WP_Error(
    235                                 'chathearth_empty_message',
    236                                 __( 'Please enter a message.', 'chathearth' ),
    237                                 array( 'status' => 400 )
    238                         );
    239                 }
    240 
    241                 if ( mb_strlen( $message, 'UTF-8' ) > $max_len ) {
    242                         $message = mb_substr( $message, 0, $max_len, 'UTF-8' );
    243                 }
    244 
    245                 $history_raw = $request->get_param( 'history' );
    246                 $history     = is_array( $history_raw ) ? $history_raw : array();
    247                 $max_history = (int) Options::get( 'max_history_messages', 20 );
    248 
    249                 foreach ( $history as $i => $turn ) {
    250                         $content = isset( $turn['content'] ) ? (string) $turn['content'] : '';
    251                         if ( mb_strlen( $content, 'UTF-8' ) > $max_len ) {
    252                                 $history[ $i ]['content'] = mb_substr( $content, 0, $max_len, 'UTF-8' );
    253                         }
    254                 }
    255 
    256                 if ( count( $history ) > $max_history ) {
    257                         $history = array_slice( $history, -$max_history );
    258                 }
    259 
    260                 $moderation = ( new Content_Moderation() )->check_or_error( $message, $history );
    261                 if ( is_wp_error( $moderation ) ) {
    262                         return $moderation;
    263                 }
    264 
    265                 Current_Page::instance()->capture(
    266                         (int) $request->get_param( 'page_id' ),
    267                         (string) $request->get_param( 'page_type' ),
    268                         (string) $request->get_param( 'page_taxonomy' ),
    269                         (string) $request->get_param( 'page_url' )
    270                 );
    271 
    272                 $reply = ( new Ai_Gateway() )->generate_reply( $message, $history );
    273 
    274                 if ( is_wp_error( $reply ) ) {
    275                         return $reply;
    276                 }
    277 
    278                 $retriever = Retriever::instance();
    279                 $current   = Current_Page::instance();
    280 
    281                 return new WP_REST_Response(
    282                         array(
    283                                 'reply'    => $reply,
    284                                 'sources'  => self::merge_unique_sources( $current->source(), $retriever->last_sources() ),
    285                                 'products' => self::merge_unique_products( $current->product(), $retriever->last_products() ),
    286                                 'commerce' => array(
    287                                         'enabled'      => Cart_Service::is_available(),
    288                                         'cart_url'     => Cart_Service::is_available() ? Cart_Service::cart_url() : '',
    289                                         'checkout_url' => Cart_Service::is_available() ? Cart_Service::checkout_url() : '',
    290                                 ),
    291                         ),
    292                         200
    293                 );
    294         }
    295 
    296         /**
    297          * Prepend the current-page citation when it is not already in the RAG list.
    298          *
    299          * @param array<string, mixed>|null  $current Current page source.
    300          * @param list<array<string, mixed>> $sources RAG sources.
    301          * @return list<array<string, mixed>>
    302          */
    303         private static function merge_unique_sources( $current, array $sources ): array {
    304                 if ( ! is_array( $current ) ) {
    305                         return $sources;
    306                 }
    307 
    308                 $url = isset( $current['url'] ) ? (string) $current['url'] : '';
    309                 if ( '' === $url ) {
    310                         return $sources;
    311                 }
    312 
    313                 foreach ( $sources as $source ) {
    314                         if ( isset( $source['url'] ) && (string) $source['url'] === $url ) {
    315                                 return $sources;
    316                         }
    317                 }
    318 
    319                 array_unshift( $sources, $current );
    320 
    321                 return $sources;
    322         }
    323 
    324         /**
    325          * Prepend the current-page product when it is not already listed.
    326          *
    327          * @param array<string, mixed>|null  $current Current product.
    328          * @param list<array<string, mixed>> $products RAG/catalog products.
    329          * @return list<array<string, mixed>>
    330          */
    331         private static function merge_unique_products( $current, array $products ): array {
    332                 if ( ! is_array( $current ) ) {
    333                         return $products;
    334                 }
    335 
    336                 $id = isset( $current['id'] ) ? (int) $current['id'] : 0;
    337                 if ( $id <= 0 ) {
    338                         return $products;
    339                 }
    340 
    341                 foreach ( $products as $product ) {
    342                         if ( isset( $product['id'] ) && (int) $product['id'] === $id ) {
    343                                 return $products;
    344                         }
    345                 }
    346 
    347                 array_unshift( $products, $current );
    348 
    349                 return $products;
     276                $error = $this->pipeline->run( $context );
     277                if ( null !== $error ) {
     278                        return $error;
     279                }
     280
     281                return new WP_REST_Response( $context->response(), 200 );
    350282        }
    351283}
  • chathearth/trunk/includes/Rest/class-kb-controller.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Knowledge-base admin REST routes.
     3 * The knowledge base routes of the Index card (feature 012, contracts/rest-api.md): `POST /kb/sync`,
     4 * `GET /kb/entries`, `POST /kb/entries` and `POST /kb/ping`. `GET /kb/status` stays in feature 010's controller.
     5 *
     6 * Every route has the same permission rule (`Kb_Permission`: the 1.4.9 `chathearth_forbidden` 403) and every reply is
     7 * marked `no-store` by it. The routes that change something accept only `POST`, so a link or an image cannot trigger
     8 * them. Nothing here exports or embeds in the request, and nothing holds request state: the controller holds services
     9 * only.
    410 *
    511 * @package ChatHearth
    … …  
    1420}
    1521
    16 use ChatHearth\Rag\Indexer;
    17 use ChatHearth\Rag\Kb_Repository;
    18 use ChatHearth\Rag\Schema;
    19 use ChatHearth\Rag\Vector_Store_Factory;
     22use ChatHearth\Kb\Entry_Presenter;
     23use ChatHearth\Kb\Entry_Query;
     24use ChatHearth\Kb\Entry_Repository;
     25use ChatHearth\Kb\Kb_Entry_Toggle;
     26use ChatHearth\Kb\Sources;
     27use ChatHearth\Kb\Status_Report;
     28use ChatHearth\Kb\Store_Check;
     29use ChatHearth\Kb\Sync_Job;
    2030use WP_Error;
    2131use WP_REST_Request;
    … …  
    2434
    2535/**
    26  * Sync, status, and per-entry include/exclude.
     36 * Controller of the four 1.4.9 routes that feature 010 did not bring back.
    2737 */
    2838final class Kb_Controller {
    2939
    30         public const REST_NAMESPACE = 'chathearth/v1';
    31 
    32         /**
    33          * Register routes.
     40        /**
     41         * @var Kb_Permission
     42         */
     43        private $permission;
     44
     45        /**
     46         * @var Status_Report
     47         */
     48        private $report;
     49
     50        /**
     51         * @var Sync_Job
     52         */
     53        private $job;
     54
     55        /**
     56         * @var Sources
     57         */
     58        private $sources;
     59
     60        /**
     61         * @var Entry_Repository
     62         */
     63        private $entries;
     64
     65        /**
     66         * @var Entry_Presenter
     67         */
     68        private $presenter;
     69
     70        /**
     71         * @var Kb_Entry_Toggle
     72         */
     73        private $toggle;
     74
     75        /**
     76         * @var Store_Check
     77         */
     78        private $store_check;
     79
     80        /**
     81         * @param Kb_Permission    $permission The shared permission rule.
     82         * @param Status_Report    $report     The status report.
     83         * @param Sync_Job         $job        The sync job.
     84         * @param Sources          $sources    The selected sources and the Knowledge Base switch.
     85         * @param Entry_Repository $entries    The entries.
     86         * @param Entry_Presenter  $presenter  Row to list item.
     87         * @param Kb_Entry_Toggle  $toggle     The Included switch.
     88         * @param Store_Check      $store_check The storage check.
     89         */
     90        public function __construct( Kb_Permission $permission, Status_Report $report, Sync_Job $job, Sources $sources, Entry_Repository $entries, Entry_Presenter $presenter, Kb_Entry_Toggle $toggle, Store_Check $store_check ) {
     91                $this->permission  = $permission;
     92                $this->report      = $report;
     93                $this->job         = $job;
     94                $this->sources     = $sources;
     95                $this->entries     = $entries;
     96                $this->presenter   = $presenter;
     97                $this->toggle      = $toggle;
     98                $this->store_check = $store_check;
     99        }
     100
     101        /**
     102         * Hook the route registration.
     103         */
     104        public function register(): void {
     105                add_action( 'rest_api_init', array( $this, 'register_routes' ) );
     106        }
     107
     108        /**
     109         * Register the routes.
    34110         */
    35111        public function register_routes(): void {
    36112                register_rest_route(
    37                         self::REST_NAMESPACE,
     113                        Chat_Controller::REST_NAMESPACE,
    38114                        '/kb/sync',
    39115                        array(
    40116                                'methods'             => WP_REST_Server::CREATABLE,
    41                                 'callback'            => array( $this, 'handle_sync' ),
    42                                 'permission_callback' => array( $this, 'can_manage' ),
     117                                'callback'            => array( $this, 'sync' ),
     118                                'permission_callback' => array( $this->permission, 'check' ),
    43119                        )
    44120                );
    45121
    46122                register_rest_route(
    47                         self::REST_NAMESPACE,
    48                         '/kb/status',
    49                         array(
    50                                 'methods'             => WP_REST_Server::READABLE,
    51                                 'callback'            => array( $this, 'handle_status' ),
    52                                 'permission_callback' => array( $this, 'can_manage' ),
     123                        Chat_Controller::REST_NAMESPACE,
     124                        '/kb/ping',
     125                        array(
     126                                'methods'             => WP_REST_Server::CREATABLE,
     127                                'callback'            => array( $this, 'ping' ),
     128                                'permission_callback' => array( $this->permission, 'check' ),
    53129                        )
    54130                );
    55131
    56132                register_rest_route(
    57                         self::REST_NAMESPACE,
     133                        Chat_Controller::REST_NAMESPACE,
    58134                        '/kb/entries',
    59135                        array(
    60                                 'methods'             => WP_REST_Server::READABLE,
    61                                 'callback'            => array( $this, 'handle_entries' ),
    62                                 'permission_callback' => array( $this, 'can_manage' ),
     136                                array(
     137                                        'methods'             => WP_REST_Server::READABLE,
     138                                        'callback'            => array( $this, 'entries' ),
     139                                        'permission_callback' => array( $this->permission, 'check' ),
     140                                        'args'                => array(
     141                                                'page'     => array(
     142                                                        'type'    => 'integer',
     143                                                        'default' => 1,
     144                                                        'minimum' => 1,
     145                                                        'maximum' => 100000,
     146                                                ),
     147                                                'search'   => array(
     148                                                        'type'    => 'string',
     149                                                        'default' => '',
     150                                                ),
     151                                                'type'     => array(
     152                                                        'type'    => 'string',
     153                                                        'default' => '',
     154                                                        'pattern' => '^(?:_site|[a-z0-9_-]{1,32})?\z',
     155                                                ),
     156                                                'status'   => array(
     157                                                        'type'    => 'string',
     158                                                        'default' => '',
     159                                                        'enum'    => array( '', 'indexed', 'pending', 'excluded', 'failed' ),
     160                                                ),
     161                                                'included' => array(
     162                                                        'type'    => 'string',
     163                                                        'default' => '',
     164                                                        'enum'    => array( '', 'yes', 'no' ),
     165                                                ),
     166                                        ),
     167                                ),
     168                                array(
     169                                        'methods'             => WP_REST_Server::CREATABLE,
     170                                        'callback'            => array( $this, 'toggle' ),
     171                                        'permission_callback' => array( $this->permission, 'check' ),
     172                                        'args'                => array(
     173                                                'source_id' => array(
     174                                                        'type'              => 'string',
     175                                                        'default'           => '',
     176                                                        'sanitize_callback' => 'sanitize_text_field',
     177                                                ),
     178                                                'included'  => array(
     179                                                        'type'              => 'boolean',
     180                                                        'default'           => false,
     181                                                        'sanitize_callback' => 'rest_sanitize_boolean',
     182                                                ),
     183                                        ),
     184                                ),
    63185                        )
    64186                );
    65 
    66                 register_rest_route(
    67                         self::REST_NAMESPACE,
    68                         '/kb/entries',
    69                         array(
    70                                 'methods'             => WP_REST_Server::CREATABLE,
    71                                 'callback'            => array( $this, 'handle_toggle' ),
    72                                 'permission_callback' => array( $this, 'can_manage' ),
    73                         )
    74                 );
    75 
    76                 register_rest_route(
    77                         self::REST_NAMESPACE,
    78                         '/kb/ping',
    79                         array(
    80                                 'methods'             => WP_REST_Server::CREATABLE,
    81                                 'callback'            => array( $this, 'handle_ping' ),
    82                                 'permission_callback' => array( $this, 'can_manage' ),
    83                         )
    84                 );
    85         }
    86 
    87         /**
    88          * Require the manage_options capability.
     187        }
     188
     189        /**
     190         * `POST /kb/ping`: test the storage and keep the result (research R10). 200 when it is ready, 502 when it is not.
     191         */
     192        public function ping(): WP_REST_Response {
     193                $result = $this->store_check->run();
     194
     195                return new WP_REST_Response( $result, $result['ok'] ? 200 : 502 );
     196        }
     197
     198        /**
     199         * `GET /kb/entries`: one page of the item list (research R5). One count query and one page query, plus the query for
     200         * the type filter. Only the 1.4.9 list fields and the labels are read, never a document.
    89201         *
    90          * @return true|WP_Error
    91          */
    92         public function can_manage() {
    93                 if ( current_user_can( 'manage_options' ) ) {
    94                         return true;
    95                 }
    96 
    97                 return new WP_Error(
    98                         'chathearth_forbidden',
    99                         __( 'You are not allowed to manage the knowledge base.', 'chathearth' ),
    100                         array( 'status' => 403 )
    101                 );
    102         }
    103 
    104         /**
    105          * Scan sources and embed a batch.
    106          *
    107          * @return WP_REST_Response
    108          */
    109         public function handle_sync() {
    110                 Schema::maybe_install();
    111                 $indexer = Indexer::instance();
    112                 $scanned = $indexer->scan_sources();
    113                 $indexed = $indexer->process_queue( 12 );
    114                 $repo    = new Kb_Repository();
     202         * @param WP_REST_Request $request The request.
     203         */
     204        public function entries( WP_REST_Request $request ): WP_REST_Response {
     205                $page  = $this->entries->list_page( Entry_Query::from_request( $request ) );
     206                $total = $page['total'];
    115207
    116208                return new WP_REST_Response(
    117209                        array(
    118                                 'scanned' => $scanned,
    119                                 'indexed' => $indexed,
    120                                 'counts'  => $repo->status_counts(),
    121                                 'pending' => $repo->has_pending(),
     210                                'items' => array_map( array( $this->presenter, 'item' ), $page['rows'] ),
     211                                'total' => $total,
     212                                'pages' => max( 1, (int) ceil( $total / Entry_Query::PAGE_SIZE ) ),
     213                                'types' => $this->presenter->types( $this->entries->types() ),
    122214                        ),
    123215                        200
    … …  
    126218
    127219        /**
    128          * Counts and store ping.
     220         * `POST /kb/entries`: include or exclude one entry (research R7).
    129221         *
    130          * @return WP_REST_Response
    131          */
    132         public function handle_status() {
    133                 Schema::maybe_install();
    134                 $repo = new Kb_Repository();
     222         * @param WP_REST_Request $request The request.
     223         * @return WP_REST_Response|WP_Error
     224         */
     225        public function toggle( WP_REST_Request $request ) {
     226                $result = $this->toggle->set( (string) $request->get_param( 'source_id' ), (bool) $request->get_param( 'included' ) );
     227
     228                return $result instanceof WP_Error ? $result : new WP_REST_Response( $result, 200 );
     229        }
     230
     231        /**
     232         * `POST /kb/sync`: ask for a full sync in the background (research R3).
     233         *
     234         * Nothing is queued while the Knowledge Base is off or a sync already runs, so a second click, or a click in another
     235         * tab, never resets the progress. The reply keeps the 1.4.9 fields (`scanned` and `indexed` are 0, because the work
     236         * runs in the background) and adds the full report.
     237         */
     238        public function sync(): WP_REST_Response {
     239                $before = $this->report->to_array();
     240                if ( $this->sources->is_enabled() && ! $before['running'] ) {
     241                        $this->job->request_full( 0 );
     242                }
     243                $report = $this->report->to_array();
    135244
    136245                return new WP_REST_Response(
    137246                        array(
    138                                 'counts'   => $repo->status_counts(),
    139                                 'pending'  => $repo->has_pending(),
    140                                 'store_ok' => Vector_Store_Factory::make()->ping(),
    141                                 'store'    => 'builtin',
     247                                'scanned' => 0,
     248                                'indexed' => 0,
     249                                'counts'  => $report['counts'],
     250                                'pending' => $report['pending'],
     251                                'report'  => $report,
    142252                        ),
    143253                        200
    144254                );
    145255        }
    146 
    147         /**
    148          * Paginated entries.
    149          *
    150          * @param WP_REST_Request $request Request.
    151          * @return WP_REST_Response
    152          */
    153         public function handle_entries( WP_REST_Request $request ) {
    154                 Schema::maybe_install();
    155                 $page   = max( 1, (int) $request->get_param( 'page' ) );
    156                 $search = sanitize_text_field( (string) $request->get_param( 'search' ) );
    157                 $data   = ( new Kb_Repository() )->paginate( $page, 20, $search );
    158 
    159                 return new WP_REST_Response( $data, 200 );
    160         }
    161 
    162         /**
    163          * Toggle include flag.
    164          *
    165          * @param WP_REST_Request $request Request.
    166          * @return WP_REST_Response|WP_Error
    167          */
    168         public function handle_toggle( WP_REST_Request $request ) {
    169                 $source_id = sanitize_text_field( (string) $request->get_param( 'source_id' ) );
    170                 $included  = rest_sanitize_boolean( $request->get_param( 'included' ) );
    171                 if ( '' === $source_id ) {
    172                         return new WP_Error(
    173                                 'chathearth_kb_invalid',
    174                                 __( 'Missing source id.', 'chathearth' ),
    175                                 array( 'status' => 400 )
    176                         );
    177                 }
    178 
    179                 Indexer::instance()->set_included( $source_id, (bool) $included );
    180                 $entry = ( new Kb_Repository() )->get_by_source( $source_id );
    181                 if ( ! is_array( $entry ) ) {
    182                         return new WP_Error(
    183                                 'chathearth_kb_missing',
    184                                 __( 'Entry not found.', 'chathearth' ),
    185                                 array( 'status' => 404 )
    186                         );
    187                 }
    188 
    189                 return new WP_REST_Response(
    190                         array(
    191                                 'source_id' => $source_id,
    192                                 'included'  => ! empty( $entry['included'] ),
    193                                 'status'    => (string) $entry['status'],
    194                         ),
    195                         200
    196                 );
    197         }
    198 
    199         /**
    200          * Ping the configured vector store.
    201          *
    202          * @param WP_REST_Request $request Request.
    203          * @return WP_REST_Response
    204          */
    205         public function handle_ping( WP_REST_Request $request ) {
    206                 unset( $request );
    207                 $status = Vector_Store_Factory::ping_status();
    208 
    209                 return new WP_REST_Response(
    210                         $status,
    211                         ! empty( $status['ok'] ) ? 200 : 502
    212                 );
    213         }
    214256}
  • chathearth/trunk/includes/Rest/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/includes/Security/class-rate-limiter.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Per-IP and global rate limiter (object cache incr, locked fallback).
     3 * Enforce site-wide and network message quotas before AI calls (FR-004–FR-008).
    44 *
    55 * @package ChatHearth
    … …  
    1414}
    1515
    16 use ChatHearth\Options;
     16use ChatHearth\Logger;
    1717use WP_Error;
    1818
    19 /**
    20  * Limits chat requests by client IP and site-wide quotas.
    21  */
     19/** Consumes the site-wide allowance first and refunds it if the network or user cannot send. */
    2220final class Rate_Limiter {
    2321
    24         private const CACHE_GROUP = 'chathearth';
     22        private const GLOBAL_MINUTE = 'chathearth_rl_g_m';
     23        private const GLOBAL_HOUR   = 'chathearth_rl_g_h';
     24        private const GLOBAL_SCOPE  = 'g';
    2525
    26         private const GLOBAL_MINUTE_KEY   = 'chathearth_rl_g_m';
    27         private const GLOBAL_HOUR_KEY     = 'chathearth_rl_g_h';
    28         private const GLOBAL_INCIDENT_KEY = 'chathearth_rl_g_inc';
    29         private const EMAIL_COOLDOWN_KEY  = 'chathearth_rl_email_cd';
     26        /** @var Counters */
     27        private $counters;
    3028
    31         public const ABUSE_ALERT_OPTION = 'chathearth_abuse_alert';
     29        /** @var array<string,mixed> */
     30        private $settings;
    3231
    33         /** Max attempts to acquire the lock. */
    34         private const LOCK_ATTEMPTS = 3;
     32        /** @var callable():void|null */
     33        private $record_incident;
    3534
    36         /** Microseconds to wait between lock attempts. */
    37         private const LOCK_WAIT_US = 50000;
    38 
    39         /** Lock option TTL in seconds (stored as an expiry timestamp). */
    40         private const LOCK_TTL = 5;
    41 
    42         /** Min seconds between escalation emails. */
    43         private const EMAIL_COOLDOWN = 1800;
     35        /** @var Quota_Policy */
     36        private $policy;
    4437
    4538        /**
    46          * Check whether the current request is allowed; increments counters if allowed.
    47          *
    48          * Order: global site limits, then per-IP limits.
    49          *
    50          * @return true|WP_Error
     39         * @param Counters             $counters        Quota storage.
     40         * @param Client_Address       $client          Visitor network, used for the default quota policy.
     41         * @param array<string,mixed>  $settings        The chat request's settings snapshot.
     42         * @param callable():void|null $record_incident Called on a genuine site-wide limit refusal.
     43         * @param Quota_Policy|null    $policy          The bucket and limits of the second step; the default follows the settings.
    5144         */
    52         public function allow_or_error() {
    53                 $global_min  = (int) Options::get( 'global_rate_limit_per_minute', 60 );
    54                 $global_hour = (int) Options::get( 'global_rate_limit_per_hour', 500 );
     45        public function __construct( Counters $counters, Client_Address $client, array $settings, ?callable $record_incident = null, ?Quota_Policy $policy = null ) {
     46                $this->counters        = $counters;
     47                $this->settings        = $settings;
     48                $this->record_incident = $record_incident;
     49                $this->policy          = $policy ?? new Quota_Policy( $client );
     50        }
    5551
    56                 $global = $this->consume_quota(
    57                         self::GLOBAL_MINUTE_KEY,
    58                         self::GLOBAL_HOUR_KEY,
    59                         'global',
    60                         $global_min,
    61                         $global_hour
     52        /** Get the first refusal, or null when both quotas allowed the chat. */
     53        public function consume(): ?WP_Error {
     54                $global = $this->counters->consume(
     55                        self::GLOBAL_MINUTE,
     56                        self::GLOBAL_HOUR,
     57                        (int) ( $this->settings['global_rate_limit_per_minute'] ?? 60 ),
     58                        (int) ( $this->settings['global_rate_limit_per_hour'] ?? 500 ),
     59                        self::GLOBAL_SCOPE
    6260                );
    63 
    64                 if ( is_wp_error( $global ) ) {
    65                         if ( 'chathearth_rate_busy' !== $global->get_error_code() ) {
    66                                 $this->on_global_limit_hit();
    67                                 return $this->global_error();
     61                if ( 'busy' === $global ) {
     62                        return self::busy( 'global' );
     63                }
     64                if ( 'allowed' !== $global ) {
     65                        if ( null !== $this->record_incident ) {
     66                                try {
     67                                        ( $this->record_incident )();
     68                                } catch ( \Throwable $error ) {
     69                                        Logger::warning( 'The site-wide quota escalation could not be completed.' );
     70                                }
    6871                        }
    69                         return $global;
     72                        return new WP_Error(
     73                                'chathearth_global_rate_limited',
     74                                __( 'The chatbot is temporarily unavailable due to high demand. Please try again later.', 'chathearth' ),
     75                                array( 'status' => 429 )
     76                        );
    7077                }
    7178
    72                 $ip   = $this->client_ip();
    73                 $hash = md5( $ip );
    74 
    75                 $per_minute = (int) Options::get( 'rate_limit_per_minute', 10 );
    76                 $per_hour   = (int) Options::get( 'rate_limit_per_hour', 60 );
    77 
    78                 return $this->consume_quota(
    79                         'chathearth_rl_m_' . $hash,
    80                         'chathearth_rl_h_' . $hash,
    81                         $hash,
    82                         $per_minute,
    83                         $per_hour
     79                // A logged-in user is counted per account (feature 008); everyone else per network.
     80                $bucket  = $this->policy->for_request( $this->settings );
     81                $key     = $bucket['key'];
     82                $network = $this->counters->consume(
     83                        'chathearth_rl_m_' . $key,
     84                        'chathearth_rl_h_' . $key,
     85                        $bucket['minute'],
     86                        $bucket['hour'],
     87                        $key
    8488                );
    85         }
    86 
    87         /**
    88          * Consume one request against a minute/hour quota pair.
    89          *
    90          * @param string $minute_key Minute counter key.
    91          * @param string $hour_key   Hour counter key.
    92          * @param string $lock_id    Lock suffix (IP hash or "global").
    93          * @param int    $per_minute Limit per minute.
    94          * @param int    $per_hour   Limit per hour.
    95          * @return true|WP_Error
    96          */
    97         private function consume_quota( string $minute_key, string $hour_key, string $lock_id, int $per_minute, int $per_hour ) {
    98                 if ( wp_using_ext_object_cache() ) {
    99                         return $this->allow_via_object_cache( $minute_key, $hour_key, $per_minute, $per_hour );
     89                if ( 'allowed' === $network ) {
     90                        return null;
    10091                }
    101 
    102                 return $this->allow_via_locked_transients( $lock_id, $minute_key, $hour_key, $per_minute, $per_hour );
    103         }
    104 
    105         /**
    106          * Atomic counters via external object cache (Redis / Memcached).
    107          *
    108          * @param string $minute_key Minute counter key.
    109          * @param string $hour_key   Hour counter key.
    110          * @param int    $per_minute Limit per minute.
    111          * @param int    $per_hour   Limit per hour.
    112          * @return true|WP_Error
    113          */
    114         private function allow_via_object_cache( string $minute_key, string $hour_key, int $per_minute, int $per_hour ) {
    115                 wp_cache_add( $minute_key, 0, self::CACHE_GROUP, MINUTE_IN_SECONDS );
    116                 $minute_count = wp_cache_incr( $minute_key, 1, self::CACHE_GROUP );
    117 
    118                 if ( false === $minute_count ) {
    119                         return $this->busy_error();
     92                $this->counters->refund( self::GLOBAL_MINUTE, self::GLOBAL_HOUR, self::GLOBAL_SCOPE );
     93                if ( 'busy' === $network ) {
     94                        return self::busy( $bucket['scope'] );
    12095                }
    121 
    122                 if ( (int) $minute_count > $per_minute ) {
    123                         return $this->minute_error();
    124                 }
    125 
    126                 wp_cache_add( $hour_key, 0, self::CACHE_GROUP, HOUR_IN_SECONDS );
    127                 $hour_count = wp_cache_incr( $hour_key, 1, self::CACHE_GROUP );
    128 
    129                 if ( false === $hour_count ) {
    130                         return $this->busy_error();
    131                 }
    132 
    133                 if ( (int) $hour_count > $per_hour ) {
    134                         return $this->hour_error();
    135                 }
    136 
    137                 return true;
    138         }
    139 
    140         /**
    141          * Read/modify/write under a short-lived exclusive option lock.
    142          *
    143          * @param string $lock_id    Lock suffix.
    144          * @param string $minute_key Minute counter key.
    145          * @param string $hour_key   Hour counter key.
    146          * @param int    $per_minute Limit per minute.
    147          * @param int    $per_hour   Limit per hour.
    148          * @return true|WP_Error
    149          */
    150         private function allow_via_locked_transients( string $lock_id, string $minute_key, string $hour_key, int $per_minute, int $per_hour ) {
    151                 $lock_key = 'chathearth_rl_lock_' . $lock_id;
    152 
    153                 if ( ! $this->acquire_lock( $lock_key ) ) {
    154                         return $this->busy_error();
    155                 }
    156 
    157                 try {
    158                         $minute_count = (int) get_transient( $minute_key );
    159                         $hour_count   = (int) get_transient( $hour_key );
    160 
    161                         if ( $minute_count >= $per_minute ) {
    162                                 return $this->minute_error();
    163                         }
    164 
    165                         if ( $hour_count >= $per_hour ) {
    166                                 return $this->hour_error();
    167                         }
    168 
    169                         set_transient( $minute_key, $minute_count + 1, MINUTE_IN_SECONDS );
    170                         set_transient( $hour_key, $hour_count + 1, HOUR_IN_SECONDS );
    171 
    172                         return true;
    173                 } finally {
    174                         delete_option( $lock_key );
    175                 }
    176         }
    177 
    178         /**
    179          * Record a global-limit denial and escalate when the incident threshold is reached.
    180          */
    181         private function on_global_limit_hit(): void {
    182                 $threshold = (int) Options::get( 'global_limit_incident_threshold', 3 );
    183                 $incidents = $this->bump_incident_count();
    184 
    185                 if ( $incidents < $threshold ) {
    186                         return;
    187                 }
    188 
    189                 $this->escalate_to_admin( $incidents );
    190         }
    191 
    192         /**
    193          * Increment the hourly global-limit incident counter.
    194          */
    195         private function bump_incident_count(): int {
    196                 $key = self::GLOBAL_INCIDENT_KEY;
    197 
    198                 if ( wp_using_ext_object_cache() ) {
    199                         wp_cache_add( $key, 0, self::CACHE_GROUP, HOUR_IN_SECONDS );
    200                         $count = wp_cache_incr( $key, 1, self::CACHE_GROUP );
    201                         return false === $count ? 1 : (int) $count;
    202                 }
    203 
    204                 $lock_key = 'chathearth_rl_lock_inc';
    205                 if ( ! $this->acquire_lock( $lock_key ) ) {
    206                         $count = (int) get_transient( $key );
    207                         set_transient( $key, $count + 1, HOUR_IN_SECONDS );
    208                         return $count + 1;
    209                 }
    210 
    211                 try {
    212                         $count = (int) get_transient( $key );
    213                         $next  = $count + 1;
    214                         set_transient( $key, $next, HOUR_IN_SECONDS );
    215                         return $next;
    216                 } finally {
    217                         delete_option( $lock_key );
    218                 }
    219         }
    220 
    221         /**
    222          * Email admin, store notice, optionally disable chat (with email cooldown).
    223          *
    224          * @param int $incidents Incident count in the current window.
    225          */
    226         private function escalate_to_admin( int $incidents ): void {
    227                 $auto_disable = (bool) Options::get( 'auto_disable_on_global_escalation', true );
    228                 $disabled_now = false;
    229 
    230                 if ( $auto_disable && Options::is_chat_enabled() ) {
    231                         $settings                 = Options::all();
    232                         $settings['chat_enabled'] = false;
    233                         update_option( Options::OPTION_KEY, $settings );
    234                         $disabled_now = true;
    235                 }
    236 
    237                 $alert = array(
    238                         'time'          => time(),
    239                         'incidents'     => $incidents,
    240                         'auto_disabled' => $disabled_now,
    241                 );
    242                 update_option( self::ABUSE_ALERT_OPTION, $alert, false );
    243 
    244                 if ( get_transient( self::EMAIL_COOLDOWN_KEY ) ) {
    245                         return;
    246                 }
    247 
    248                 set_transient( self::EMAIL_COOLDOWN_KEY, 1, self::EMAIL_COOLDOWN );
    249 
    250                 $admin_email = get_option( 'admin_email' );
    251                 if ( ! is_string( $admin_email ) || '' === $admin_email ) {
    252                         return;
    253                 }
    254 
    255                 $site_name    = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
    256                 $settings_url = admin_url( 'options-general.php?page=chathearth&tab=protection' );
    257 
    258                 $subject = sprintf(
    259                         /* translators: %s: site name */
    260                         __( '[%s] ChatHearth - AI Chatbot: global rate limit escalation', 'chathearth' ),
    261                         $site_name
    262                 );
    263 
    264                 $lines = array(
    265                         __( 'ChatHearth - AI Chatbot blocked site-wide chat traffic after repeated global rate-limit hits.', 'chathearth' ),
    266                         '',
    267                         sprintf(
    268                                 /* translators: %d: number of global limit hits in the current hour */
    269                                 __( 'Global limit hits in the last hour: %d', 'chathearth' ),
    270                                 $incidents
    271                         ),
    272                         sprintf(
    273                                 /* translators: 1: per-minute limit, 2: per-hour limit */
    274                                 __( 'Configured global limits: %1$d/minute, %2$d/hour', 'chathearth' ),
    275                                 (int) Options::get( 'global_rate_limit_per_minute', 60 ),
    276                                 (int) Options::get( 'global_rate_limit_per_hour', 500 )
    277                         ),
    278                 );
    279 
    280                 if ( $disabled_now ) {
    281                         $lines[] = '';
    282                         $lines[] = __( 'The chatbot has been automatically disabled. Re-enable it under Settings → ChatHearth - AI Chatbot → Protection when ready.', 'chathearth' );
    283                 }
    284 
    285                 $lines[] = '';
    286                 $lines[] = __( 'Protection settings:', 'chathearth' );
    287                 $lines[] = $settings_url;
    288 
    289                 wp_mail( $admin_email, $subject, implode( "\n", $lines ) );
    290         }
    291 
    292         /**
    293          * Acquire an exclusive lock via add_option (succeeds only if the option is missing).
    294          *
    295          * @param string $lock_key Lock option name.
    296          */
    297         private function acquire_lock( string $lock_key ): bool {
    298                 for ( $i = 0; $i < self::LOCK_ATTEMPTS; $i++ ) {
    299                         $now = time();
    300 
    301                         $existing = get_option( $lock_key, false );
    302                         if ( false !== $existing && is_numeric( $existing ) && (int) $existing < $now ) {
    303                                 delete_option( $lock_key );
    304                         }
    305 
    306                         if ( add_option( $lock_key, $now + self::LOCK_TTL, '', false ) ) {
    307                                 return true;
    308                         }
    309 
    310                         usleep( self::LOCK_WAIT_US );
    311                 }
    312 
    313                 return false;
    314         }
    315 
    316         /**
    317          * Return the site-wide rate-limit error.
    318          *
    319          * @return WP_Error
    320          */
    321         private function global_error(): WP_Error {
    32296                return new WP_Error(
    323                         'chathearth_global_rate_limited',
    324                         __( 'The chatbot is temporarily unavailable due to high demand. Please try again later.', 'chathearth' ),
     97                        'chathearth_rate_limited',
     98                        $this->limit_message( 'hour' === $network, $bucket ),
    32599                        array( 'status' => 429 )
    326100                );
    … …  
    328102
    329103        /**
    330          * Return the per-minute rate-limit error.
     104         * The text of a minute or hour refusal: the owner's message with the limit that was reached and the window, or the
     105         * 1.4.9 text when the owner left the message empty.
    331106         *
    332          * @return WP_Error
     107         * @param bool                                                  $hour   Whether the hour limit was reached.
     108         * @param array{scope:string,key:string,minute:int,hour:int} $bucket The bucket that was counted.
    333109         */
    334         private function minute_error(): WP_Error {
    335                 return new WP_Error(
    336                         'chathearth_rate_limited',
    337                         __( 'Too many requests. Please wait a minute and try again.', 'chathearth' ),
    338                         array( 'status' => 429 )
     110        private function limit_message( bool $hour, array $bucket ): string {
     111                $template = isset( $this->settings['rate_limit_message'] ) && is_string( $this->settings['rate_limit_message'] ) ? $this->settings['rate_limit_message'] : '';
     112                $custom   = Limit_Message::render(
     113                        $template,
     114                        $hour ? $bucket['hour'] : $bucket['minute'],
     115                        $hour
     116                                /* translators: The window of a message limit, used in "You can send 10 messages per hour." Keep it a single lower-case word. */
     117                                ? __( 'hour', 'chathearth' )
     118                                /* translators: The window of a message limit, used in "You can send 10 messages per minute." Keep it a single lower-case word. */
     119                                : __( 'minute', 'chathearth' )
    339120                );
     121                if ( '' !== $custom ) {
     122                        return $custom;
     123                }
     124
     125                return $hour
     126                        ? __( 'Hourly message limit reached. Please try again later.', 'chathearth' )
     127                        : __( 'Too many requests. Please wait a minute and try again.', 'chathearth' );
    340128        }
    341129
    342130        /**
    343          * Return the per-hour rate-limit error.
     131         * Deny a storage failure while keeping the network and database details private.
    344132         *
    345          * @return WP_Error
     133         * @param 'global'|'network'|'user' $scope Scope type only.
    346134         */
    347         private function hour_error(): WP_Error {
    348                 return new WP_Error(
    349                         'chathearth_rate_limited',
    350                         __( 'Hourly message limit reached. Please try again later.', 'chathearth' ),
    351                         array( 'status' => 429 )
    352                 );
    353         }
    354 
    355         /**
    356          * Return the lock-contention error.
    357          *
    358          * @return WP_Error
    359          */
    360         private function busy_error(): WP_Error {
     135        private static function busy( string $scope ): WP_Error {
     136                Logger::warning( 'Chat quota counters are busy.', array( 'scope' => $scope ) );
    361137                return new WP_Error(
    362138                        'chathearth_rate_busy',
    … …  
    365141                );
    366142        }
    367 
    368         /**
    369          * Best-effort client IP.
    370          */
    371         private function client_ip(): string {
    372                 $ip = '';
    373                 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
    374                         $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
    375                 }
    376                 if ( false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
    377                         $ip = '0.0.0.0';
    378                 }
    379 
    380                 /**
    381                  * Filter the IP address used for chatbot rate limiting.
    382                  *
    383                  * @param string $ip Detected IP.
    384                  */
    385                 return (string) apply_filters( 'chathearth_client_ip', $ip );
    386         }
    387143}
  • chathearth/trunk/includes/Security/index.php

    r3663506 r3833468  
    1 <?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     1<?php // Silence is golden.
  • chathearth/trunk/includes/class-autoloader.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Simple PSR-4 style autoloader for ChatHearth.
     3 * Class autoloader, ported from 1.4.9 (research R1).
     4 *
     5 * Maps `ChatHearth\Sub\Class_Name` to `includes/Sub/class-class-name.php`.
    46 *
    57 * @package ChatHearth
    … …  
    2729
    2830        /**
    29          * Load a class file.
     31         * Load a class or interface file.
    3032         *
    3133         * @param string $fqcn Fully qualified class name.
    3234         */
    3335        public static function load( string $fqcn ): void {
     36                self::load_from( constant( 'CHATHEARTH_PATH' ), $fqcn );
     37        }
     38
     39        /**
     40         * Load a class or interface file from a plugin folder.
     41         *
     42         * The class file wins; when it does not exist, the interface file `interface-<name>.php` is tried.
     43         *
     44         * @param string $base Plugin folder with a trailing slash.
     45         * @param string $fqcn Fully qualified class name.
     46         */
     47        public static function load_from( string $base, string $fqcn ): void {
     48                $relative = self::relative_path( $fqcn );
     49                if ( null === $relative ) {
     50                        return;
     51                }
     52
     53                if ( is_readable( $base . $relative ) ) {
     54                        require_once $base . $relative;
     55                        return;
     56                }
     57
     58                $interface = self::interface_path( $fqcn );
     59                if ( null !== $interface && is_readable( $base . $interface ) ) {
     60                        require_once $base . $interface;
     61                }
     62        }
     63
     64        /**
     65         * Path of an interface file relative to the plugin folder, or null for a name outside `ChatHearth\`.
     66         *
     67         * A trailing `_Interface` is dropped: `Ai\Text_Generator_Interface` is `includes/Ai/interface-text-generator.php`.
     68         *
     69         * @param string $fqcn Fully qualified interface name.
     70         */
     71        public static function interface_path( string $fqcn ): ?string {
     72                $relative = self::relative_path( $fqcn );
     73                if ( null === $relative ) {
     74                        return null;
     75                }
     76
     77                // .../class-text-generator-interface.php becomes .../interface-text-generator.php.
     78                $path = (string) preg_replace( '#/class-([^/]+?)(?:-interface)?\.php$#', '/interface-$1.php', $relative );
     79
     80                return $path;
     81        }
     82
     83        /**
     84         * Path of a class file relative to the plugin folder, or null for a class outside `ChatHearth\`.
     85         *
     86         * @param string $fqcn Fully qualified class name.
     87         */
     88        public static function relative_path( string $fqcn ): ?string {
    3489                $prefix = __NAMESPACE__ . '\\';
    3590
    3691                if ( 0 !== strpos( $fqcn, $prefix ) ) {
    37                         return;
     92                        return null;
    3893                }
    3994
    40                 $relative   = substr( $fqcn, strlen( $prefix ) );
    41                 $parts      = explode( '\\', $relative );
    42                 $class_name = array_pop( $parts );
     95                $parts      = explode( '\\', substr( $fqcn, strlen( $prefix ) ) );
     96                $class_name = (string) array_pop( $parts );
    4397
    44                 // Convert Class_Name to class-class-name.php (WordPress style).
    45                 $file = 'class-' . str_replace( '_', '-', strtolower( preg_replace( '/([a-z])([A-Z])/', '$1-$2', $class_name ) ) ) . '.php';
     98                // Class_Name becomes class-class-name.php (WordPress file naming).
     99                $file = 'class-' . str_replace( '_', '-', strtolower( (string) preg_replace( '/([a-z])([A-Z])/', '$1-$2', $class_name ) ) ) . '.php';
     100                $dir  = 'includes/' . ( empty( $parts ) ? '' : implode( '/', $parts ) . '/' );
    46101
    47                 $dir = CHATHEARTH_PATH . 'includes/';
    48                 if ( ! empty( $parts ) ) {
    49                         $dir .= implode( '/', $parts ) . '/';
    50                 }
    51 
    52                 $path = $dir . $file;
    53                 if ( is_readable( $path ) ) {
    54                         require_once $path;
    55                 }
     102                return $dir . $file;
    56103        }
    57104}
  • chathearth/trunk/includes/class-logger.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Conditional error logging into WordPress debug.log.
     3 * Masking logger (FR-022, research R13).
     4 *
     5 * Writes one `[chathearth] …` line to the PHP error log only when WP_DEBUG_LOG is already on. It never
     6 * defines or forces WP_DEBUG / WP_DEBUG_LOG. Context values whose key looks like a secret are masked.
    47 *
    58 * @package ChatHearth
    … …  
    1518
    1619/**
    17  * Writes to PHP / WordPress error log only when WP_DEBUG_LOG is already enabled.
    18  * Does not define or force WP_DEBUG / WP_DEBUG_LOG.
     20 * Logger.
    1921 */
    2022final class Logger {
    2123
    2224        /**
    23          * Log an error-level message when WP_DEBUG_LOG is on.
     25         * Key fragments that mark a context value as secret.
     26         */
     27        private const SECRET_FRAGMENTS = array( 'key', 'secret', 'pass', 'token', 'auth', 'cookie', 'nonce', 'ip', 'email' );
     28
     29        /**
     30         * Replacement writer (tests); null writes to the PHP error log.
     31         *
     32         * @var callable|null
     33         */
     34        private static $writer = null;
     35
     36        /**
     37         * Forced on/off state (tests); null follows WP_DEBUG_LOG.
     38         *
     39         * @var bool|null
     40         */
     41        private static $enabled = null;
     42
     43        /**
     44         * Log an error-level message.
    2445         *
    2546         * @param string               $message Human-readable message.
    26          * @param array<string, mixed> $context Optional scalar context (no secrets).
     47         * @param array<string, mixed> $context Optional scalar context.
    2748         */
    2849        public static function error( string $message, array $context = array() ): void {
    29                 if ( ! defined( 'WP_DEBUG_LOG' ) || ! WP_DEBUG_LOG ) {
     50                self::write( $message, $context );
     51        }
     52
     53        /**
     54         * Log a warning-level message.
     55         *
     56         * @param string               $message Human-readable message.
     57         * @param array<string, mixed> $context Optional scalar context.
     58         */
     59        public static function warning( string $message, array $context = array() ): void {
     60                self::write( 'warning: ' . $message, $context );
     61        }
     62
     63        /**
     64         * Replace the writer (tests). Pass null to restore the default.
     65         *
     66         * @param callable|null $writer Receives the finished line.
     67         */
     68        public static function set_writer( ?callable $writer ): void {
     69                self::$writer = $writer;
     70        }
     71
     72        /**
     73         * Force logging on or off (tests). Pass null to follow WP_DEBUG_LOG.
     74         *
     75         * @param bool|null $enabled State.
     76         */
     77        public static function set_enabled( ?bool $enabled ): void {
     78                self::$enabled = $enabled;
     79        }
     80
     81        /**
     82         * Build and write one line.
     83         *
     84         * @param string               $message Message.
     85         * @param array<string, mixed> $context Context.
     86         */
     87        private static function write( string $message, array $context ): void {
     88                if ( ! self::is_enabled() ) {
    3089                        return;
    3190                }
    3291
    33                 $line = '[chathearth] ' . self::sanitize_line( $message );
    34 
    35                 if ( ! empty( $context ) ) {
    36                         $parts = array();
    37                         foreach ( $context as $key => $value ) {
    38                                 if ( ! is_scalar( $value ) && null !== $value ) {
    39                                         continue;
    40                                 }
    41                                 $parts[] = sanitize_key( (string) $key ) . '=' . self::sanitize_line( (string) $value );
     92                $line  = '[chathearth] ' . self::single_line( $message );
     93                $parts = array();
     94                foreach ( $context as $key => $value ) {
     95                        if ( ! is_scalar( $value ) && null !== $value ) {
     96                                continue;
    4297                        }
    43                         if ( ! empty( $parts ) ) {
    44                                 $line .= ' ' . implode( ' ', $parts );
    45                         }
     98                        $name    = (string) preg_replace( '/[^a-z0-9_\-]/', '', strtolower( (string) $key ) );
     99                        $parts[] = $name . '=' . ( self::is_secret_key( $name ) ? '[redacted]' : self::single_line( (string) $value ) );
     100                }
     101                if ( ! empty( $parts ) ) {
     102                        $line .= ' ' . implode( ' ', $parts );
    46103                }
    47104
    48                 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- intentional when WP_DEBUG_LOG is on.
     105                if ( null !== self::$writer ) {
     106                        call_user_func( self::$writer, $line );
     107                        return;
     108                }
     109
     110                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional: only runs when WP_DEBUG_LOG is on.
    49111                error_log( $line );
    50112        }
    51113
    52114        /**
    53          * Collapse newlines so log lines stay single-line.
     115         * Whether debug logging is on.
     116         */
     117        private static function is_enabled(): bool {
     118                if ( null !== self::$enabled ) {
     119                        return self::$enabled;
     120                }
     121
     122                return defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG;
     123        }
     124
     125        /**
     126         * Whether a context key looks like it holds a secret.
     127         *
     128         * @param string $name Normalised key.
     129         */
     130        private static function is_secret_key( string $name ): bool {
     131                foreach ( self::SECRET_FRAGMENTS as $fragment ) {
     132                        if ( false !== strpos( $name, $fragment ) ) {
     133                                return true;
     134                        }
     135                }
     136
     137                return false;
     138        }
     139
     140        /**
     141         * Collapse line breaks so a log entry stays one line.
    54142         *
    55143         * @param string $text Raw text.
    56144         */
    57         private static function sanitize_line( string $text ): string {
    58                 return trim( preg_replace( '/[\r\n]+/', ' ', $text ) ?? $text );
     145        private static function single_line( string $text ): string {
     146                return trim( (string) preg_replace( '/[\r\n]+/', ' ', $text ) );
    59147        }
    60148}
  • chathearth/trunk/includes/class-options.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Plugin options helper.
     3 * 1.4.9 settings facade (research R3): the static calls other code already makes.
    44 *
    55 * @package ChatHearth
    … …  
    1414}
    1515
     16use ChatHearth\Settings\Settings_Repository;
     17use ChatHearth\Settings\Settings_Schema;
     18
    1619/**
    17  * Reads and sanitizes plugin settings.
     20 * Static access to the settings. Other 1.4.9 helpers return with the feature that owns their behaviour.
    1821 */
    1922final class Options {
    … …  
    2730         */
    2831        public static function defaults(): array {
    29                 return array(
    30                         'chat_enabled'                      => true,
    31                         'icon_shape'                        => 'circle',
    32                         'icon_border_color'                 => '#1e293b',
    33                         'icon_background_color'             => '#0f172a',
    34                         'icon_color'                        => '#ffffff',
    35                         'icon_size'                         => 56,
    36                         'position'                          => 'bottom-right',
    37                         'popup_size'                        => 'medium',
    38                         'header_title'                      => 'Chat with us',
    39                         'user_bubble_color'                 => '#0f172a',
    40                         'assistant_bubble_color'            => '#e2e8f0',
    41                         'welcome_message'                   => 'Hi! How can I help you today?',
    42                         'starter_phrases'                   => "What do you offer?\nHow can I contact you?\nTell me about your services",
    43                         'ai_provider'                       => 'openai',
    44                         'ai_model'                          => defined( 'CHATHEARTH_DEFAULT_MODEL' ) ? CHATHEARTH_DEFAULT_MODEL : 'gpt-4.1',
    45                         'system_prompt'                     => 'You are a helpful assistant for this website. Be concise, friendly, and accurate. If you do not know something, say so.',
    46                         'rate_limit_per_minute'             => 10,
    47                         'rate_limit_per_hour'               => 60,
    48                         'global_rate_limit_per_minute'      => 60,
    49                         'global_rate_limit_per_hour'        => 500,
    50                         'global_limit_incident_threshold'   => 3,
    51                         'auto_disable_on_global_escalation' => true,
    52                         'recaptcha_site_key'                => '',
    53                         'recaptcha_secret_key'              => '',
    54                         'recaptcha_min_score'               => 0.5,
    55                         'max_message_length'                => 2000,
    56                         'max_history_messages'              => 20,
    57                         'content_moderation_enabled'        => true,
    58                         'moderation_use_openai'             => true,
    59                         'moderation_disallowed_phrases'     => '',
    60                         'moderation_block_message'          => 'Sorry, that message cannot be processed. Please rephrase and try again.',
    61                         'rag_enabled'                       => false,
    62                         'rag_vector_store'                  => 'builtin',
    63                         'rag_post_types'                    => array( 'post', 'page', 'product' ),
    64                         'rag_taxonomies'                    => array( 'category', 'post_tag', 'product_cat', 'product_tag' ),
    65                         'rag_include_site_identity'         => true,
    66                         'rag_include_woocommerce'           => true,
    67                         'rag_top_k'                         => 6,
    68                         'rag_chunk_size'                    => 1800,
    69                 );
     32                return Settings_Schema::defaults();
    7033        }
    7134
    7235        /**
    73          * Get all settings merged with defaults.
     36         * Every setting with a valid value.
    7437         *
    7538         * @return array<string, mixed>
    7639         */
    7740        public static function all(): array {
    78                 $stored = get_option( self::OPTION_KEY, array() );
    79                 if ( ! is_array( $stored ) ) {
    80                         $stored = array();
    81                 }
    82 
    83                 $merged                     = array_merge( self::defaults(), $stored );
    84                 $merged['rag_vector_store'] = 'builtin';
    85                 foreach ( self::retired_vector_store_keys() as $retired ) {
    86                         unset( $merged[ $retired ] );
    87                 }
    88 
    89                 return $merged;
     41                return self::repository()->all();
    9042        }
    9143
    9244        /**
    93          * Drop Chroma/Pinecone settings so RAG never depends on extra servers.
     45         * One setting.
     46         *
     47         * @param string $key      Setting key.
     48         * @param mixed  $fallback Returned when the key is not a declared setting.
     49         * @return mixed
    9450         */
    95         public static function maybe_use_wordpress_vector_store(): void {
    96                 $stored = get_option( self::OPTION_KEY, false );
    97                 if ( ! is_array( $stored ) ) {
    98                         return;
    99                 }
     51        public static function get( string $key, $fallback = null ) {
     52                $all = self::repository()->all();
    10053
    101                 $changed = false;
    102                 if ( ( $stored['rag_vector_store'] ?? 'builtin' ) !== 'builtin' ) {
    103                         $stored['rag_vector_store'] = 'builtin';
    104                         $changed                    = true;
    105                 }
    106 
    107                 foreach ( self::retired_vector_store_keys() as $key ) {
    108                         if ( array_key_exists( $key, $stored ) ) {
    109                                 unset( $stored[ $key ] );
    110                                 $changed = true;
    111                         }
    112                 }
    113 
    114                 if ( $changed ) {
    115                         update_option( self::OPTION_KEY, $stored );
    116                 }
     54                return array_key_exists( $key, $all ) ? $all[ $key ] : $fallback;
    11755        }
    11856
    11957        /**
    120          * Get a single setting.
    121          *
    122          * @param string $key     Setting key.
    123          * @param mixed  $fallback Optional fallback.
    124          * @return mixed
     58         * The repository from the container.
    12559         */
    126         public static function get( string $key, $fallback = null ) {
    127                 $all = self::all();
    128 
    129                 if ( array_key_exists( $key, $all ) ) {
    130                         return $all[ $key ];
    131                 }
    132 
    133                 return $fallback;
    134         }
    135 
    136         /**
    137          * Whether the chatbot is enabled.
    138          */
    139         public static function is_chat_enabled(): bool {
    140                 return (bool) self::get( 'chat_enabled', true );
    141         }
    142 
    143         /**
    144          * Whether Google reCAPTCHA v3 is active (both site and secret keys configured).
    145          */
    146         public static function is_recaptcha_enabled(): bool {
    147                 $site   = self::recaptcha_site_key();
    148                 $secret = self::recaptcha_secret_key();
    149 
    150                 return '' !== $site && '' !== $secret;
    151         }
    152 
    153         /**
    154          * Resolved reCAPTCHA v3 site key (environment/constant wins over settings).
    155          */
    156         public static function recaptcha_site_key(): string {
    157                 return self::resolved_secret( 'CHATHEARTH_RECAPTCHA_SITE_KEY', 'recaptcha_site_key' );
    158         }
    159 
    160         /**
    161          * Resolved reCAPTCHA v3 secret key (environment/constant wins over settings).
    162          */
    163         public static function recaptcha_secret_key(): string {
    164                 return self::resolved_secret( 'CHATHEARTH_RECAPTCHA_SECRET_KEY', 'recaptcha_secret_key' );
    165         }
    166 
    167         /**
    168          * Whether site/secret keys come from the server environment rather than plugin settings.
    169          */
    170         public static function recaptcha_keys_from_environment(): bool {
    171                 $site   = self::env_or_constant( 'CHATHEARTH_RECAPTCHA_SITE_KEY' );
    172                 $secret = self::env_or_constant( 'CHATHEARTH_RECAPTCHA_SECRET_KEY' );
    173 
    174                 return '' !== $site && '' !== $secret;
    175         }
    176 
    177         /**
    178          * Minimum v3 score (0–1) required to unlock chat.
    179          */
    180         public static function recaptcha_min_score(): float {
    181                 $score = (float) self::get( 'recaptcha_min_score', 0.5 );
    182                 if ( $score < 0 ) {
    183                         return 0.0;
    184                 }
    185                 if ( $score > 1 ) {
    186                         return 1.0;
    187                 }
    188 
    189                 return $score;
    190         }
    191 
    192         /**
    193          * Whether content moderation (keywords and/or OpenAI Moderations) is enabled.
    194          */
    195         public static function is_content_moderation_enabled(): bool {
    196                 return (bool) self::get( 'content_moderation_enabled', true );
    197         }
    198 
    199         /**
    200          * Whether the OpenAI Moderations API layer is enabled (requires master toggle too).
    201          */
    202         public static function is_moderation_openai_enabled(): bool {
    203                 return (bool) self::get( 'moderation_use_openai', true );
    204         }
    205 
    206         /**
    207          * Disallowed phrases as a list of strings (one per line in settings).
    208          *
    209          * @return list<string>
    210          */
    211         public static function moderation_disallowed_phrases_list(): array {
    212                 $raw   = (string) self::get( 'moderation_disallowed_phrases', '' );
    213                 $lines = preg_split( '/\r\n|\r|\n/', $raw );
    214                 if ( ! is_array( $lines ) ) {
    215                         return array();
    216                 }
    217 
    218                 $out = array();
    219                 foreach ( $lines as $line ) {
    220                         $line = trim( (string) $line );
    221                         if ( '' !== $line ) {
    222                                 $out[] = $line;
    223                         }
    224                 }
    225 
    226                 return $out;
    227         }
    228 
    229         /**
    230          * Supported AI providers for settings (v1: OpenAI only).
    231          *
    232          * @return array<string, string> Provider id => label.
    233          */
    234         public static function available_providers(): array {
    235                 return array(
    236                         'openai' => 'OpenAI',
    237                 );
    238         }
    239 
    240         /**
    241          * OpenAI chat models offered in settings.
    242          *
    243          * @return array<string, string> Model id => label.
    244          */
    245         public static function available_openai_models(): array {
    246                 return array(
    247                         'gpt-4.1'      => 'GPT-4.1',
    248                         'gpt-4.1-mini' => 'GPT-4.1 Mini',
    249                         'gpt-4.1-nano' => 'GPT-4.1 Nano',
    250                         'gpt-4o'       => 'GPT-4o',
    251                         'gpt-4o-mini'  => 'GPT-4o Mini',
    252                         'o4-mini'      => 'o4-mini',
    253                         'o3-mini'      => 'o3-mini',
    254                 );
    255         }
    256 
    257         /**
    258          * Starter phrases as a list of strings.
    259          *
    260          * @return list<string>
    261          */
    262         public static function starter_phrases_list(): array {
    263                 $raw   = (string) self::get( 'starter_phrases', '' );
    264                 $lines = preg_split( '/\r\n|\r|\n/', $raw );
    265                 if ( ! is_array( $lines ) ) {
    266                         return array();
    267                 }
    268 
    269                 $out = array();
    270                 foreach ( $lines as $line ) {
    271                         $line = trim( (string) $line );
    272                         if ( '' !== $line ) {
    273                                 $out[] = $line;
    274                         }
    275                 }
    276 
    277                 return $out;
    278         }
    279 
    280         /**
    281          * Sanitize settings array from the admin form.
    282          *
    283          * @param mixed $input Raw input.
    284          * @return array<string, mixed>
    285          */
    286         public static function sanitize( $input ): array {
    287                 $defaults = self::defaults();
    288                 $input    = is_array( $input ) ? $input : array();
    289                 $out      = self::all();
    290 
    291                 $out['chat_enabled'] = ! empty( $input['chat_enabled'] );
    292 
    293                 $shape             = isset( $input['icon_shape'] ) ? sanitize_key( (string) $input['icon_shape'] ) : $defaults['icon_shape'];
    294                 $out['icon_shape'] = in_array( $shape, array( 'circle', 'square' ), true ) ? $shape : $defaults['icon_shape'];
    295 
    296                 foreach ( array( 'icon_border_color', 'icon_background_color', 'icon_color', 'user_bubble_color', 'assistant_bubble_color' ) as $color_key ) {
    297                         if ( isset( $input[ $color_key ] ) ) {
    298                                 $color             = sanitize_hex_color( (string) $input[ $color_key ] );
    299                                 $out[ $color_key ] = $color ? $color : $defaults[ $color_key ];
    300                         }
    301                 }
    302 
    303                 $size             = isset( $input['icon_size'] ) ? absint( $input['icon_size'] ) : (int) $defaults['icon_size'];
    304                 $out['icon_size'] = max( 40, min( 96, $size ) );
    305 
    306                 $position        = isset( $input['position'] ) ? sanitize_key( (string) $input['position'] ) : $defaults['position'];
    307                 $out['position'] = in_array( $position, array( 'bottom-right', 'bottom-left' ), true ) ? $position : $defaults['position'];
    308 
    309                 $popup             = isset( $input['popup_size'] ) ? sanitize_key( (string) $input['popup_size'] ) : $defaults['popup_size'];
    310                 $out['popup_size'] = in_array( $popup, array( 'small', 'medium', 'large' ), true ) ? $popup : $defaults['popup_size'];
    311 
    312                 if ( isset( $input['header_title'] ) ) {
    313                         $out['header_title'] = sanitize_text_field( (string) $input['header_title'] );
    314                 }
    315 
    316                 if ( isset( $input['welcome_message'] ) ) {
    317                         $out['welcome_message'] = sanitize_textarea_field( (string) $input['welcome_message'] );
    318                 }
    319 
    320                 if ( isset( $input['starter_phrases'] ) ) {
    321                         $out['starter_phrases'] = sanitize_textarea_field( (string) $input['starter_phrases'] );
    322                 }
    323 
    324                 if ( isset( $input['system_prompt'] ) ) {
    325                         $out['system_prompt'] = sanitize_textarea_field( (string) $input['system_prompt'] );
    326                 }
    327 
    328                 $provider           = isset( $input['ai_provider'] ) ? sanitize_key( (string) $input['ai_provider'] ) : $defaults['ai_provider'];
    329                 $out['ai_provider'] = array_key_exists( $provider, self::available_providers() ) ? $provider : $defaults['ai_provider'];
    330 
    331                 $model           = isset( $input['ai_model'] ) ? sanitize_text_field( (string) $input['ai_model'] ) : $defaults['ai_model'];
    332                 $out['ai_model'] = array_key_exists( $model, self::available_openai_models() ) ? $model : $defaults['ai_model'];
    333 
    334                 $per_min                      = isset( $input['rate_limit_per_minute'] ) ? absint( $input['rate_limit_per_minute'] ) : (int) $defaults['rate_limit_per_minute'];
    335                 $out['rate_limit_per_minute'] = max( 1, min( 120, $per_min ) );
    336 
    337                 $per_hour                   = isset( $input['rate_limit_per_hour'] ) ? absint( $input['rate_limit_per_hour'] ) : (int) $defaults['rate_limit_per_hour'];
    338                 $out['rate_limit_per_hour'] = max( 1, min( 1000, $per_hour ) );
    339 
    340                 $g_min                               = isset( $input['global_rate_limit_per_minute'] ) ? absint( $input['global_rate_limit_per_minute'] ) : (int) $defaults['global_rate_limit_per_minute'];
    341                 $out['global_rate_limit_per_minute'] = max( 1, min( 1000, $g_min ) );
    342 
    343                 $g_hour                            = isset( $input['global_rate_limit_per_hour'] ) ? absint( $input['global_rate_limit_per_hour'] ) : (int) $defaults['global_rate_limit_per_hour'];
    344                 $out['global_rate_limit_per_hour'] = max( 1, min( 10000, $g_hour ) );
    345 
    346                 $threshold                              = isset( $input['global_limit_incident_threshold'] ) ? absint( $input['global_limit_incident_threshold'] ) : (int) $defaults['global_limit_incident_threshold'];
    347                 $out['global_limit_incident_threshold'] = max( 1, min( 50, $threshold ) );
    348 
    349                 $out['auto_disable_on_global_escalation'] = ! empty( $input['auto_disable_on_global_escalation'] );
    350 
    351                 if ( isset( $input['recaptcha_site_key'] ) ) {
    352                         $out['recaptcha_site_key'] = sanitize_text_field( (string) $input['recaptcha_site_key'] );
    353                 }
    354 
    355                 if ( ! empty( $input['recaptcha_clear_secret'] ) ) {
    356                         $out['recaptcha_secret_key'] = '';
    357                 } elseif ( isset( $input['recaptcha_secret_key'] ) ) {
    358                         $secret = trim( (string) $input['recaptcha_secret_key'] );
    359                         // Leave blank to keep the existing secret.
    360                         if ( '' !== $secret ) {
    361                                 $out['recaptcha_secret_key'] = sanitize_text_field( $secret );
    362                         }
    363                 }
    364 
    365                 if ( isset( $input['recaptcha_min_score'] ) ) {
    366                         $score                      = (float) $input['recaptcha_min_score'];
    367                         $out['recaptcha_min_score'] = max( 0.0, min( 1.0, round( $score, 2 ) ) );
    368                 }
    369 
    370                 $max_len                   = isset( $input['max_message_length'] ) ? absint( $input['max_message_length'] ) : (int) $defaults['max_message_length'];
    371                 $out['max_message_length'] = max( 100, min( 8000, $max_len ) );
    372 
    373                 $max_hist                    = isset( $input['max_history_messages'] ) ? absint( $input['max_history_messages'] ) : (int) $defaults['max_history_messages'];
    374                 $out['max_history_messages'] = max( 2, min( 50, $max_hist ) );
    375 
    376                 $out['content_moderation_enabled'] = ! empty( $input['content_moderation_enabled'] );
    377                 $out['moderation_use_openai']      = ! empty( $input['moderation_use_openai'] );
    378 
    379                 if ( isset( $input['moderation_disallowed_phrases'] ) ) {
    380                         $out['moderation_disallowed_phrases'] = sanitize_textarea_field( (string) $input['moderation_disallowed_phrases'] );
    381                 }
    382 
    383                 if ( isset( $input['moderation_block_message'] ) ) {
    384                         $msg                             = sanitize_text_field( (string) $input['moderation_block_message'] );
    385                         $out['moderation_block_message'] = '' !== $msg ? $msg : (string) $defaults['moderation_block_message'];
    386                 }
    387 
    388                 if ( isset( $input['rag_vector_store'] ) ) {
    389                         $out['rag_enabled'] = ! empty( $input['rag_enabled'] );
    390 
    391                         $out['rag_vector_store'] = 'builtin';
    392 
    393                         $out['rag_post_types'] = self::sanitize_key_list( $input['rag_post_types'] ?? array() );
    394                         $out['rag_taxonomies'] = self::sanitize_key_list( $input['rag_taxonomies'] ?? array() );
    395 
    396                         $out['rag_include_site_identity'] = ! empty( $input['rag_include_site_identity'] );
    397                         $out['rag_include_woocommerce']   = ! empty( $input['rag_include_woocommerce'] );
    398 
    399                         $top_k            = isset( $input['rag_top_k'] ) ? absint( $input['rag_top_k'] ) : (int) $defaults['rag_top_k'];
    400                         $out['rag_top_k'] = max( 1, min( 12, $top_k ) );
    401 
    402                         $chunk                 = isset( $input['rag_chunk_size'] ) ? absint( $input['rag_chunk_size'] ) : (int) $defaults['rag_chunk_size'];
    403                         $out['rag_chunk_size'] = max( 400, min( 4000, $chunk ) );
    404                 }
    405 
    406                 return $out;
    407         }
    408 
    409         /**
    410          * Whether RAG retrieval is enabled.
    411          */
    412         public static function is_rag_enabled(): bool {
    413                 return (bool) self::get( 'rag_enabled', false );
    414         }
    415 
    416         /**
    417          * Selected post types for the knowledge base.
    418          *
    419          * @return list<string>
    420          */
    421         public static function rag_post_types(): array {
    422                 $types = self::get( 'rag_post_types', array() );
    423                 return self::sanitize_key_list( is_array( $types ) ? $types : array() );
    424         }
    425 
    426         /**
    427          * Selected taxonomies for the knowledge base.
    428          *
    429          * @return list<string>
    430          */
    431         public static function rag_taxonomies(): array {
    432                 $taxes = self::get( 'rag_taxonomies', array() );
    433                 return self::sanitize_key_list( is_array( $taxes ) ? $taxes : array() );
    434         }
    435 
    436         /**
    437          * Whether site identity is indexed.
    438          */
    439         public static function rag_include_site_identity(): bool {
    440                 return (bool) self::get( 'rag_include_site_identity', true );
    441         }
    442 
    443         /**
    444          * Whether the WooCommerce store summary is indexed.
    445          */
    446         public static function rag_include_woocommerce(): bool {
    447                 return (bool) self::get( 'rag_include_woocommerce', true );
    448         }
    449 
    450         /**
    451          * Public post types offered in the Knowledge Base UI (no attachments).
    452          *
    453          * @return array<array-key, string> slug => label.
    454          */
    455         public static function available_content_post_types(): array {
    456                 $objects = get_post_types( array( 'public' => true ), 'objects' );
    457                 $out     = array();
    458                 foreach ( $objects as $name => $object ) {
    459                         if ( 'attachment' === $name ) {
    460                                 continue;
    461                         }
    462                         $label        = isset( $object->labels->name ) ? (string) $object->labels->name : (string) $name;
    463                         $out[ $name ] = $label;
    464                 }
    465 
    466                 return $out;
    467         }
    468 
    469         /**
    470          * Public taxonomies offered in the Knowledge Base UI.
    471          *
    472          * @return array<array-key, string> slug => label.
    473          */
    474         public static function available_content_taxonomies(): array {
    475                 $objects = get_taxonomies( array( 'public' => true ), 'objects' );
    476                 $out     = array();
    477                 foreach ( $objects as $name => $object ) {
    478                         $label                 = isset( $object->labels->name ) ? (string) $object->labels->name : (string) $name;
    479                         $out[ (string) $name ] = $label;
    480                 }
    481 
    482                 return $out;
    483         }
    484 
    485         /**
    486          * Settings keys for stores that required extra software or accounts.
    487          *
    488          * @return list<string>
    489          */
    490         private static function retired_vector_store_keys(): array {
    491                 return array(
    492                         'rag_chroma_url',
    493                         'rag_chroma_collection',
    494                         'rag_chroma_tenant',
    495                         'rag_chroma_database',
    496                         'rag_pinecone_api_key',
    497                         'rag_pinecone_host',
    498                         'rag_pinecone_namespace',
    499                 );
    500         }
    501 
    502         /**
    503          * Read a secret from a PHP constant, then the process environment, then settings.
    504          *
    505          * @param string $env_name Constant / environment variable name.
    506          * @param string $option_key Settings key.
    507          */
    508         private static function resolved_secret( string $env_name, string $option_key ): string {
    509                 $from_env = self::env_or_constant( $env_name );
    510                 if ( '' !== $from_env ) {
    511                         return $from_env;
    512                 }
    513 
    514                 return trim( (string) self::get( $option_key, '' ) );
    515         }
    516 
    517         /**
    518          * Value from a PHP constant or environment variable.
    519          *
    520          * @param string $name Constant and environment variable name.
    521          */
    522         private static function env_or_constant( string $name ): string {
    523                 /**
    524                  * Short-circuit environment/constant secret lookup (tests).
    525                  *
    526                  * Return a string to use that value (empty string disables the env key).
    527                  *
    528                  * @param string|null $pre  Existing override.
    529                  * @param string      $name Variable name.
    530                  */
    531                 $pre = apply_filters( 'chathearth_pre_env_secret', null, $name );
    532                 if ( is_string( $pre ) ) {
    533                         return trim( $pre );
    534                 }
    535                 if ( defined( $name ) ) {
    536                         $value = constant( $name );
    537                         if ( is_string( $value ) || is_numeric( $value ) ) {
    538                                 $value = trim( (string) $value );
    539                                 if ( '' !== $value ) {
    540                                         return $value;
    541                                 }
    542                         }
    543                 }
    544 
    545                 $env = getenv( $name );
    546                 if ( is_string( $env ) ) {
    547                         $env = trim( $env );
    548                         if ( '' !== $env ) {
    549                                 return $env;
    550                         }
    551                 }
    552 
    553                 return '';
    554         }
    555 
    556         /**
    557          * Sanitize a list of WP slugs.
    558          *
    559          * @param mixed $value Raw list.
    560          * @return list<string>
    561          */
    562         private static function sanitize_key_list( $value ): array {
    563                 if ( ! is_array( $value ) ) {
    564                         return array();
    565                 }
    566 
    567                 $out = array();
    568                 foreach ( $value as $item ) {
    569                         $key = sanitize_key( (string) $item );
    570                         if ( '' !== $key ) {
    571                                 $out[] = $key;
    572                         }
    573                 }
    574 
    575                 return array_values( array_unique( $out ) );
     60        private static function repository(): Settings_Repository {
     61                return Plugin::instance()->get( Settings_Repository::class );
    57662        }
    57763}
  • chathearth/trunk/includes/class-plugin.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Main plugin bootstrap.
     3 * Plugin container and start-up (research R2).
     4 *
     5 * A small lazy service container: each service is built once per request, on first use. It holds services,
     6 * never request state.
    47 *
    58 * @package ChatHearth
    … …  
    1518
    1619use ChatHearth\Admin\Admin_Notices;
     20use ChatHearth\Admin\Plugin_Links;
    1721use ChatHearth\Admin\Privacy;
    18 use ChatHearth\Admin\Settings_Page;
    19 use ChatHearth\Frontend\Assets;
    20 use ChatHearth\Rag\Current_Page;
    21 use ChatHearth\Rag\Indexer;
     22use ChatHearth\Admin\Reenable_Action;
     23use ChatHearth\Admin\Settings\Abuse_Alert_Actions;
     24use ChatHearth\Admin\Settings\Rate_Limit_Reset_Action;
     25use ChatHearth\Admin\Settings\Settings_Page;
     26use ChatHearth\Admin\Settings\Site_Status;
     27use ChatHearth\Ai\Connectors_Generator;
     28use ChatHearth\Ai\Embedding_Client;
     29use ChatHearth\Ai\Openai_Embedding_Client;
     30use ChatHearth\Chat\Ban_Stage;
     31use ChatHearth\Chat\Catalog_Stage;
     32use ChatHearth\Chat\Chat_Pipeline;
     33use ChatHearth\Chat\Generation_Stage;
     34use ChatHearth\Chat\Honeypot_Stage;
     35use ChatHearth\Chat\Input_Stage;
     36use ChatHearth\Chat\Instructions_Stage;
     37use ChatHearth\Chat\Limits_Stage;
     38use ChatHearth\Chat\Moderation_Stage;
     39use ChatHearth\Chat\Page_Stage;
     40use ChatHearth\Chat\Reply_Stage;
     41use ChatHearth\Chat\Retrieval_Stage;
     42use ChatHearth\Chat\Verification_Stage;
     43use ChatHearth\Commerce\Cart_Service;
     44use ChatHearth\Commerce\Catalog_Block;
     45use ChatHearth\Commerce\Product_Card;
     46use ChatHearth\Commerce\Product_Catalog;
     47use ChatHearth\Commerce\Product_Name_Index;
     48use ChatHearth\Commerce\Product_Name_Index_Invalidator;
     49use ChatHearth\Commerce\Product_Name_Normaliser;
     50use ChatHearth\Commerce\Store_Links;
     51use ChatHearth\Content\Markdown_Exporter;
     52use ChatHearth\Frontend\Current_Page;
     53use ChatHearth\Frontend\Launcher_Icon;
     54use ChatHearth\Frontend\Widget;
     55use ChatHearth\Frontend\Widget_Config;
     56use ChatHearth\Grounding\Current_Page_Section;
     57use ChatHearth\Grounding\Page_Link_Matcher;
     58use ChatHearth\Grounding\Page_Resolver;
     59use ChatHearth\Grounding\Site_Context;
     60use ChatHearth\Grounding\Site_Context_Invalidator;
     61use ChatHearth\Grounding\Site_Grounding;
     62use ChatHearth\Jobs\Job_Runner;
     63use ChatHearth\Jobs\Job_Runner_Factory;
     64use ChatHearth\Kb\Change_Listener;
     65use ChatHearth\Kb\Chunker;
     66use ChatHearth\Kb\Entry_Presenter;
     67use ChatHearth\Kb\Entry_Repository;
     68use ChatHearth\Kb\Kb_Entry_Toggle;
     69use ChatHearth\Kb\Markdown_Files;
     70use ChatHearth\Kb\Passage_Repository;
     71use ChatHearth\Kb\Sources;
     72use ChatHearth\Kb\Status_Report;
     73use ChatHearth\Kb\Store_Check;
     74use ChatHearth\Kb\Sync_Job;
     75use ChatHearth\Kb\Sync_State;
     76use ChatHearth\Lifecycle\Activator;
     77use ChatHearth\Migrations\Migration_Runner;
     78use ChatHearth\Moderation\Content_Moderation;
     79use ChatHearth\Moderation\Openai_Moderation_Client;
     80use ChatHearth\Moderation\Verdict_Cache;
     81use ChatHearth\Rag\Comparison_Detector;
     82use ChatHearth\Rag\Knowledge_Section;
    2283use ChatHearth\Rag\Retriever;
    23 use ChatHearth\Rag\Schema;
    24 use ChatHearth\Rag\Site_Grounding;
     84use ChatHearth\Rag\Source_Gate;
     85use ChatHearth\Readiness\Readiness_Checker;
    2586use ChatHearth\Rest\Cart_Controller;
    2687use ChatHearth\Rest\Chat_Controller;
    2788use ChatHearth\Rest\Kb_Controller;
     89use ChatHearth\Rest\Kb_Permission;
     90use ChatHearth\Rest\Kb_Status_Controller;
     91use ChatHearth\Rest\Nonce_Controller;
     92use ChatHearth\Rest\Nonce_Throttle;
     93use ChatHearth\Rest\Recaptcha_Controller;
     94use ChatHearth\Rest\Request_Guard;
     95use ChatHearth\Security\Access_Check;
     96use ChatHearth\Security\Client_Address;
     97use ChatHearth\Security\Counter_Generation;
     98use ChatHearth\Security\Counters;
     99use ChatHearth\Security\Escalation;
     100use ChatHearth\Security\Escalation_Mailer;
     101use ChatHearth\Security\Human_Check;
     102use ChatHearth\Security\Human_Pass;
     103use ChatHearth\Security\Option_Lock;
     104use ChatHearth\Security\Quota_Policy;
     105use ChatHearth\Security\Rate_Limiter;
     106use ChatHearth\Security\Rearm_Pause;
     107use ChatHearth\Security\Reenable_Link;
     108use ChatHearth\Security\Recaptcha_V3;
     109use ChatHearth\Security\Trusted_Proxy;
     110use ChatHearth\Settings\Server_Overrides;
     111use ChatHearth\Settings\Settings_Repository;
     112use ChatHearth\Settings\Settings_Sanitizer;
    28113
    29114/**
    30  * Plugin singleton.
     115 * Plugin singleton and service container.
    31116 */
    32117final class Plugin {
    … …  
    38123         */
    39124        private static $instance = null;
     125
     126        /**
     127         * Services built so far, by class name.
     128         *
     129         * @var array<string, object>
     130         */
     131        private $services = array();
     132
     133        /**
     134         * Whether boot() already ran on this instance.
     135         *
     136         * @var bool
     137         */
     138        private $booted = false;
    40139
    41140        /**
    … …  
    51150
    52151        /**
    53          * Activation defaults.
    54          */
    55         public static function activate(): void {
    56                 if ( false === get_option( Options::OPTION_KEY ) ) {
    57                         add_option( Options::OPTION_KEY, Options::defaults() );
    58                 }
    59                 Schema::install();
    60                 Indexer::instance()->ensure_cron();
    61         }
    62 
    63         /**
    64          * Wire hooks.
    65          */
    66         public function init(): void {
    67                 Schema::maybe_install();
    68                 Options::maybe_use_wordpress_vector_store();
    69                 ( new Admin_Notices() )->register();
    70                 ( new Privacy() )->register();
    71                 ( new Settings_Page() )->register();
    72                 ( new Assets() )->register();
    73                 Indexer::instance()->register();
    74                 ( new Site_Grounding() )->register();
    75                 Current_Page::instance()->register();
    76                 Retriever::instance()->register();
    77 
    78                 add_action( 'rest_api_init', array( $this, 'register_rest' ) );
    79         }
    80 
    81         /**
    82          * Register REST routes.
    83          */
    84         public function register_rest(): void {
    85                 ( new Chat_Controller() )->register_routes();
    86                 ( new Cart_Controller() )->register_routes();
    87                 ( new Kb_Controller() )->register_routes();
    88         }
    89 
    90         /**
    91          * Whether AI Client + OpenAI provider look available.
    92          *
    93          * Always reaches `chathearth_openai_ready` so callers (and tests) can
    94          * override detection even when WordPress AI support is missing.
     152         * Drop the shared instance and its services (tests).
     153         */
     154        public static function reset(): void {
     155                self::$instance = null;
     156        }
     157
     158        /**
     159         * A service, built on first use and then shared.
     160         *
     161         * @template T of object
     162         * @param class-string<T> $service_class Service class.
     163         * @return T
     164         * @throws \InvalidArgumentException For a class the container does not know.
     165         */
     166        public function get( string $service_class ) {
     167                if ( ! isset( $this->services[ $service_class ] ) ) {
     168                        $this->services[ $service_class ] = $this->build( $service_class );
     169                }
     170
     171                /** @var T $service */
     172                $service = $this->services[ $service_class ];
     173
     174                return $service;
     175        }
     176
     177        /**
     178         * Whether the AI Client and the OpenAI provider are ready (1.4.9 facade).
     179         *
     180         * Computed on every call and always passes through the `chathearth_openai_ready` filter.
    95181         */
    96182        public static function is_openai_ready(): bool {
    97                 $ready = false;
    98 
    99                 if ( function_exists( 'wp_supports_ai' ) && wp_supports_ai() && function_exists( 'wp_ai_client_prompt' ) ) {
    100                         if ( ! function_exists( 'is_plugin_active' ) ) {
    101                                 require_once ABSPATH . 'wp-admin/includes/plugin.php';
    102                         }
    103 
    104                         if ( is_plugin_active( 'ai-provider-for-openai/plugin.php' ) ) {
    105                                 if ( function_exists( 'wp_is_connector_registered' ) && ! wp_is_connector_registered( 'openai' ) ) {
    106                                         $ready = false;
    107                                 } else {
    108                                         $ready = self::is_provider_configured( 'openai' );
    109                                 }
    110                         }
    111                 }
    112 
    113                 /**
    114                  * Whether OpenAI is ready for ChatHearth (Connectors key present).
    115                  *
    116                  * The public chat launcher stays hidden until this is true.
    117                  *
    118                  * @since 1.4.7
    119                  *
    120                  * @param bool $ready Detected readiness.
    121                  */
    122                 return (bool) apply_filters( 'chathearth_openai_ready', $ready );
    123         }
    124 
    125         /**
    126          * Whether an AI provider is configured with working credentials.
    127          *
    128          * Uses the WordPress AI Client registry so the plugin never reads provider
    129          * API keys directly — those credentials were granted by the user to
    130          * WordPress, not to this plugin. Result is not cached so removing a key
    131          * (or adding one) is reflected immediately.
    132          *
    133          * @param string $provider Provider id (e.g. "openai").
    134          */
    135         private static function is_provider_configured( string $provider ): bool {
    136                 if ( ! class_exists( '\\WordPress\\AiClient\\AiClient' ) ) {
    137                         return false;
    138                 }
    139 
    140                 try {
    141                         $registry = \WordPress\AiClient\AiClient::defaultRegistry();
    142                         return $registry->hasProvider( $provider ) && $registry->isProviderConfigured( $provider );
    143                 } catch ( \Throwable $e ) {
    144                         return false;
    145                 }
     183                return self::instance()->get( Readiness_Checker::class )->is_ready();
     184        }
     185
     186        /**
     187         * Wire the hooks and keep the plugin's storage in place. Runs on `plugins_loaded`, priority 5.
     188         */
     189        public function boot(): void {
     190                if ( $this->booted ) {
     191                        return;
     192                }
     193                $this->booted = true;
     194
     195                // Order of contracts/lifecycle.md: storage check, then the upgrade runner.
     196                Activator::ensure();
     197                $this->get( Migration_Runner::class )->run();
     198                $this->get( Settings_Repository::class )->register();
     199                // Content changes happen in the admin, REST, cron and WP-CLI too (feature 009, R4).
     200                $this->get( Site_Context_Invalidator::class )->register();
     201                // The product name index (feature 013): changes are seen in the admin, REST, imports and WP-CLI too, and the
     202                // background job builds it. Without WooCommerce both do nothing.
     203                $this->get( Product_Name_Index_Invalidator::class )->register();
     204                add_action( Product_Name_Index::JOB_HOOK, array( $this->get( Product_Name_Index::class ), 'build' ) );
     205                // The knowledge base index (feature 010): the sync step, the hourly safety net and the settings trigger, and the
     206                // progress route. Content changes and steps happen in the admin, REST, cron and WP-CLI too.
     207                $this->get( Sync_Job::class )->register();
     208                $this->get( Change_Listener::class )->register();
     209                $this->get( Kb_Permission::class )->register();
     210                $this->get( Kb_Status_Controller::class )->register();
     211                $this->get( Kb_Controller::class )->register();
     212                $this->get( Request_Guard::class )->register();
     213                $this->get( Chat_Controller::class )->register();
     214                $this->get( Cart_Controller::class )->register();
     215                $this->get( Nonce_Controller::class )->register();
     216                $this->get( Recaptcha_Controller::class )->register();
     217                $this->get( Widget::class )->register();
     218                if ( is_admin() ) {
     219                        // The notices belong to the admin and show to administrators only; a front end request never prints one (feature 015, FR-017).
     220                        $this->get( Admin_Notices::class )->register();
     221                }
     222                if ( is_admin() && ! is_network_admin() ) {
     223                        $this->get( Settings_Page::class )->register();
     224                        $this->get( Abuse_Alert_Actions::class )->register();
     225                        $this->get( Rate_Limit_Reset_Action::class )->register();
     226                        $this->get( Reenable_Action::class )->register();
     227                        $this->get( Rearm_Pause::class )->register();
     228                        $this->get( Plugin_Links::class )->register();
     229                        $this->get( Privacy::class )->register();
     230                }
     231        }
     232
     233        /**
     234         * Builds a service.
     235         *
     236         * @param string $service_class Service class.
     237         * @throws \InvalidArgumentException For a class the container does not know.
     238         */
     239        private function build( string $service_class ): object {
     240                switch ( $service_class ) {
     241                        case Settings_Repository::class:
     242                                return new Settings_Repository( $this->get( Server_Overrides::class ), $this->get( Settings_Sanitizer::class ) );
     243                        case Migration_Runner::class:
     244                                return new Migration_Runner( $this->get( Settings_Repository::class ) );
     245                        case Readiness_Checker::class:
     246                                return new Readiness_Checker();
     247                        case Admin_Notices::class:
     248                                return new Admin_Notices( $this->get( Readiness_Checker::class ) );
     249                        case Plugin_Links::class:
     250                                return new Plugin_Links();
     251                        case Privacy::class:
     252                                return new Privacy();
     253                        case Reenable_Action::class:
     254                                return new Reenable_Action( $this->get( Settings_Repository::class ), $this->get( Reenable_Link::class ) );
     255                        case Rate_Limit_Reset_Action::class:
     256                                return new Rate_Limit_Reset_Action( $this->get( Counter_Generation::class ) );
     257                        case Counter_Generation::class:
     258                                return new Counter_Generation();
     259                        case Abuse_Alert_Actions::class:
     260                                return new Abuse_Alert_Actions( $this->get( Settings_Repository::class ) );
     261                        case Site_Status::class:
     262                                return new Site_Status( $this->get( Readiness_Checker::class ) );
     263                        case Settings_Page::class:
     264                                return new Settings_Page( $this->get( Settings_Repository::class ), $this->get( Readiness_Checker::class ), $this->get( Site_Status::class ), $this->get( Status_Report::class ) );
     265                        case Request_Guard::class:
     266                                return new Request_Guard();
     267                        case Chat_Controller::class:
     268                                return new Chat_Controller( $this->get( Settings_Repository::class ), $this->get( Chat_Pipeline::class ) );
     269                        case Cart_Service::class:
     270                                return new Cart_Service( $this->get( Product_Catalog::class ), $this->get( Product_Card::class ) );
     271                        case Cart_Controller::class:
     272                                return new Cart_Controller( $this->get( Settings_Repository::class ), $this->get( Chat_Controller::class ), $this->get( Access_Check::class ), $this->get( Client_Address::class ), $this->get( Counters::class ), $this->get( Cart_Service::class ) );
     273                        case Recaptcha_Controller::class:
     274                                return new Recaptcha_Controller( $this->get( Settings_Repository::class ), $this->get( Chat_Controller::class ), \Closure::fromCallable( array( $this, 'check_human' ) ), $this->get( Access_Check::class ) );
     275                        case Widget::class:
     276                                return new Widget( $this->get( Settings_Repository::class ), $this->get( Readiness_Checker::class ), $this->get( Widget_Config::class ), $this->get( Launcher_Icon::class ) );
     277                        case Widget_Config::class:
     278                                return new Widget_Config( $this->get( Settings_Repository::class ), $this->get( Current_Page::class ), $this->get( Store_Links::class ) );
     279                        case Current_Page::class:
     280                                return new Current_Page();
     281                        case Launcher_Icon::class:
     282                                return new Launcher_Icon();
     283                        case Nonce_Controller::class:
     284                                return new Nonce_Controller( $this->get( Settings_Repository::class ), $this->get( Nonce_Throttle::class ), $this->get( Client_Address::class ), $this->get( Access_Check::class ) );
     285                        case Nonce_Throttle::class:
     286                                return new Nonce_Throttle();
     287                        case Client_Address::class:
     288                                return new Client_Address( new Trusted_Proxy( $this->get( Settings_Repository::class )->all() ) );
     289                        case Quota_Policy::class:
     290                                return new Quota_Policy( $this->get( Client_Address::class ) );
     291                        case Option_Lock::class:
     292                                return new Option_Lock();
     293                        case Counters::class:
     294                                return new Counters( $this->get( Option_Lock::class ), null, $this->get( Counter_Generation::class ) );
     295                        case Escalation::class:
     296                                return new Escalation( $this->get( Settings_Repository::class ), $this->get( Counters::class ), $this->get( Rearm_Pause::class ), $this->get( Reenable_Link::class ), new Escalation_Mailer(), $this->get( Option_Lock::class ) );
     297                        case Rearm_Pause::class:
     298                                return new Rearm_Pause( $this->get( Settings_Repository::class ) );
     299                        case Reenable_Link::class:
     300                                return new Reenable_Link();
     301                        case Access_Check::class:
     302                                return new Access_Check( $this->get( Client_Address::class ) );
     303                        case Ban_Stage::class:
     304                                return new Ban_Stage( array( $this->get( Access_Check::class ), 'refusal' ) );
     305                        case Honeypot_Stage::class:
     306                                return new Honeypot_Stage(
     307                                        static function ( string $value, array $settings ): ?\WP_Error {
     308                                                if ( ! (bool) ( $settings['honeypot_enabled'] ?? true ) || '' === trim( $value ) ) {
     309                                                        return null;
     310                                                }
     311                                                // The answer of a failed generation, so a bot learns nothing from it. The value is never logged.
     312                                                Logger::warning( 'Bot trap filled.' );
     313                                                return Chat_Pipeline::generic_error();
     314                                        }
     315                                );
     316                        case Verification_Stage::class:
     317                                return new Verification_Stage( \Closure::fromCallable( array( $this, 'check_human' ) ) );
     318                        case Limits_Stage::class:
     319                                return new Limits_Stage(
     320                                        function ( array $settings ): ?\WP_Error {
     321                                                $limiter = new Rate_Limiter( $this->get( Counters::class ), $this->get( Client_Address::class ), $settings, array( $this->get( Escalation::class ), 'record_incident' ), $this->get( Quota_Policy::class ) );
     322                                                return $limiter->consume();
     323                                        }
     324                                );
     325                        case Verdict_Cache::class:
     326                                return new Verdict_Cache();
     327                        case Moderation_Stage::class:
     328                                return new Moderation_Stage(
     329                                        function ( string $message, array $history, array $settings ): ?\WP_Error {
     330                                                $moderation = new Content_Moderation(
     331                                                        $settings,
     332                                                        $this->get( Readiness_Checker::class ),
     333                                                        $this->get( Verdict_Cache::class ),
     334                                                        new Openai_Moderation_Client( (float) $settings['moderation_timeout'] )
     335                                                );
     336                                                return $moderation->check( $message, $history );
     337                                        }
     338                                );
     339                        case Chat_Pipeline::class:
     340                                return new Chat_Pipeline(
     341                                        array(
     342                                                $this->get( Ban_Stage::class ),
     343                                                $this->get( Honeypot_Stage::class ),
     344                                                new Input_Stage(),
     345                                                $this->get( Verification_Stage::class ),
     346                                                $this->get( Limits_Stage::class ),
     347                                                $this->get( Moderation_Stage::class ),
     348                                                new Page_Stage( $this->get( Page_Resolver::class ) ),
     349                                                new Retrieval_Stage( $this->get( Retriever::class ), $this->get( Readiness_Checker::class ) ),
     350                                                new Catalog_Stage( $this->get( Product_Catalog::class ), $this->get( Product_Name_Index::class ), $this->get( Comparison_Detector::class ) ),
     351                                                new Instructions_Stage( $this->get( Readiness_Checker::class ), $this->get( Site_Grounding::class ), $this->get( Current_Page_Section::class ), $this->get( Knowledge_Section::class ) ),
     352                                                new Generation_Stage( $this->get( Connectors_Generator::class ) ),
     353                                                new Reply_Stage( $this->get( Store_Links::class ), $this->get( Page_Link_Matcher::class ), $this->get( Product_Card::class ) ),
     354                                        )
     355                                );
     356                        case Connectors_Generator::class:
     357                                return new Connectors_Generator();
     358                        case Store_Links::class:
     359                                return new Store_Links();
     360                        case Markdown_Exporter::class:
     361                                return new Markdown_Exporter();
     362                        case Site_Context::class:
     363                                return new Site_Context( $this->get( Markdown_Exporter::class ) );
     364                        case Site_Context_Invalidator::class:
     365                                return new Site_Context_Invalidator( $this->get( Site_Context::class ) );
     366                        case Site_Grounding::class:
     367                                return new Site_Grounding( $this->get( Site_Context::class ) );
     368                        case Current_Page_Section::class:
     369                                return new Current_Page_Section();
     370                        case Page_Resolver::class:
     371                                return new Page_Resolver(
     372                                        $this->get( Markdown_Exporter::class ),
     373                                        static function (): string {
     374                                                return home_url( '/' );
     375                                        }
     376                                );
     377                        case Page_Link_Matcher::class:
     378                                return new Page_Link_Matcher();
     379                        case Product_Card::class:
     380                                return new Product_Card();
     381                        case Product_Catalog::class:
     382                                return new Product_Catalog( $this->get( Product_Card::class ) );
     383                        case Product_Name_Normaliser::class:
     384                                return new Product_Name_Normaliser();
     385                        case Product_Name_Index::class:
     386                                return new Product_Name_Index( $this->get( Product_Name_Normaliser::class ), $this->get( Job_Runner::class ), $this->get( Option_Lock::class ), $this->get( Product_Catalog::class ) );
     387                        case Product_Name_Index_Invalidator::class:
     388                                return new Product_Name_Index_Invalidator( $this->get( Product_Name_Index::class ), $this->get( Product_Catalog::class ) );
     389                        case Job_Runner::class:
     390                                return Job_Runner_Factory::make();
     391                        case Embedding_Client::class:
     392                                return new Openai_Embedding_Client();
     393                        case Source_Gate::class:
     394                                return new Source_Gate( $this->get( Markdown_Exporter::class ), $this->get( Sources::class ) );
     395                        case Comparison_Detector::class:
     396                                return new Comparison_Detector();
     397                        case Catalog_Block::class:
     398                                return new Catalog_Block();
     399                        case Knowledge_Section::class:
     400                                return new Knowledge_Section( $this->get( Catalog_Block::class ), $this->get( Product_Catalog::class ) );
     401                        case Retriever::class:
     402                                return new Retriever(
     403                                        $this->get( Embedding_Client::class ),
     404                                        $this->get( Passage_Repository::class ),
     405                                        $this->get( Entry_Repository::class ),
     406                                        $this->get( Source_Gate::class ),
     407                                        $this->get( Comparison_Detector::class )
     408                                );
     409                        case Sources::class:
     410                                return new Sources( $this->get( Settings_Repository::class ) );
     411                        case Sync_State::class:
     412                                return new Sync_State();
     413                        case Entry_Repository::class:
     414                                return new Entry_Repository();
     415                        case Passage_Repository::class:
     416                                return new Passage_Repository();
     417                        case Chunker::class:
     418                                return new Chunker();
     419                        case Markdown_Files::class:
     420                                return new Markdown_Files();
     421                        case Status_Report::class:
     422                                return new Status_Report( $this->get( Entry_Repository::class ), $this->get( Sync_State::class ), $this->get( Sources::class ), $this->get( Store_Check::class ) );
     423                        case Change_Listener::class:
     424                                return new Change_Listener( $this->get( Sync_Job::class ), $this->get( Sources::class ), $this->get( Markdown_Exporter::class ) );
     425                        case Kb_Permission::class:
     426                                return new Kb_Permission();
     427                        case Store_Check::class:
     428                                return new Store_Check();
     429                        case Entry_Presenter::class:
     430                                return new Entry_Presenter();
     431                        case Kb_Entry_Toggle::class:
     432                                return new Kb_Entry_Toggle( $this->get( Entry_Repository::class ), $this->get( Passage_Repository::class ), $this->get( Sync_Job::class ) );
     433                        case Kb_Controller::class:
     434                                return new Kb_Controller( $this->get( Kb_Permission::class ), $this->get( Status_Report::class ), $this->get( Sync_Job::class ), $this->get( Sources::class ), $this->get( Entry_Repository::class ), $this->get( Entry_Presenter::class ), $this->get( Kb_Entry_Toggle::class ), $this->get( Store_Check::class ) );
     435                        case Kb_Status_Controller::class:
     436                                return new Kb_Status_Controller( $this->get( Status_Report::class ), $this->get( Kb_Permission::class ) );
     437                        case Sync_Job::class:
     438                                return new Sync_Job(
     439                                        $this->get( Sources::class ),
     440                                        $this->get( Sync_State::class ),
     441                                        $this->get( Entry_Repository::class ),
     442                                        $this->get( Passage_Repository::class ),
     443                                        $this->get( Markdown_Exporter::class ),
     444                                        $this->get( Chunker::class ),
     445                                        $this->get( Embedding_Client::class ),
     446                                        $this->get( Job_Runner::class ),
     447                                        $this->get( Markdown_Files::class ),
     448                                        $this->get( Readiness_Checker::class )
     449                                );
     450                        case Server_Overrides::class:
     451                                return new Server_Overrides();
     452                        case Settings_Sanitizer::class:
     453                                return new Settings_Sanitizer();
     454                }
     455
     456                throw new \InvalidArgumentException( 'Unknown service: ' . $service_class ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Developer message, never output.
     457        }
     458
     459        /**
     460         * Verify against the settings snapshot already read by the calling REST route.
     461         *
     462         * @param string               $token    Visitor challenge token.
     463         * @param array<string, mixed> $settings Effective settings.
     464         */
     465        private function check_human( string $token, array $settings ): ?\WP_Error {
     466                $address = $this->get( Client_Address::class );
     467                $check   = new Human_Check(
     468                        new Recaptcha_V3( $settings ),
     469                        new Human_Pass( $address, (int) $settings['recaptcha_pass_ttl'] ),
     470                        new Nonce_Throttle( 'chathearth_rcv_' ),
     471                        $address
     472                );
     473                return $check->check( $token );
    146474        }
    147475}
  • chathearth/trunk/includes/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/languages/chathearth.pot

    r3663506 r3833468  
    1 #, fuzzy
     1# Copyright (C) 2026 PalWP
     2# This file is distributed under the GPL-2.0-or-later.
    23msgid ""
    34msgstr ""
    4 "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
    5 "Project-Id-Version: ChatHearth - AI Chatbot\n"
    6 "POT-Creation-Date: 2026-07-16 18:01+0300\n"
    7 "PO-Revision-Date: 2026-07-16 18:01+0300\n"
    8 "Last-Translator: \n"
    9 "Language-Team: \n"
     5"Project-Id-Version: ChatHearth - AI Chatbot 2.0.0\n"
     6"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/chathearth\n"
     7"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
     8"Language-Team: LANGUAGE <LL@li.org>\n"
    109"MIME-Version: 1.0\n"
    1110"Content-Type: text/plain; charset=UTF-8\n"
    1211"Content-Transfer-Encoding: 8bit\n"
    13 "X-Generator: Poedit 2.2\n"
    14 "X-Poedit-Basepath: ..\n"
    15 "X-Poedit-Flags-xgettext: --add-comments=translators:\n"
    16 "X-Poedit-WPHeader: chathearth.php\n"
    17 "X-Poedit-SourceCharset: UTF-8\n"
    18 "X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;esc_attr__;"
    19 "esc_attr_e;esc_attr_x:1,2c;esc_html__;esc_html_e;esc_html_x:1,2c;_n_noop:1,2;"
    20 "_nx_noop:3c,1,2;__ngettext_noop:1,2\n"
    21 "X-Poedit-SearchPath-0: .\n"
    22 "X-Poedit-SearchPathExcluded-0: *.js\n"
    23 
    24 #: includes/Admin/class-admin-notices.php:56
    25 msgid ""
    26 "ChatHearth - AI Chatbot needs WordPress AI support, the “AI Provider for "
    27 "OpenAI” plugin, and an OpenAI API key under Connectors."
    28 msgstr ""
    29 
    30 #: includes/Admin/class-admin-notices.php:59
     12"POT-Creation-Date: 2026-11-25T16:14:44+01:00\n"
     13"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
     14"X-Generator: WP-CLI 2.12.0\n"
     15"X-Domain: chathearth\n"
     16
     17#. Plugin Name of the plugin
     18#: chathearth.php
     19#: includes/Admin/class-privacy.php:88
     20#: includes/Admin/Settings/class-settings-page.php:101
     21#: includes/Admin/Settings/class-settings-page.php:102
     22msgid "ChatHearth - AI Chatbot"
     23msgstr ""
     24
     25#. Description of the plugin
     26#: chathearth.php
     27msgid "Site-wide AI chatbot for WordPress, powered by the AI Provider for OpenAI plugin."
     28msgstr ""
     29
     30#. Author of the plugin
     31#: chathearth.php
     32msgid "PalWP"
     33msgstr ""
     34
     35#. Author URI of the plugin
     36#: chathearth.php
     37msgid "https://palwp.com/"
     38msgstr ""
     39
     40#. translators: 1: software name (WordPress or PHP), 2: required version, 3: installed version.
     41#: chathearth.php:60
     42#, php-format
     43msgid "%1$s %2$s or newer (this site runs %3$s)"
     44msgstr ""
     45
     46#. translators: %s: the unmet requirements, for example "PHP 7.4 or newer (this site runs 7.3.33)".
     47#: chathearth.php:71
     48#, php-format
     49msgid "ChatHearth - AI Chatbot needs %s. The plugin stays inactive until the site is updated."
     50msgstr ""
     51
     52#: includes/Admin/class-admin-notices.php:76
     53msgid "Rate-limit counters cleared."
     54msgstr ""
     55
     56#: includes/Admin/class-admin-notices.php:91
     57msgid "The chat is switched back on."
     58msgstr ""
     59
     60#: includes/Admin/class-admin-notices.php:95
     61msgid "The chat is already on."
     62msgstr ""
     63
     64#: includes/Admin/class-admin-notices.php:99
     65msgid "This link has expired or was already used. Switch the chat on in the Protection settings."
     66msgstr ""
     67
     68#: includes/Admin/class-admin-notices.php:116
     69msgid "ChatHearth - AI Chatbot could not finish updating its settings. Your site keeps working with your current settings, and the update will be tried again automatically."
     70msgstr ""
     71
     72#: includes/Admin/class-admin-notices.php:136
     73msgid "ChatHearth - AI Chatbot needs WordPress AI support, which is turned off or unavailable on this site. The chat icon stays hidden until it is available."
     74msgstr ""
     75
     76#: includes/Admin/class-admin-notices.php:139
     77msgid "ChatHearth - AI Chatbot needs the “AI Provider for OpenAI” plugin to be installed and active. The chat icon stays hidden until it is."
     78msgstr ""
     79
     80#: includes/Admin/class-admin-notices.php:140
     81msgid "Open Plugins"
     82msgstr ""
     83
     84#: includes/Admin/class-admin-notices.php:143
     85msgid "ChatHearth - AI Chatbot cannot find the OpenAI connector. The chat icon stays hidden until it is available."
     86msgstr ""
     87
     88#: includes/Admin/class-admin-notices.php:144
     89#: includes/Admin/class-admin-notices.php:148
    3190msgid "Open Connectors settings"
    3291msgstr ""
    3392
    34 #: includes/Admin/class-admin-notices.php:82
    35 msgid ""
    36 "ChatHearth - AI Chatbot: global rate limits were hit repeatedly (possible multi-"
    37 "IP abuse)."
    38 msgstr ""
    39 
    40 #. translators: %d: number of hits
    41 #: includes/Admin/class-admin-notices.php:90
     93#: includes/Admin/class-admin-notices.php:147
     94msgid "ChatHearth - AI Chatbot needs an OpenAI API key under Connectors. The chat icon stays hidden until one is added."
     95msgstr ""
     96
     97#: includes/Admin/class-admin-notices.php:186
     98msgid "Site-wide rate limits were hit repeatedly (possible abuse)."
     99msgstr ""
     100
     101#. translators: %s: number of recorded rate-limit hits.
     102#: includes/Admin/class-admin-notices.php:188
    42103#, php-format
    43 msgid "Recorded hits in the window: %d."
    44 msgstr ""
    45 
    46 #: includes/Admin/class-admin-notices.php:97
    47 msgid "The chatbot was automatically disabled."
    48 msgstr ""
    49 
    50 #: includes/Admin/class-admin-notices.php:99
    51 msgid "Open Protection settings"
    52 msgstr ""
    53 
    54 #: includes/Admin/class-admin-notices.php:100
     104msgid "Recorded hit: %s."
     105msgid_plural "Recorded hits: %s."
     106msgstr[0] ""
     107msgstr[1] ""
     108
     109#: includes/Admin/class-admin-notices.php:190
     110msgid "The chat was switched off automatically."
     111msgstr ""
     112
     113#: includes/Admin/class-admin-notices.php:195
     114msgid "Switch chat back on"
     115msgstr ""
     116
     117#: includes/Admin/class-admin-notices.php:197
     118msgid "Review protection settings"
     119msgstr ""
     120
     121#: includes/Admin/class-admin-notices.php:198
     122#: assets/js/admin/toasts.js:33
    55123msgid "Dismiss"
    56124msgstr ""
    57125
    58 #: includes/Admin/class-admin-notices.php:109
     126#: includes/Admin/class-plugin-links.php:41
     127msgid "Settings"
     128msgstr ""
     129
     130#: includes/Admin/class-privacy.php:37
     131msgid "Always, when a visitor sends a message: the message and the recent conversation history of that chat are sent to OpenAI, through the AI provider set up in WordPress (Connectors), so a reply can be generated."
     132msgstr ""
     133
     134#: includes/Admin/class-privacy.php:38
     135msgid "Always, when a visitor sends a message: a short summary of this site’s public pages (and, with WooCommerce, the store and its product categories) and the public content of the page the visitor is on are sent to the AI provider together with the instructions, so the answer is about this site. Drafts, private and password-protected content are never sent, and the page is read as a guest sees it."
     136msgstr ""
     137
     138#: includes/Admin/class-privacy.php:39
     139msgid "Always: the conversation history of the chat is kept in the visitor’s browser (local storage) and removed after 24 hours without a new message, or sooner when the visitor clears the chat. The plugin does not store chat transcripts in the WordPress database."
     140msgstr ""
     141
     142#: includes/Admin/class-privacy.php:40
     143msgid "Always: the visitor’s IP address is used for a short time for rate limits, for blocking the addresses you list and for abuse protection. IPv6 visitors are counted per network block. Visitors behind a proxy share a limit until trusted proxies are set up. The counters are short-lived and are not a chat log."
     144msgstr ""
     145
     146#: includes/Admin/class-privacy.php:41
     147msgid "When you list blocked addresses: the addresses and ranges you enter are stored in the plugin’s settings and compared with each visitor’s address. Visitors’ addresses are not stored."
     148msgstr ""
     149
     150#: includes/Admin/class-privacy.php:42
     151msgid "When “Separate limits for logged-in users” is on: the visitor’s WordPress user account is used to count their messages, so the limits follow the person and not their network."
     152msgstr ""
     153
     154#: includes/Admin/class-privacy.php:43
     155msgid "When the bot trap is on: an invisible form field is added to the chat. Only automated programs fill it in, and the result is used to refuse their requests. Visitors never see it."
     156msgstr ""
     157
     158#: includes/Admin/class-privacy.php:44
     159msgid "When content moderation uses OpenAI: the new message and up to two earlier visitor messages of the same chat (never the assistant’s replies) are also sent to OpenAI’s moderation service before a reply is generated, so harmful or disallowed content can be blocked. Only texts not checked in the last 24 hours are sent. The result is remembered for 24 hours as a salted hash, never as text."
     160msgstr ""
     161
     162#: includes/Admin/class-privacy.php:45
     163msgid "When both Google reCAPTCHA v3 keys are set: Google is contacted only after the visitor presses Continue. Google processes a score-based check and related technical data such as the IP address, under Google’s privacy policy. The HTTP-only chathearth_human cookie lasts at most 60 minutes and is used only to skip repeated checks."
     164msgstr ""
     165
     166#: includes/Admin/class-privacy.php:46
     167msgid "When the Knowledge Base is on and OpenAI is connected: the public content selected in the Knowledge Base settings is sent to the OpenAI embeddings service when it is indexed and when it changes, and each visitor question is sent to the OpenAI embeddings service to find matching passages. ChatHearth does not store the question for this. The index holds only this public site content and its numeric representations (embeddings), stored in the WordPress database of this site, with no visitor or account data, so there is nothing in it to export or erase for a person. Markdown copies of the selected content can be kept in the uploads folder of this site."
     168msgstr ""
     169
     170#: includes/Admin/class-privacy.php:47
     171msgid "Always: ChatHearth does not track visitors. It sets no tracking cookies and sends no analytics."
     172msgstr ""
     173
     174#: includes/Admin/class-privacy.php:48
     175msgid "Always: ChatHearth does not store the AI provider key. That credential is managed by WordPress Connectors or the server environment."
     176msgstr ""
     177
     178#: includes/Admin/class-privacy.php:49
     179msgid "Always: the summary of this site’s public pages that goes with a message is kept on this site for up to 12 hours, so the next messages do not rebuild it."
     180msgstr ""
     181
     182#: includes/Admin/class-privacy.php:50
     183msgid "Always: the rate-limit counters of a visitor’s network or account are kept only for the length of the limit window and are not a chat log."
     184msgstr ""
     185
     186#: includes/Admin/class-privacy.php:51
     187msgid "When the Knowledge Base is on: the index stays in the WordPress database of this site until you delete an item, turn the Knowledge Base off or delete the plugin, and the markdown copies in the uploads folder are removed when you turn the setting off or delete the plugin."
     188msgstr ""
     189
     190#: includes/Admin/class-privacy.php:52
     191msgid "When site-wide rate limits are hit repeatedly: the plugin keeps an abuse alert in this site’s options, with the number of hits and whether the chat was switched off, and shows it to administrators until you dismiss it. It holds no visitor data."
     192msgstr ""
     193
     194#: includes/Admin/class-privacy.php:53
     195msgid "When WP_DEBUG_LOG is already on in your site’s configuration: the plugin writes short failure codes to the PHP error log, and never message text, addresses or keys."
     196msgstr ""
     197
     198#: includes/Admin/class-privacy.php:54
     199msgid "Always: the plugin sets no tracking or analytics cookie, sends no analytics or telemetry request and keeps no visitor identifier beyond the stores described here."
     200msgstr ""
     201
     202#: includes/Admin/class-privacy.php:65
     203msgid "When WooCommerce is active and the assistant shows product cards: the Add to cart button of a product card in the chat uses the WooCommerce cart on this site. Payment still happens at the store checkout."
     204msgstr ""
     205
     206#: includes/Admin/class-privacy.php:66
     207msgid "The facts of the products named in a message or found in the knowledge base (name, price, stock, categories, attributes and short description) are sent to the AI provider with the question."
     208msgstr ""
     209
     210#: includes/Admin/class-privacy.php:82
     211msgid "ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this site. Depending on how the chatbot is set up, the following may apply:"
     212msgstr ""
     213
     214#: includes/Admin/class-privacy.php:86
     215msgid "Site owners should read the privacy policy of their AI provider (and of Google, if reCAPTCHA is used) and make sure this section matches how the chatbot is set up on their site."
     216msgstr ""
     217
     218#: includes/Admin/class-reenable-action.php:54
     219#: includes/Admin/Settings/class-abuse-alert-actions.php:78
     220#: includes/Admin/Settings/class-rate-limit-reset-action.php:48
    59221msgid "Sorry, you are not allowed to do that."
    60222msgstr ""
    61223
    62 #: includes/Admin/class-privacy.php:37
    63 msgid ""
    64 "ChatHearth - AI Chatbot lets visitors send messages to an AI assistant on this "
    65 "site. When someone uses the chatbot, the following may apply:"
    66 msgstr ""
    67 
    68 #: includes/Admin/class-privacy.php:43
    69 msgid ""
    70 "Message text and recent conversation history from the chat session are sent "
    71 "to a third-party AI provider (OpenAI in the current version) through "
    72 "WordPress Connectors / the site’s configured AI provider, so a reply can be "
    73 "generated."
    74 msgstr ""
    75 
    76 #: includes/Admin/class-privacy.php:47
    77 msgid ""
    78 "Conversation history for the widget is stored in the visitor’s browser "
    79 "(local storage). The plugin does not store chat transcripts in the WordPress "
    80 "database in the current version."
    81 msgstr ""
    82 
    83 #: includes/Admin/class-privacy.php:51
    84 msgid ""
    85 "The visitor’s IP address may be used temporarily for rate limiting and abuse "
    86 "protection. Related counters are short-lived and are not kept as a chat log."
    87 msgstr ""
    88 
    89 #: includes/Admin/class-privacy.php:55
    90 msgid ""
    91 "If Google reCAPTCHA is enabled in the chatbot settings, Google may process a "
    92 "CAPTCHA challenge (and related technical data such as IP address) according "
    93 "to Google’s privacy policy."
    94 msgstr ""
    95 
    96 #: includes/Admin/class-privacy.php:59
    97 msgid ""
    98 "This plugin does not store the AI provider API key; that credential is "
    99 "managed through WordPress Connectors or the server environment."
    100 msgstr ""
    101 
    102 #: includes/Admin/class-privacy.php:65
    103 msgid ""
    104 "Site owners should review the privacy policy of their chosen AI provider "
    105 "(and Google, if reCAPTCHA is used) and ensure this section matches how the "
    106 "chatbot is configured on their site."
    107 msgstr ""
    108 
    109 #. Plugin Name of the plugin/theme
    110 #: includes/Admin/class-privacy.php:70
    111 #: includes/Admin/class-settings-page.php:68
    112 #: includes/Admin/class-settings-page.php:69
    113 msgid "ChatHearth - AI Chatbot"
    114 msgstr ""
    115 
    116 #: includes/Admin/class-settings-page.php:127
     224#: includes/Admin/Settings/class-field-choices.php:35
     225msgid "Icon only"
     226msgstr ""
     227
     228#: includes/Admin/Settings/class-field-choices.php:36
     229msgid "Icon and text"
     230msgstr ""
     231
     232#: includes/Admin/Settings/class-field-choices.php:40
     233msgid "Circle"
     234msgstr ""
     235
     236#: includes/Admin/Settings/class-field-choices.php:41
     237msgid "Square"
     238msgstr ""
     239
     240#: includes/Admin/Settings/class-field-choices.php:45
     241msgid "Bottom left"
     242msgstr ""
     243
     244#: includes/Admin/Settings/class-field-choices.php:46
     245msgid "Bottom center"
     246msgstr ""
     247
     248#: includes/Admin/Settings/class-field-choices.php:47
     249msgid "Bottom right"
     250msgstr ""
     251
     252#: includes/Admin/Settings/class-field-choices.php:51
     253msgid "Small"
     254msgstr ""
     255
     256#: includes/Admin/Settings/class-field-choices.php:52
     257msgid "Medium"
     258msgstr ""
     259
     260#: includes/Admin/Settings/class-field-choices.php:53
     261msgid "Large"
     262msgstr ""
     263
     264#: includes/Admin/Settings/class-field-choices.php:57
     265msgid "3 seconds: shortest delay"
     266msgstr ""
     267
     268#: includes/Admin/Settings/class-field-choices.php:58
     269msgid "5 seconds: balanced"
     270msgstr ""
     271
     272#: includes/Admin/Settings/class-field-choices.php:59
     273msgid "10 seconds: almost always gets an answer"
     274msgstr ""
     275
     276#: includes/Admin/Settings/class-field-choices.php:60
     277msgid "15 seconds: longest delay"
     278msgstr ""
     279
     280#: includes/Admin/Settings/class-field-choices.php:63
     281msgid "OpenAI"
     282msgstr ""
     283
     284#: includes/Admin/Settings/class-field-renderer.php:297
     285msgid "On"
     286msgstr ""
     287
     288#: includes/Admin/Settings/class-field-renderer.php:297
     289msgid "Off"
     290msgstr ""
     291
     292#. translators: %s: setting name.
     293#: includes/Admin/Settings/class-field-renderer.php:324
     294#, php-format
     295msgid "%s (slider)"
     296msgstr ""
     297
     298#. translators: %s: setting name.
     299#: includes/Admin/Settings/class-field-renderer.php:387
     300#, php-format
     301msgid "%s (colour picker)"
     302msgstr ""
     303
     304#: includes/Admin/Settings/class-field-renderer.php:423
     305msgid "Set by server environment"
     306msgstr ""
     307
     308#: includes/Admin/Settings/class-field-renderer.php:492
     309msgid "(not available)"
     310msgstr ""
     311
     312#: includes/Admin/Settings/class-field-renderer.php:535
     313msgid "A secret key is saved."
     314msgstr ""
     315
     316#: includes/Admin/Settings/class-field-renderer.php:536
     317msgid "Replace"
     318msgstr ""
     319
     320#: includes/Admin/Settings/class-field-renderer.php:543
     321msgid "Remove the saved secret key"
     322msgstr ""
     323
     324#: includes/Admin/Settings/class-settings-page.php:307
     325msgid "Sorry, you are not allowed to access this page."
     326msgstr ""
     327
     328#: includes/Admin/Settings/class-settings-page.php:355
     329msgid "Not ready"
     330msgstr ""
     331
     332#: includes/Admin/Settings/class-settings-page.php:360
     333msgid "Chat is off – switched off automatically"
     334msgstr ""
     335
     336#: includes/Admin/Settings/class-settings-page.php:363
     337msgid "Chat is off"
     338msgstr ""
     339
     340#: includes/Admin/Settings/class-settings-page.php:366
     341msgid "Chat is live"
     342msgstr ""
     343
     344#: includes/Admin/Settings/class-settings-page.php:379
     345msgid "AI Chatbot"
     346msgstr ""
     347
     348#: includes/Admin/Settings/class-settings-page.php:380
     349msgid "Make every conversation feel at home."
     350msgstr ""
     351
     352#: includes/Admin/Settings/class-settings-page.php:381
     353msgid "Plugin version"
     354msgstr ""
     355
     356#: includes/Admin/Settings/class-settings-page.php:383
     357msgid "Help and documentation"
     358msgstr ""
     359
     360#: includes/Admin/Settings/class-settings-page.php:384
     361msgid "(opens in a new tab)"
     362msgstr ""
     363
     364#: includes/Admin/Settings/class-settings-page.php:396
     365msgid "ChatHearth settings"
     366msgstr ""
     367
     368#: includes/Admin/Settings/class-settings-page.php:396
     369msgid "Settings sections"
     370msgstr ""
     371
     372#: includes/Admin/Settings/class-settings-page.php:409
     373#: includes/Admin/Settings/class-settings-page.php:458
     374#: includes/Admin/Settings/class-settings-page.php:532
     375msgid "Unsaved changes"
     376msgstr ""
     377
     378#: includes/Admin/Settings/class-settings-page.php:453
     379msgid "Protection sections"
     380msgstr ""
     381
     382#: includes/Admin/Settings/class-settings-page.php:521
     383msgid "Clear all rate-limit counters now? Visitors and users get their full allowance again."
     384msgstr ""
     385
     386#: includes/Admin/Settings/class-settings-page.php:533
     387msgid "Your settings are up to date."
     388msgstr ""
     389
     390#: includes/Admin/Settings/class-settings-page.php:534
     391msgid "Discard changes"
     392msgstr ""
     393
     394#: includes/Admin/Settings/class-settings-page.php:535
     395msgid "Save settings"
     396msgstr ""
     397
     398#: includes/Admin/Settings/class-site-status.php:119
     399msgid "Could not be checked"
     400msgstr ""
     401
     402#: includes/Admin/Settings/class-site-status.php:133
     403msgid "WordPress version"
     404msgstr ""
     405
     406#: includes/Admin/Settings/class-site-status.php:134
     407msgid "PHP version"
     408msgstr ""
     409
     410#: includes/Admin/Settings/class-site-status.php:135
     411msgid "WordPress AI support"
     412msgstr ""
     413
     414#: includes/Admin/Settings/class-site-status.php:136
     415msgid "AI Provider for OpenAI plugin"
     416msgstr ""
     417
     418#: includes/Admin/Settings/class-site-status.php:137
     419msgid "OpenAI key in Connectors"
     420msgstr ""
     421
     422#: includes/Admin/Settings/class-site-status.php:138
     423msgid "Persistent object cache"
     424msgstr ""
     425
     426#: includes/Admin/Settings/class-site-status.php:139
     427msgid "WooCommerce"
     428msgstr ""
     429
     430#: includes/Admin/Settings/class-site-status.php:140
     431msgid "Background tasks (WP-Cron)"
     432msgstr ""
     433
     434#: includes/Admin/Settings/class-site-status.php:173
     435msgid "Available"
     436msgstr ""
     437
     438#: includes/Admin/Settings/class-site-status.php:173
     439msgid "Not available"
     440msgstr ""
     441
     442#: includes/Admin/Settings/class-site-status.php:182
     443#: includes/Admin/Settings/class-tab-protection.php:285
     444msgid "Active"
     445msgstr ""
     446
     447#: includes/Admin/Settings/class-site-status.php:182
     448#: includes/Admin/Settings/class-site-status.php:216
     449msgid "Not active"
     450msgstr ""
     451
     452#: includes/Admin/Settings/class-site-status.php:192
     453msgid "Configured"
     454msgstr ""
     455
     456#: includes/Admin/Settings/class-site-status.php:192
     457#: includes/Admin/Settings/class-tab-ai-settings.php:98
     458msgid "Not configured"
     459msgstr ""
     460
     461#: includes/Admin/Settings/class-site-status.php:204
     462msgid "Detected"
     463msgstr ""
     464
     465#: includes/Admin/Settings/class-site-status.php:204
     466msgid "Not detected. Rate limits still work. An object cache makes them faster."
     467msgstr ""
     468
     469#. translators: %s: WooCommerce version.
     470#: includes/Admin/Settings/class-site-status.php:218
     471#, php-format
     472msgid "Active %s"
     473msgstr ""
     474
     475#: includes/Admin/Settings/class-site-status.php:229
     476msgid "Disabled (server task)"
     477msgstr ""
     478
     479#: includes/Admin/Settings/class-site-status.php:234
     480msgid "Not scheduled"
     481msgstr ""
     482
     483#: includes/Admin/Settings/class-site-status.php:237
     484msgid "Late"
     485msgstr ""
     486
     487#: includes/Admin/Settings/class-site-status.php:240
     488msgid "Running"
     489msgstr ""
     490
     491#: includes/Admin/Settings/class-site-status.php:250
     492msgid "OK"
     493msgstr ""
     494
     495#: includes/Admin/Settings/class-site-status.php:251
     496msgid "Warning"
     497msgstr ""
     498
     499#: includes/Admin/Settings/class-site-status.php:252
     500msgid "Error"
     501msgstr ""
     502
     503#: includes/Admin/Settings/class-site-status.php:253
     504msgid "Info"
     505msgstr ""
     506
     507#: includes/Admin/Settings/class-site-status.php:265
     508msgid "ChatHearth status report"
     509msgstr ""
     510
     511#. translators: %s: date and time.
     512#: includes/Admin/Settings/class-site-status.php:267
     513#, php-format
     514msgid "Generated: %s"
     515msgstr ""
     516
     517#. translators: %s: site address.
     518#: includes/Admin/Settings/class-site-status.php:269
     519#, php-format
     520msgid "Site: %s"
     521msgstr ""
     522
     523#. translators: %s: plugin version.
     524#: includes/Admin/Settings/class-site-status.php:271
     525#, php-format
     526msgid "ChatHearth: %s"
     527msgstr ""
     528
     529#. translators: 1: theme name, 2: theme version.
     530#: includes/Admin/Settings/class-site-status.php:273
     531#, php-format
     532msgid "Theme: %1$s %2$s"
     533msgstr ""
     534
     535#: includes/Admin/Settings/class-tab-advanced.php:44
     536msgid "Advanced"
     537msgstr ""
     538
     539#: includes/Admin/Settings/class-tab-advanced.php:58
     540msgid "Copy status report"
     541msgstr ""
     542
     543#: includes/Admin/Settings/class-tab-advanced.php:78
     544msgid "How to fix"
     545msgstr ""
     546
     547#: includes/Admin/Settings/class-tab-advanced.php:88
     548msgid "Status report"
     549msgstr ""
     550
     551#: includes/Admin/Settings/class-tab-advanced.php:101
     552msgid "System status"
     553msgstr ""
     554
     555#: includes/Admin/Settings/class-tab-advanced.php:102
     556msgid "A quick check of your site's readiness."
     557msgstr ""
     558
     559#: includes/Admin/Settings/class-tab-advanced.php:111
     560msgid "Data"
     561msgstr ""
     562
     563#: includes/Admin/Settings/class-tab-advanced.php:112
     564msgid "Choose what happens when the plugin is deleted."
     565msgstr ""
     566
     567#: includes/Admin/Settings/class-tab-advanced.php:114
     568msgid "Keep data when the plugin is deleted"
     569msgstr ""
     570
     571#: includes/Admin/Settings/class-tab-advanced.php:114
     572msgid "When off, deleting ChatHearth removes all its settings, knowledge base and files."
     573msgstr ""
     574
     575#: includes/Admin/Settings/class-tab-ai-settings.php:44
     576msgid "AI Settings"
     577msgstr ""
     578
     579#: includes/Admin/Settings/class-tab-ai-settings.php:63
     580msgid "Connection"
     581msgstr ""
     582
     583#: includes/Admin/Settings/class-tab-ai-settings.php:64
     584msgid "Your API key is stored by WordPress, not by ChatHearth."
     585msgstr ""
     586
     587#: includes/Admin/Settings/class-tab-ai-settings.php:70
     588#: includes/Admin/Settings/class-tab-ai-settings.php:74
     589msgid "Model"
     590msgstr ""
     591
     592#: includes/Admin/Settings/class-tab-ai-settings.php:71
     593msgid "Choose the AI that generates replies."
     594msgstr ""
     595
     596#: includes/Admin/Settings/class-tab-ai-settings.php:73
     597msgid "Provider"
     598msgstr ""
     599
     600#: includes/Admin/Settings/class-tab-ai-settings.php:73
     601msgid "More providers will be added in future versions."
     602msgstr ""
     603
     604#: includes/Admin/Settings/class-tab-ai-settings.php:74
     605msgid "Smaller models are faster and cheaper."
     606msgstr ""
     607
     608#: includes/Admin/Settings/class-tab-ai-settings.php:79
     609msgid "Instructions"
     610msgstr ""
     611
     612#: includes/Admin/Settings/class-tab-ai-settings.php:80
     613msgid "Guide how the assistant behaves and speaks."
     614msgstr ""
     615
     616#: includes/Admin/Settings/class-tab-ai-settings.php:82
     617msgid "Additional instructions"
     618msgstr ""
     619
     620#: includes/Admin/Settings/class-tab-ai-settings.php:82
     621msgid "Tone, focus and anything the assistant should know. ChatHearth always keeps the assistant limited to your website."
     622msgstr ""
     623
     624#: includes/Admin/Settings/class-tab-ai-settings.php:95
     625msgid "OpenAI via WordPress Connectors"
     626msgstr ""
     627
     628#: includes/Admin/Settings/class-tab-ai-settings.php:96
     629msgid "Your OpenAI API key is stored securely in WordPress core. ChatHearth never sees or stores it."
     630msgstr ""
     631
     632#: includes/Admin/Settings/class-tab-ai-settings.php:98
     633msgid "Ready"
     634msgstr ""
     635
     636#: includes/Admin/Settings/class-tab-ai-settings.php:99
     637#: includes/Admin/Settings/class-tab-protection.php:314
     638msgid "Open Connectors"
     639msgstr ""
     640
     641#: includes/Admin/Settings/class-tab-ai-settings.php:107
     642msgid "Answer only questions about this website: its pages, posts, products, categories, policies, store, shipping and related services."
     643msgstr ""
     644
     645#: includes/Admin/Settings/class-tab-ai-settings.php:108
     646msgid "When the visitor asks about \"this page\", \"this product\" or \"here\", use the page they are viewing."
     647msgstr ""
     648
     649#: includes/Admin/Settings/class-tab-ai-settings.php:109
     650msgid "Politely refuse unrelated topics (news, homework, other companies, general trivia) and offer help with this website instead."
     651msgstr ""
     652
     653#: includes/Admin/Settings/class-tab-ai-settings.php:110
     654msgid "Never invent pages, URLs, prices, stock or products. If the information is not available, say so."
     655msgstr ""
     656
     657#: includes/Admin/Settings/class-tab-ai-settings.php:111
     658msgid "Link to every page, post, product or category you mention."
     659msgstr ""
     660
     661#: includes/Admin/Settings/class-tab-ai-settings.php:112
     662msgid "Compare products in a table or side-by-side list, using only known facts."
     663msgstr ""
     664
     665#: includes/Admin/Settings/class-tab-ai-settings.php:113
     666msgid "Point buyers to Add to cart, the cart or checkout. Never claim an order was placed."
     667msgstr ""
     668
     669#: includes/Admin/Settings/class-tab-ai-settings.php:116
     670msgid "Show the built-in website rules"
     671msgstr ""
     672
     673#: includes/Admin/Settings/class-tab-appearance.php:46
     674msgid "Appearance"
     675msgstr ""
     676
     677#: includes/Admin/Settings/class-tab-appearance.php:67
     678msgid "Reset appearance to defaults"
     679msgstr ""
     680
     681#: includes/Admin/Settings/class-tab-appearance.php:104
     682#: includes/Admin/Settings/class-tab-appearance.php:106
     683msgid "Live preview"
     684msgstr ""
     685
     686#: includes/Admin/Settings/class-tab-appearance.php:106
     687msgid "Example conversation"
     688msgstr ""
     689
     690#: includes/Admin/Settings/class-tab-appearance.php:114
     691msgid "What do you offer?"
     692msgstr ""
     693
     694#: includes/Admin/Settings/class-tab-appearance.php:115
     695msgid "Here are a few products you might like."
     696msgstr ""
     697
     698#: includes/Admin/Settings/class-tab-appearance.php:119
     699msgid "Type a message…"
     700msgstr ""
     701
     702#: includes/Admin/Settings/class-tab-appearance.php:122
     703msgid "Launcher preview"
     704msgstr ""
     705
     706#: includes/Admin/Settings/class-tab-appearance.php:134
     707msgid "Shirt"
     708msgstr ""
     709
     710#: includes/Admin/Settings/class-tab-appearance.php:135
     711msgid "Shoes"
     712msgstr ""
     713
     714#: includes/Admin/Settings/class-tab-appearance.php:138
     715msgid "Sample products. Scroll sideways to see more."
     716msgstr ""
     717
     718#: includes/Admin/Settings/class-tab-appearance.php:142
     719#: includes/Frontend/class-widget-config.php:270
     720msgid "Add to cart"
     721msgstr ""
     722
     723#: includes/Admin/Settings/class-tab-appearance.php:155
     724msgid "Choose a colour or enter a hex value."
     725msgstr ""
     726
     727#: includes/Admin/Settings/class-tab-appearance.php:156
     728msgid "px"
     729msgstr ""
     730
     731#: includes/Admin/Settings/class-tab-appearance.php:161
     732msgid "Launcher button"
     733msgstr ""
     734
     735#: includes/Admin/Settings/class-tab-appearance.php:162
     736msgid "How visitors open the chat on your site."
     737msgstr ""
     738
     739#: includes/Admin/Settings/class-tab-appearance.php:164
     740msgid "Launcher style"
     741msgstr ""
     742
     743#: includes/Admin/Settings/class-tab-appearance.php:164
     744msgid "Choose a compact icon button or an animated pill with text."
     745msgstr ""
     746
     747#: includes/Admin/Settings/class-tab-appearance.php:165
     748msgid "Button label"
     749msgstr ""
     750
     751#: includes/Admin/Settings/class-tab-appearance.php:165
     752msgid "Text shown next to the sparkle icon on wide screens (up to 50 characters)."
     753msgstr ""
     754
     755#: includes/Admin/Settings/class-tab-appearance.php:166
     756msgid "Shape"
     757msgstr ""
     758
     759#: includes/Admin/Settings/class-tab-appearance.php:166
     760msgid "Shape of the icon-only launcher."
     761msgstr ""
     762
     763#: includes/Admin/Settings/class-tab-appearance.php:167
     764msgid "Size"
     765msgstr ""
     766
     767#: includes/Admin/Settings/class-tab-appearance.php:167
     768msgid "Size of the launcher icon."
     769msgstr ""
     770
     771#: includes/Admin/Settings/class-tab-appearance.php:168
     772msgid "Position"
     773msgstr ""
     774
     775#: includes/Admin/Settings/class-tab-appearance.php:168
     776msgid "Where the launcher sits on your pages."
     777msgstr ""
     778
     779#: includes/Admin/Settings/class-tab-appearance.php:169
     780msgid "Background"
     781msgstr ""
     782
     783#: includes/Admin/Settings/class-tab-appearance.php:170
     784msgid "Border"
     785msgstr ""
     786
     787#: includes/Admin/Settings/class-tab-appearance.php:171
     788msgid "Icon"
     789msgstr ""
     790
     791#: includes/Admin/Settings/class-tab-appearance.php:176
     792msgid "Chat window"
     793msgstr ""
     794
     795#: includes/Admin/Settings/class-tab-appearance.php:177
     796msgid "Make the conversation feel at home on your site."
     797msgstr ""
     798
     799#: includes/Admin/Settings/class-tab-appearance.php:179
     800msgid "Window size"
     801msgstr ""
     802
     803#: includes/Admin/Settings/class-tab-appearance.php:179
     804msgid "How large the chat window opens."
     805msgstr ""
     806
     807#: includes/Admin/Settings/class-tab-appearance.php:180
     808msgid "Window title"
     809msgstr ""
     810
     811#: includes/Admin/Settings/class-tab-appearance.php:180
     812msgid "Shown at the top of the chat window."
     813msgstr ""
     814
     815#: includes/Admin/Settings/class-tab-appearance.php:181
     816msgid "Visitor messages"
     817msgstr ""
     818
     819#: includes/Admin/Settings/class-tab-appearance.php:181
     820msgid "Background colour of the visitor's messages."
     821msgstr ""
     822
     823#: includes/Admin/Settings/class-tab-appearance.php:182
     824msgid "Assistant messages"
     825msgstr ""
     826
     827#: includes/Admin/Settings/class-tab-appearance.php:182
     828msgid "Background colour of the assistant's replies."
     829msgstr ""
     830
     831#: includes/Admin/Settings/class-tab-appearance.php:187
     832msgid "Product cards"
     833msgstr ""
     834
     835#: includes/Admin/Settings/class-tab-appearance.php:188
     836msgid "Style how products appear when the assistant suggests them from your store."
     837msgstr ""
     838
     839#: includes/Admin/Settings/class-tab-appearance.php:190
     840msgid "Card background"
     841msgstr ""
     842
     843#: includes/Admin/Settings/class-tab-appearance.php:190
     844msgid "Background of each product card."
     845msgstr ""
     846
     847#: includes/Admin/Settings/class-tab-appearance.php:191
     848msgid "Card border"
     849msgstr ""
     850
     851#: includes/Admin/Settings/class-tab-appearance.php:191
     852msgid "Outline around each product card."
     853msgstr ""
     854
     855#: includes/Admin/Settings/class-tab-appearance.php:192
     856msgid "Card text"
     857msgstr ""
     858
     859#: includes/Admin/Settings/class-tab-appearance.php:192
     860msgid "Colour of product names and prices."
     861msgstr ""
     862
     863#: includes/Admin/Settings/class-tab-appearance.php:193
     864msgid "Add to cart button"
     865msgstr ""
     866
     867#: includes/Admin/Settings/class-tab-appearance.php:193
     868msgid "Background of the Add to cart button."
     869msgstr ""
     870
     871#: includes/Admin/Settings/class-tab-appearance.php:194
     872msgid "Add to cart button text"
     873msgstr ""
     874
     875#: includes/Admin/Settings/class-tab-appearance.php:194
     876msgid "Text colour of the Add to cart button."
     877msgstr ""
     878
     879#: includes/Admin/Settings/class-tab-appearance.php:195
     880msgid "Add to cart button corners"
     881msgstr ""
     882
     883#: includes/Admin/Settings/class-tab-appearance.php:195
     884msgid "Round the corners of the Add to cart button."
     885msgstr ""
     886
     887#: includes/Admin/Settings/class-tab-appearance.php:196
     888msgid "Card corners"
     889msgstr ""
     890
     891#: includes/Admin/Settings/class-tab-appearance.php:196
     892msgid "Round the corners of each product card."
     893msgstr ""
     894
     895#: includes/Admin/Settings/class-tab-appearance.php:197
     896msgid "Card width"
     897msgstr ""
     898
     899#: includes/Admin/Settings/class-tab-appearance.php:197
     900msgid "Width of each card in the horizontal product list."
     901msgstr ""
     902
     903#: includes/Admin/Settings/class-tab-knowledge-base.php:55
     904#: includes/Admin/Settings/class-tab-knowledge-base.php:74
     905msgid "Knowledge Base"
     906msgstr ""
     907
     908#: includes/Admin/Settings/class-tab-knowledge-base.php:75
     909msgid "Give the assistant accurate facts from your own content."
     910msgstr ""
     911
     912#: includes/Admin/Settings/class-tab-knowledge-base.php:77
     913msgid "Use the Knowledge Base"
     914msgstr ""
     915
     916#: includes/Admin/Settings/class-tab-knowledge-base.php:77
     917msgid "Answers use matching content from your site. The assistant stays limited to your website even when this is off."
     918msgstr ""
     919
     920#: includes/Admin/Settings/class-tab-knowledge-base.php:83
     921#: includes/Frontend/class-widget-config.php:249
     922msgid "Sources"
     923msgstr ""
     924
     925#: includes/Admin/Settings/class-tab-knowledge-base.php:84
     926msgid "Choose what the assistant can read."
     927msgstr ""
     928
     929#: includes/Admin/Settings/class-tab-knowledge-base.php:86
     930msgid "Content types"
     931msgstr ""
     932
     933#: includes/Admin/Settings/class-tab-knowledge-base.php:86
     934msgid "Posts and pages included in searches."
     935msgstr ""
     936
     937#: includes/Admin/Settings/class-tab-knowledge-base.php:87
     938msgid "Categories and tags"
     939msgstr ""
     940
     941#: includes/Admin/Settings/class-tab-knowledge-base.php:87
     942msgid "Term names and descriptions."
     943msgstr ""
     944
     945#: includes/Admin/Settings/class-tab-knowledge-base.php:88
     946#: includes/Kb/class-entry-presenter.php:113
     947msgid "Site summary"
     948msgstr ""
     949
     950#: includes/Admin/Settings/class-tab-knowledge-base.php:88
     951msgid "Site name, tagline, address and list of pages."
     952msgstr ""
     953
     954#: includes/Admin/Settings/class-tab-knowledge-base.php:89
     955msgid "Store summary"
     956msgstr ""
     957
     958#: includes/Admin/Settings/class-tab-knowledge-base.php:89
     959msgid "Shop links, currency and product categories."
     960msgstr ""
     961
     962#: includes/Admin/Settings/class-tab-knowledge-base.php:94
     963msgid "Search tuning"
     964msgstr ""
     965
     966#: includes/Admin/Settings/class-tab-knowledge-base.php:95
     967msgid "Fine-tune how content is matched and broken up."
     968msgstr ""
     969
     970#: includes/Admin/Settings/class-tab-knowledge-base.php:97
     971msgid "Passages per question"
     972msgstr ""
     973
     974#: includes/Admin/Settings/class-tab-knowledge-base.php:97
     975msgid "More passages give fuller answers but cost more."
     976msgstr ""
     977
     978#: includes/Admin/Settings/class-tab-knowledge-base.php:98
     979msgid "Passage size"
     980msgstr ""
     981
     982#: includes/Admin/Settings/class-tab-knowledge-base.php:98
     983msgid "Changing this re-indexes the whole knowledge base."
     984msgstr ""
     985
     986#: includes/Admin/Settings/class-tab-knowledge-base.php:98
     987#: includes/Admin/Settings/class-tab-protection.php:116
     988msgid "characters"
     989msgstr ""
     990
     991#: includes/Admin/Settings/class-tab-knowledge-base.php:99
     992msgid "Keep markdown copies"
     993msgstr ""
     994
     995#: includes/Admin/Settings/class-tab-knowledge-base.php:99
     996msgid "Saves a protected copy of each document in your uploads folder."
     997msgstr ""
     998
     999#: includes/Admin/Settings/class-tab-knowledge-base.php:104
     1000msgid "Index"
     1001msgstr ""
     1002
     1003#: includes/Admin/Settings/class-tab-knowledge-base.php:105
     1004msgid "The content the assistant can search."
     1005msgstr ""
     1006
     1007#: includes/Admin/Settings/class-tab-knowledge-base.php:122
     1008msgid "Stored in your WordPress database. No extra servers or accounts needed."
     1009msgstr ""
     1010
     1011#: includes/Admin/Settings/class-tab-knowledge-base.php:140
     1012#: includes/Admin/Settings/class-tab-knowledge-base.php:227
     1013msgid "Sync now"
     1014msgstr ""
     1015
     1016#: includes/Admin/Settings/class-tab-knowledge-base.php:141
     1017msgid "Test storage"
     1018msgstr ""
     1019
     1020#: includes/Admin/Settings/class-tab-knowledge-base.php:159
     1021#: includes/Admin/Settings/class-tab-knowledge-base.php:194
     1022#: assets/js/admin/kb-index.js:96
     1023msgid "Indexed"
     1024msgstr ""
     1025
     1026#: includes/Admin/Settings/class-tab-knowledge-base.php:160
     1027#: includes/Admin/Settings/class-tab-knowledge-base.php:195
     1028#: assets/js/admin/kb-index.js:97
     1029msgid "Pending"
     1030msgstr ""
     1031
     1032#: includes/Admin/Settings/class-tab-knowledge-base.php:161
     1033#: includes/Admin/Settings/class-tab-knowledge-base.php:196
     1034#: includes/Admin/Settings/class-tab-knowledge-base.php:202
     1035#: assets/js/admin/kb-index.js:98
     1036msgid "Excluded"
     1037msgstr ""
     1038
     1039#: includes/Admin/Settings/class-tab-knowledge-base.php:162
     1040#: includes/Admin/Settings/class-tab-knowledge-base.php:197
     1041#: assets/js/admin/kb-index.js:99
     1042msgid "Failed"
     1043msgstr ""
     1044
     1045#: includes/Admin/Settings/class-tab-knowledge-base.php:179
     1046msgid "Try again"
     1047msgstr ""
     1048
     1049#: includes/Admin/Settings/class-tab-knowledge-base.php:182
     1050msgid "Sync progress"
     1051msgstr ""
     1052
     1053#: includes/Admin/Settings/class-tab-knowledge-base.php:183
     1054msgid "You can leave this page. Syncing continues in the background."
     1055msgstr ""
     1056
     1057#: includes/Admin/Settings/class-tab-knowledge-base.php:186
     1058msgid "Show failed items"
     1059msgstr ""
     1060
     1061#: includes/Admin/Settings/class-tab-knowledge-base.php:189
     1062msgid "Search titles, URLs…"
     1063msgstr ""
     1064
     1065#: includes/Admin/Settings/class-tab-knowledge-base.php:189
     1066msgid "Search items in Knowledge Base"
     1067msgstr ""
     1068
     1069#: includes/Admin/Settings/class-tab-knowledge-base.php:191
     1070msgid "Filter by content type"
     1071msgstr ""
     1072
     1073#: includes/Admin/Settings/class-tab-knowledge-base.php:191
     1074#: assets/js/admin/kb-index.js:451
     1075msgid "All types"
     1076msgstr ""
     1077
     1078#: includes/Admin/Settings/class-tab-knowledge-base.php:192
     1079msgid "Filter by index status"
     1080msgstr ""
     1081
     1082#: includes/Admin/Settings/class-tab-knowledge-base.php:193
     1083msgid "All statuses"
     1084msgstr ""
     1085
     1086#: includes/Admin/Settings/class-tab-knowledge-base.php:199
     1087msgid "Filter by inclusion"
     1088msgstr ""
     1089
     1090#: includes/Admin/Settings/class-tab-knowledge-base.php:200
     1091msgid "All"
     1092msgstr ""
     1093
     1094#: includes/Admin/Settings/class-tab-knowledge-base.php:201
     1095#: includes/Admin/Settings/class-tab-knowledge-base.php:213
     1096msgid "Included"
     1097msgstr ""
     1098
     1099#: includes/Admin/Settings/class-tab-knowledge-base.php:207
     1100msgid "Knowledge Base items"
     1101msgstr ""
     1102
     1103#: includes/Admin/Settings/class-tab-knowledge-base.php:209
     1104msgid "Title"
     1105msgstr ""
     1106
     1107#: includes/Admin/Settings/class-tab-knowledge-base.php:210
     1108msgid "Type"
     1109msgstr ""
     1110
     1111#: includes/Admin/Settings/class-tab-knowledge-base.php:211
     1112msgid "Status"
     1113msgstr ""
     1114
     1115#: includes/Admin/Settings/class-tab-knowledge-base.php:212
     1116msgid "Updated"
     1117msgstr ""
     1118
     1119#: includes/Admin/Settings/class-tab-knowledge-base.php:216
     1120msgid "No items match your search."
     1121msgstr ""
     1122
     1123#: includes/Admin/Settings/class-tab-knowledge-base.php:217
     1124msgid "Clear search and filters"
     1125msgstr ""
     1126
     1127#: includes/Admin/Settings/class-tab-knowledge-base.php:218
     1128msgid "Knowledge Base pagination"
     1129msgstr ""
     1130
     1131#: includes/Admin/Settings/class-tab-knowledge-base.php:219
     1132msgid "‹ Previous"
     1133msgstr ""
     1134
     1135#: includes/Admin/Settings/class-tab-knowledge-base.php:221
     1136msgid "Next ›"
     1137msgstr ""
     1138
     1139#: includes/Admin/Settings/class-tab-knowledge-base.php:226
     1140msgid "No items yet."
     1141msgstr ""
     1142
     1143#: includes/Admin/Settings/class-tab-knowledge-base.php:226
     1144msgid "Choose your sources above, save settings, then click Sync now."
     1145msgstr ""
     1146
     1147#: includes/Admin/Settings/class-tab-knowledge-base.php:241
     1148#: assets/js/admin/kb-status.js:69
     1149msgid "Markdown copies could not be saved because your server asks for file system credentials. Indexing is not affected."
     1150msgstr ""
     1151
     1152#. translators: 1: date the last sync finished, 2: time it finished.
     1153#: includes/Admin/Settings/class-tab-knowledge-base.php:260
     1154#: assets/js/admin/kb-status.js:108
     1155#, php-format,js-format
     1156msgid "Last sync: %1$s, %2$s."
     1157msgstr ""
     1158
     1159#: includes/Admin/Settings/class-tab-protection.php:47
     1160msgid "Protection"
     1161msgstr ""
     1162
     1163#: includes/Admin/Settings/class-tab-protection.php:71
     1164#: includes/Admin/Settings/class-tab-protection.php:104
     1165msgid "Availability"
     1166msgstr ""
     1167
     1168#: includes/Admin/Settings/class-tab-protection.php:72
     1169#: includes/Admin/Settings/class-tab-protection.php:113
     1170msgid "Message limits"
     1171msgstr ""
     1172
     1173#: includes/Admin/Settings/class-tab-protection.php:73
     1174#: includes/Admin/Settings/class-tab-protection.php:122
     1175msgid "Rate limits"
     1176msgstr ""
     1177
     1178#: includes/Admin/Settings/class-tab-protection.php:74
     1179#: includes/Admin/Settings/class-tab-protection.php:154
     1180msgid "Escalation"
     1181msgstr ""
     1182
     1183#: includes/Admin/Settings/class-tab-protection.php:75
     1184#: includes/Admin/Settings/class-tab-protection.php:164
     1185msgid "Access rules"
     1186msgstr ""
     1187
     1188#: includes/Admin/Settings/class-tab-protection.php:76
     1189msgid "Human verification"
     1190msgstr ""
     1191
     1192#: includes/Admin/Settings/class-tab-protection.php:77
     1193#: includes/Admin/Settings/class-tab-protection.php:192
     1194msgid "Content moderation"
     1195msgstr ""
     1196
     1197#: includes/Admin/Settings/class-tab-protection.php:87
     1198msgid "messages"
     1199msgstr ""
     1200
     1201#: includes/Admin/Settings/class-tab-protection.php:93
     1202msgid "Per visitor"
     1203msgstr ""
     1204
     1205#: includes/Admin/Settings/class-tab-protection.php:97
     1206msgid "Whole site"
     1207msgstr ""
     1208
     1209#: includes/Admin/Settings/class-tab-protection.php:99
     1210msgid "Logged-in users"
     1211msgstr ""
     1212
     1213#: includes/Admin/Settings/class-tab-protection.php:105
     1214msgid "Choose when the chatbot accepts messages on your site."
     1215msgstr ""
     1216
     1217#: includes/Admin/Settings/class-tab-protection.php:107
     1218msgid "Enable chatbot"
     1219msgstr ""
     1220
     1221#: includes/Admin/Settings/class-tab-protection.php:107
     1222msgid "Shows the chat on your site and accepts messages. Turning it off hides the chat immediately."
     1223msgstr ""
     1224
     1225#: includes/Admin/Settings/class-tab-protection.php:114
     1226msgid "Cap the size and memory of each conversation."
     1227msgstr ""
     1228
     1229#: includes/Admin/Settings/class-tab-protection.php:116
     1230msgid "Maximum message length"
     1231msgstr ""
     1232
     1233#: includes/Admin/Settings/class-tab-protection.php:116
     1234msgid "Longer messages are shortened before they are sent to the AI."
     1235msgstr ""
     1236
     1237#: includes/Admin/Settings/class-tab-protection.php:117
     1238msgid "Conversation memory"
     1239msgstr ""
     1240
     1241#: includes/Admin/Settings/class-tab-protection.php:117
     1242msgid "How many earlier messages are sent with each question. Lower values reduce cost."
     1243msgstr ""
     1244
     1245#: includes/Admin/Settings/class-tab-protection.php:123
     1246msgid "Prevent misuse by limiting how fast questions can be sent."
     1247msgstr ""
     1248
     1249#: includes/Admin/Settings/class-tab-protection.php:128
     1250#: includes/Admin/Settings/class-tab-protection.php:134
     1251msgid "Per minute"
     1252msgstr ""
     1253
     1254#: includes/Admin/Settings/class-tab-protection.php:129
     1255msgid "Highest number of questions one visitor can send each minute."
     1256msgstr ""
     1257
     1258#: includes/Admin/Settings/class-tab-protection.php:130
     1259msgid "Behind a content delivery network or proxy, all visitors share one limit until trusted proxies are set up."
     1260msgstr ""
     1261
     1262#: includes/Admin/Settings/class-tab-protection.php:133
     1263#: includes/Admin/Settings/class-tab-protection.php:135
     1264msgid "Per hour"
     1265msgstr ""
     1266
     1267#: includes/Admin/Settings/class-tab-protection.php:133
     1268msgid "Highest number of questions one visitor can send each hour."
     1269msgstr ""
     1270
     1271#: includes/Admin/Settings/class-tab-protection.php:134
     1272msgid "Site-wide limit per minute. A shared ceiling across all visitors."
     1273msgstr ""
     1274
     1275#: includes/Admin/Settings/class-tab-protection.php:135
     1276msgid "Site-wide limit per hour. Protects against attacks from many addresses."
     1277msgstr ""
     1278
     1279#: includes/Admin/Settings/class-tab-protection.php:136
     1280msgid "Separate limits for logged-in users"
     1281msgstr ""
     1282
     1283#: includes/Admin/Settings/class-tab-protection.php:136
     1284msgid "Logged-in users get their own limits instead of sharing their network's."
     1285msgstr ""
     1286
     1287#: includes/Admin/Settings/class-tab-protection.php:137
     1288msgid "Extra allowance by role"
     1289msgstr ""
     1290
     1291#: includes/Admin/Settings/class-tab-protection.php:137
     1292msgid "×2 doubles the per-visitor limits for that role (1–10)."
     1293msgstr ""
     1294
     1295#: includes/Admin/Settings/class-tab-protection.php:141
     1296msgid "Message when a limit is reached"
     1297msgstr ""
     1298
     1299#: includes/Admin/Settings/class-tab-protection.php:142
     1300msgid "Optional. You can use {limit} and {window}. Leave empty for the default text."
     1301msgstr ""
     1302
     1303#: includes/Admin/Settings/class-tab-protection.php:144
     1304msgid "Limit message"
     1305msgstr ""
     1306
     1307#: includes/Admin/Settings/class-tab-protection.php:146
     1308#: includes/Rest/class-nonce-controller.php:111
     1309#: includes/Security/class-rate-limiter.php:127
     1310msgid "Too many requests. Please wait a minute and try again."
     1311msgstr ""
     1312
     1313#: includes/Admin/Settings/class-tab-protection.php:155
     1314msgid "What happens when the whole-site limit is hit again and again."
     1315msgstr ""
     1316
     1317#: includes/Admin/Settings/class-tab-protection.php:157
     1318msgid "Alert after"
     1319msgstr ""
     1320
     1321#: includes/Admin/Settings/class-tab-protection.php:157
     1322msgid "The site admin gets an email (at most every 30 minutes) and an admin notice."
     1323msgstr ""
     1324
     1325#: includes/Admin/Settings/class-tab-protection.php:157
     1326msgid "limit hits within an hour"
     1327msgstr ""
     1328
     1329#: includes/Admin/Settings/class-tab-protection.php:158
     1330msgid "Switch chat off automatically"
     1331msgstr ""
     1332
     1333#: includes/Admin/Settings/class-tab-protection.php:158
     1334msgid "Stops all chat traffic until you switch it back on."
     1335msgstr ""
     1336
     1337#: includes/Admin/Settings/class-tab-protection.php:159
     1338msgid "Protection cool-down"
     1339msgstr ""
     1340
     1341#: includes/Admin/Settings/class-tab-protection.php:159
     1342msgid "After you switch the chat back on, it cannot be switched off automatically again for this long."
     1343msgstr ""
     1344
     1345#: includes/Admin/Settings/class-tab-protection.php:159
     1346#: includes/Admin/Settings/class-tab-protection.php:183
     1347msgid "minutes"
     1348msgstr ""
     1349
     1350#: includes/Admin/Settings/class-tab-protection.php:165
     1351msgid "Block unwanted visitors and handle reverse proxies."
     1352msgstr ""
     1353
     1354#: includes/Admin/Settings/class-tab-protection.php:167
     1355msgid "Blocked addresses"
     1356msgstr ""
     1357
     1358#: includes/Admin/Settings/class-tab-protection.php:167
     1359msgid "One IP address or range per line, for example 203.0.113.7 or 198.51.100.0/24. IPv6 is supported."
     1360msgstr ""
     1361
     1362#: includes/Admin/Settings/class-tab-protection.php:168
     1363msgid "Bot trap"
     1364msgstr ""
     1365
     1366#: includes/Admin/Settings/class-tab-protection.php:168
     1367msgid "Adds an invisible field that only bots fill in. Visitors never see it."
     1368msgstr ""
     1369
     1370#: includes/Admin/Settings/class-tab-protection.php:169
     1371msgid "Use a trusted proxy"
     1372msgstr ""
     1373
     1374#: includes/Admin/Settings/class-tab-protection.php:169
     1375msgid "Turn on only if your site is behind a proxy or CDN such as Cloudflare."
     1376msgstr ""
     1377
     1378#: includes/Admin/Settings/class-tab-protection.php:170
     1379msgid "Visitor IP header"
     1380msgstr ""
     1381
     1382#: includes/Admin/Settings/class-tab-protection.php:170
     1383msgid "Header that contains the real visitor IP."
     1384msgstr ""
     1385
     1386#: includes/Admin/Settings/class-tab-protection.php:171
     1387msgid "Trusted proxy addresses"
     1388msgstr ""
     1389
     1390#: includes/Admin/Settings/class-tab-protection.php:171
     1391msgid "The header is only trusted for requests coming from these addresses. One per line."
     1392msgstr ""
     1393
     1394#: includes/Admin/Settings/class-tab-protection.php:177
     1395msgid "Human verification (Google reCAPTCHA v3)"
     1396msgstr ""
     1397
     1398#: includes/Admin/Settings/class-tab-protection.php:178
     1399msgid "Stop bots without giving visitors puzzles to solve."
     1400msgstr ""
     1401
     1402#: includes/Admin/Settings/class-tab-protection.php:180
     1403msgid "Site key"
     1404msgstr ""
     1405
     1406#: includes/Admin/Settings/class-tab-protection.php:180
     1407msgid "Your public reCAPTCHA v3 site key."
     1408msgstr ""
     1409
     1410#: includes/Admin/Settings/class-tab-protection.php:181
     1411msgid "Secret key"
     1412msgstr ""
     1413
     1414#: includes/Admin/Settings/class-tab-protection.php:181
     1415msgid "Your reCAPTCHA v3 secret key. Kept private and never shown after saving."
     1416msgstr ""
     1417
     1418#: includes/Admin/Settings/class-tab-protection.php:182
     1419msgid "Minimum score"
     1420msgstr ""
     1421
     1422#: includes/Admin/Settings/class-tab-protection.php:182
     1423msgid "0.0 is likely a bot, 1.0 is likely a human. 0.5 is a good start."
     1424msgstr ""
     1425
     1426#: includes/Admin/Settings/class-tab-protection.php:183
     1427msgid "Verified for"
     1428msgstr ""
     1429
     1430#: includes/Admin/Settings/class-tab-protection.php:183
     1431msgid "How long a verified visitor can chat before being checked again."
     1432msgstr ""
     1433
     1434#: includes/Admin/Settings/class-tab-protection.php:193
     1435msgid "Filter harmful or unwanted questions before they reach the AI."
     1436msgstr ""
     1437
     1438#: includes/Admin/Settings/class-tab-protection.php:195
     1439msgid "Check messages before they reach the AI"
     1440msgstr ""
     1441
     1442#: includes/Admin/Settings/class-tab-protection.php:195
     1443msgid "Checks each question with OpenAI moderation and your list of blocked words."
     1444msgstr ""
     1445
     1446#: includes/Admin/Settings/class-tab-protection.php:196
     1447msgid "Use OpenAI moderation"
     1448msgstr ""
     1449
     1450#: includes/Admin/Settings/class-tab-protection.php:196
     1451msgid "Uses your Connectors key. No extra key needed."
     1452msgstr ""
     1453
     1454#: includes/Admin/Settings/class-tab-protection.php:197
     1455msgid "Moderation time limit"
     1456msgstr ""
     1457
     1458#: includes/Admin/Settings/class-tab-protection.php:197
     1459msgid "How long to wait for OpenAI moderation. If it does not answer in time, the message is sent without it."
     1460msgstr ""
     1461
     1462#: includes/Admin/Settings/class-tab-protection.php:198
     1463msgid "Blocked words and phrases"
     1464msgstr ""
     1465
     1466#: includes/Admin/Settings/class-tab-protection.php:198
     1467msgid "One per line. Whole words, not case-sensitive."
     1468msgstr ""
     1469
     1470#: includes/Admin/Settings/class-tab-protection.php:199
     1471msgid "Reply to blocked messages"
     1472msgstr ""
     1473
     1474#: includes/Admin/Settings/class-tab-protection.php:199
     1475msgid "Shown to visitors when their question is refused by moderation."
     1476msgstr ""
     1477
     1478#: includes/Admin/Settings/class-tab-protection.php:218
     1479msgid "Use a trusted proxy is on, but no trusted proxy addresses are listed, so the header is not used."
     1480msgstr ""
     1481
     1482#: includes/Admin/Settings/class-tab-protection.php:222
     1483msgid "A trusted proxy address is also in the blocked list: every request through it would be refused."
     1484msgstr ""
     1485
     1486#: includes/Admin/Settings/class-tab-protection.php:229
     1487msgid "Some trusted proxy ranges are too wide and are ignored: list only your proxy's own addresses."
     1488msgstr ""
     1489
     1490#: includes/Admin/Settings/class-tab-protection.php:246
     1491msgid "Clear rate-limit counters"
     1492msgstr ""
     1493
     1494#: includes/Admin/Settings/class-tab-protection.php:248
     1495msgid "Starts every visitor, user and site-wide count from zero, for example after a false alarm. Verification passes and settings are not changed."
     1496msgstr ""
     1497
     1498#. translators: %s: date the chat was switched off.
     1499#: includes/Admin/Settings/class-tab-protection.php:266
     1500#, php-format
     1501msgid "Switched off automatically on %s after repeated site-wide limit hits."
     1502msgstr ""
     1503
     1504#: includes/Admin/Settings/class-tab-protection.php:282
     1505msgid "Active – keys from server environment"
     1506msgstr ""
     1507
     1508#: includes/Admin/Settings/class-tab-protection.php:288
     1509msgid "Off – add both keys to enable"
     1510msgstr ""
     1511
     1512#: includes/Admin/Settings/class-tab-protection.php:299
     1513msgid "Visitors see a short verification overlay on the chat window. Google's script loads only when both keys are set."
     1514msgstr ""
     1515
     1516#: includes/Admin/Settings/class-tab-protection.php:300
     1517msgid "Get reCAPTCHA v3 keys ↗"
     1518msgstr ""
     1519
     1520#: includes/Admin/Settings/class-tab-protection.php:313
     1521msgid "OpenAI moderation is unavailable until an OpenAI key is configured in WordPress Connectors."
     1522msgstr ""
     1523
     1524#: includes/Admin/Settings/class-tab-welcome.php:44
    1171525msgid "Welcome"
    1181526msgstr ""
    1191527
    120 #: includes/Admin/class-settings-page.php:128
    121 msgid "Protection"
    122 msgstr ""
    123 
    124 #: includes/Admin/class-settings-page.php:129
    125 msgid "Appearance"
    126 msgstr ""
    127 
    128 #: includes/Admin/class-settings-page.php:130
    129 msgid "AI Settings"
    130 msgstr ""
    131 
    132 #: includes/Admin/class-settings-page.php:173
    133 msgid "ChatHearth - AI Chatbot Settings"
    134 msgstr ""
    135 
    136 #: includes/Admin/class-settings-page.php:178
    137 msgid ""
    138 "Configure OpenAI API key under WordPress Connectors. This plugin does not "
    139 "store the API key."
    140 msgstr ""
    141 
    142 #: includes/Admin/class-settings-page.php:182
    143 msgid "Open Connectors"
    144 msgstr ""
    145 
    146 #: includes/Admin/class-settings-page.php:185
    147 msgid "Settings sections"
    148 msgstr ""
    149 
    150 #: includes/Admin/class-settings-page.php:204
     1528#: includes/Admin/Settings/class-tab-welcome.php:60
     1529msgid "Live suggestion chips preview"
     1530msgstr ""
     1531
     1532#. translators: %d: number of further suggestions that are not shown as chips.
     1533#: includes/Admin/Settings/class-tab-welcome.php:68
     1534#: assets/js/admin/starters.js:38
     1535#, php-format,js-format
     1536msgid "+%d more"
     1537msgid_plural "+%d more"
     1538msgstr[0] ""
     1539msgstr[1] ""
     1540
     1541#: includes/Admin/Settings/class-tab-welcome.php:85
     1542msgid "Greeting"
     1543msgstr ""
     1544
     1545#: includes/Admin/Settings/class-tab-welcome.php:86
     1546msgid "What visitors see when they open the chat."
     1547msgstr ""
     1548
     1549#: includes/Admin/Settings/class-tab-welcome.php:88
    1511550msgid "Welcome message"
    1521551msgstr ""
    1531552
    154 #: includes/Admin/class-settings-page.php:208
    155 msgid "Starter phrases"
    156 msgstr ""
    157 
    158 #: includes/Admin/class-settings-page.php:211
    159 msgid "One suggested prompt per line. Shown as clickable chips in the chat."
    160 msgstr ""
    161 
    162 #: includes/Admin/class-settings-page.php:220
    163 msgid "Enable chatbot"
    164 msgstr ""
    165 
    166 #: includes/Admin/class-settings-page.php:224
    167 msgid "Show the chatbot on the front end and allow chat requests"
    168 msgstr ""
    169 
    170 #: includes/Admin/class-settings-page.php:229
    171 msgid "Max requests per minute (per IP)"
    172 msgstr ""
    173 
    174 #: includes/Admin/class-settings-page.php:233
    175 msgid "Max requests per hour (per IP)"
    176 msgstr ""
    177 
    178 #: includes/Admin/class-settings-page.php:237
    179 msgid "Max requests per minute (entire site)"
    180 msgstr ""
    181 
    182 #: includes/Admin/class-settings-page.php:240
    183 msgid "Applies across all visitors. Helps stop multi-IP floods."
    184 msgstr ""
    185 
    186 #: includes/Admin/class-settings-page.php:244
    187 msgid "Max requests per hour (entire site)"
    188 msgstr ""
    189 
    190 #: includes/Admin/class-settings-page.php:248
    191 msgid "Escalate after global limit hits"
    192 msgstr ""
    193 
    194 #: includes/Admin/class-settings-page.php:251
    195 msgid ""
    196 "Number of site-wide limit blocks within an hour before emailing the admin."
    197 msgstr ""
    198 
    199 #: includes/Admin/class-settings-page.php:255
    200 msgid "Auto-disable on escalation"
    201 msgstr ""
    202 
    203 #: includes/Admin/class-settings-page.php:259
    204 msgid "Turn off the chatbot when the escalation threshold is reached"
    205 msgstr ""
    206 
    207 #: includes/Admin/class-settings-page.php:264
    208 msgid "Max message length"
    209 msgstr ""
    210 
    211 #: includes/Admin/class-settings-page.php:268
    212 msgid "Google reCAPTCHA v2"
    213 msgstr ""
    214 
    215 #: includes/Admin/class-settings-page.php:272
    216 msgid ""
    217 "CAPTCHA is enabled. Visitors complete the reCAPTCHA v2 checkbox once; "
    218 "further messages in the next hour stay unlocked."
    219 msgstr ""
    220 
    221 #: includes/Admin/class-settings-page.php:275
    222 msgid ""
    223 "CAPTCHA is disabled until both site key and secret key are set. Create a "
    224 "reCAPTCHA v2 (“I’m not a robot” Checkbox) key for your domain."
    225 msgstr ""
    226 
    227 #: includes/Admin/class-settings-page.php:280
    228 msgid "reCAPTCHA site key"
    229 msgstr ""
    230 
    231 #: includes/Admin/class-settings-page.php:286
    232 msgid "reCAPTCHA secret key"
    233 msgstr ""
    234 
    235 #: includes/Admin/class-settings-page.php:288
    236 msgid "•••••••• (saved — leave blank to keep)"
    237 msgstr ""
    238 
    239 #: includes/Admin/class-settings-page.php:292
    240 msgid "Clear saved secret key"
    241 msgstr ""
    242 
    243 #: includes/Admin/class-settings-page.php:297
    244 msgid ""
    245 "Get keys from Google reCAPTCHA admin. Leave the secret blank when saving to "
    246 "keep the current value."
    247 msgstr ""
    248 
    249 #: includes/Admin/class-settings-page.php:308
    250 msgid "Icon shape"
    251 msgstr ""
    252 
    253 #: includes/Admin/class-settings-page.php:311
    254 msgid "Circle"
    255 msgstr ""
    256 
    257 #: includes/Admin/class-settings-page.php:312
    258 msgid "Square"
    259 msgstr ""
    260 
    261 #: includes/Admin/class-settings-page.php:317
    262 msgid "Position"
    263 msgstr ""
    264 
    265 #: includes/Admin/class-settings-page.php:320
    266 msgid "Bottom right"
    267 msgstr ""
    268 
    269 #: includes/Admin/class-settings-page.php:321
    270 msgid "Bottom left"
    271 msgstr ""
    272 
    273 #: includes/Admin/class-settings-page.php:326
    274 msgid "Popup size"
    275 msgstr ""
    276 
    277 #: includes/Admin/class-settings-page.php:329
    278 msgid "Small"
    279 msgstr ""
    280 
    281 #: includes/Admin/class-settings-page.php:330
    282 msgid "Medium"
    283 msgstr ""
    284 
    285 #: includes/Admin/class-settings-page.php:331
    286 msgid "Large"
    287 msgstr ""
    288 
    289 #: includes/Admin/class-settings-page.php:336
    290 msgid "Icon size (px)"
    291 msgstr ""
    292 
    293 #: includes/Admin/class-settings-page.php:340
    294 msgid "Header title"
    295 msgstr ""
    296 
    297 #: includes/Admin/class-settings-page.php:345
    298 msgid "Icon background color"
    299 msgstr ""
    300 
    301 #: includes/Admin/class-settings-page.php:346
    302 msgid "Icon border color"
    303 msgstr ""
    304 
    305 #: includes/Admin/class-settings-page.php:347
    306 msgid "Icon (glyph) color"
    307 msgstr ""
    308 
    309 #: includes/Admin/class-settings-page.php:348
    310 msgid "User bubble color"
    311 msgstr ""
    312 
    313 #: includes/Admin/class-settings-page.php:349
    314 msgid "Assistant bubble color"
    315 msgstr ""
    316 
    317 #: includes/Admin/class-settings-page.php:364
    318 msgid "AI provider"
    319 msgstr ""
    320 
    321 #: includes/Admin/class-settings-page.php:371
    322 msgid ""
    323 "More providers can be added in future releases. Configure the API key under "
    324 "Connectors."
    325 msgstr ""
    326 
    327 #: includes/Admin/class-settings-page.php:375
    328 msgid "Chat model"
    329 msgstr ""
    330 
    331 #: includes/Admin/class-settings-page.php:382
    332 msgid "Select an OpenAI model for chat replies."
    333 msgstr ""
    334 
    335 #: includes/Admin/class-settings-page.php:386
    336 msgid "System prompt"
    337 msgstr ""
    338 
    339 #: includes/Admin/class-settings-page.php:394
    340 msgid "Save settings"
    341 msgstr ""
    342 
    343 #: includes/Ai/class-ai-gateway.php:45
    344 msgid ""
    345 "The AI provider is not configured. Please check OpenAI Connectors settings."
    346 msgstr ""
    347 
    348 #: includes/Ai/class-ai-gateway.php:133
    349 msgid ""
    350 "Sorry, the assistant could not generate a reply. Please try again later."
    351 msgstr ""
    352 
    353 #: includes/Frontend/class-assets.php:88
     1553#: includes/Admin/Settings/class-tab-welcome.php:88
     1554msgid "Shown as the first message in the chat."
     1555msgstr ""
     1556
     1557#: includes/Admin/Settings/class-tab-welcome.php:89
     1558msgid "Starter suggestions"
     1559msgstr ""
     1560
     1561#: includes/Admin/Settings/class-tab-welcome.php:89
     1562msgid "One suggestion per line. Visitors can click them to start a conversation."
     1563msgstr ""
     1564
     1565#. translators: 1: help text, 2: the allowed range, such as "100–8,000".
     1566#: includes/Admin/Settings/class-tab.php:152
     1567#, php-format
     1568msgctxt "help text followed by its allowed range"
     1569msgid "%1$s (%2$s)"
     1570msgstr ""
     1571
     1572#. translators: %s: the product names joined by " vs ".
     1573#: includes/Chat/class-catalog-stage.php:136
     1574#: includes/Frontend/class-widget-config.php:252
     1575#, php-format
     1576msgid "Compare %s in a markdown table covering price, stock, and key differences. Use only catalog facts and include product links."
     1577msgstr ""
     1578
     1579#: includes/Chat/class-chat-pipeline.php:130
     1580msgid "Sorry, the assistant could not generate a reply. Please try again later."
     1581msgstr ""
     1582
     1583#: includes/Chat/class-input-stage.php:48
     1584msgid "Please enter a message."
     1585msgstr ""
     1586
     1587#: includes/Chat/class-instructions-stage.php:74
     1588msgid "The AI provider is not configured. Please check OpenAI Connectors settings."
     1589msgstr ""
     1590
     1591#: includes/Commerce/class-cart-service.php:116
     1592#: includes/Frontend/class-widget-config.php:274
     1593msgid "Could not add that product to the cart."
     1594msgstr ""
     1595
     1596#: includes/Commerce/class-cart-service.php:224
     1597msgid "That product is not available."
     1598msgstr ""
     1599
     1600#: includes/Commerce/class-cart-service.php:235
     1601msgid "That product cannot be added to the cart."
     1602msgstr ""
     1603
     1604#: includes/Frontend/class-widget-config.php:242
    3541605msgid "Type your message…"
    3551606msgstr ""
    3561607
    357 #: includes/Frontend/class-assets.php:89
     1608#: includes/Frontend/class-widget-config.php:243
    3581609msgid "Send"
    3591610msgstr ""
    3601611
    361 #: includes/Frontend/class-assets.php:90
     1612#: includes/Frontend/class-widget-config.php:244
    3621613msgid "Clear chat"
    3631614msgstr ""
    3641615
    365 #: includes/Frontend/class-assets.php:91
     1616#: includes/Frontend/class-widget-config.php:245
    3661617msgid "Close chat"
    3671618msgstr ""
    3681619
    369 #: includes/Frontend/class-assets.php:92
     1620#: includes/Frontend/class-widget-config.php:246
    3701621msgid "Open chat"
    3711622msgstr ""
    3721623
    373 #: includes/Frontend/class-assets.php:93
     1624#: includes/Frontend/class-widget-config.php:247
    3741625msgid "Sorry, something went wrong. Please try again."
    3751626msgstr ""
    3761627
    377 #: includes/Frontend/class-assets.php:94
     1628#: includes/Frontend/class-widget-config.php:248
     1629#: includes/Frontend/class-widget-config.php:284
    3781630msgid "Thinking…"
    3791631msgstr ""
    3801632
    381 #: includes/Frontend/class-assets.php:95
    382 msgid "Please complete the CAPTCHA before sending."
    383 msgstr ""
    384 
    385 #: includes/Rest/class-chat-controller.php:124
     1633#: includes/Frontend/class-widget-config.php:250
     1634msgid "Compare these products"
     1635msgstr ""
     1636
     1637#: includes/Frontend/class-widget-config.php:253
     1638msgid "Tell me about this page"
     1639msgstr ""
     1640
     1641#: includes/Frontend/class-widget-config.php:254
     1642msgid "Double chat size"
     1643msgstr ""
     1644
     1645#: includes/Frontend/class-widget-config.php:255
     1646msgid "Restore chat size"
     1647msgstr ""
     1648
     1649#: includes/Frontend/class-widget-config.php:256
     1650msgid "Please reload the page to keep chatting."
     1651msgstr ""
     1652
     1653#: includes/Frontend/class-widget-config.php:257
     1654msgid "Reload page"
     1655msgstr ""
     1656
     1657#: includes/Frontend/class-widget-config.php:258
     1658msgid "New reply"
     1659msgstr ""
     1660
     1661#: includes/Frontend/class-widget-config.php:259
     1662msgid "Please verify you are human before chatting."
     1663msgstr ""
     1664
     1665#: includes/Frontend/class-widget-config.php:260
     1666msgid "Please verify you are human to start chatting."
     1667msgstr ""
     1668
     1669#: includes/Frontend/class-widget-config.php:261
     1670msgid "Continue"
     1671msgstr ""
     1672
     1673#: includes/Frontend/class-widget-config.php:262
     1674msgid "Verifying…"
     1675msgstr ""
     1676
     1677#: includes/Frontend/class-widget-config.php:263
     1678msgid "Verification failed. Please try again."
     1679msgstr ""
     1680
     1681#. translators: 1: privacy policy link, 2: terms of service link
     1682#: includes/Frontend/class-widget-config.php:265
     1683#, php-format
     1684msgid "This site is protected by reCAPTCHA and the Google %1$s and %2$s apply."
     1685msgstr ""
     1686
     1687#: includes/Frontend/class-widget-config.php:266
     1688msgid "Privacy Policy"
     1689msgstr ""
     1690
     1691#: includes/Frontend/class-widget-config.php:267
     1692msgid "Terms of Service"
     1693msgstr ""
     1694
     1695#: includes/Frontend/class-widget-config.php:268
     1696msgid "Your browser did not keep the verification. Please allow cookies for this site to keep chatting."
     1697msgstr ""
     1698
     1699#: includes/Frontend/class-widget-config.php:269
     1700msgid "Leave this field empty"
     1701msgstr ""
     1702
     1703#: includes/Frontend/class-widget-config.php:271
     1704msgid "Added to cart."
     1705msgstr ""
     1706
     1707#: includes/Frontend/class-widget-config.php:272
     1708msgid "View cart"
     1709msgstr ""
     1710
     1711#: includes/Frontend/class-widget-config.php:273
     1712msgid "Checkout"
     1713msgstr ""
     1714
     1715#: includes/Frontend/class-widget-config.php:275
     1716msgid "In stock"
     1717msgstr ""
     1718
     1719#: includes/Frontend/class-widget-config.php:276
     1720msgid "Out of stock"
     1721msgstr ""
     1722
     1723#: includes/Frontend/class-widget-config.php:277
     1724msgid "Choose an option"
     1725msgstr ""
     1726
     1727#: includes/Frontend/class-widget-config.php:278
     1728msgid "Choose options"
     1729msgstr ""
     1730
     1731#: includes/Frontend/class-widget-config.php:279
     1732msgid "Adding…"
     1733msgstr ""
     1734
     1735#: includes/Frontend/class-widget-config.php:280
     1736msgid "Not available to buy in the chat"
     1737msgstr ""
     1738
     1739#. translators: %s: a product option and its value, for example "Size: Large".
     1740#: includes/Frontend/class-widget-config.php:282
     1741#, php-format
     1742msgid "%s (out of stock)"
     1743msgstr ""
     1744
     1745#: includes/Frontend/class-widget-config.php:285
     1746msgid "Reading your question…"
     1747msgstr ""
     1748
     1749#: includes/Frontend/class-widget-config.php:286
     1750msgid "Looking through the site…"
     1751msgstr ""
     1752
     1753#: includes/Frontend/class-widget-config.php:287
     1754msgid "Searching for relevant information…"
     1755msgstr ""
     1756
     1757#: includes/Frontend/class-widget-config.php:288
     1758msgid "Checking the details…"
     1759msgstr ""
     1760
     1761#: includes/Frontend/class-widget-config.php:289
     1762msgid "Putting the pieces together…"
     1763msgstr ""
     1764
     1765#: includes/Frontend/class-widget-config.php:290
     1766msgid "Preparing the best answer for you…"
     1767msgstr ""
     1768
     1769#: includes/Frontend/class-widget-config.php:291
     1770msgid "Almost there…"
     1771msgstr ""
     1772
     1773#: includes/Frontend/class-widget-config.php:292
     1774msgid "Still working on it…"
     1775msgstr ""
     1776
     1777#: includes/Frontend/class-widget-config.php:293
     1778msgid "Thanks for waiting, just a moment more…"
     1779msgstr ""
     1780
     1781#: includes/Kb/class-failure-reasons.php:33
     1782msgid "OpenAI was busy or did not answer. It will be tried again on the next sync."
     1783msgstr ""
     1784
     1785#: includes/Kb/class-failure-reasons.php:36
     1786msgid "OpenAI could not use this item. Editing the item or the next sync may fix it."
     1787msgstr ""
     1788
     1789#: includes/Kb/class-failure-reasons.php:38
     1790msgid "OpenAI refused the connection. Check the connection under Settings → Connectors."
     1791msgstr ""
     1792
     1793#: includes/Kb/class-failure-reasons.php:40
     1794msgid "This item has no text to index."
     1795msgstr ""
     1796
     1797#: includes/Kb/class-failure-reasons.php:43
     1798msgid "This item could not be indexed. It will be tried again on the next sync."
     1799msgstr ""
     1800
     1801#: includes/Kb/class-kb-entry-toggle.php:69
     1802msgid "Missing source id."
     1803msgstr ""
     1804
     1805#: includes/Kb/class-kb-entry-toggle.php:73
     1806#: includes/Kb/class-kb-entry-toggle.php:88
     1807msgid "Entry not found."
     1808msgstr ""
     1809
     1810#: includes/Kb/class-status-report.php:114
     1811msgid "The Knowledge Base is off."
     1812msgstr ""
     1813
     1814#: includes/Kb/class-status-report.php:117
     1815msgid "Indexing is paused until OpenAI is ready."
     1816msgstr ""
     1817
     1818#. translators: %s: number of items waiting to be indexed.
     1819#: includes/Kb/class-status-report.php:121
     1820#, php-format
     1821msgid "Indexing %s item…"
     1822msgid_plural "Indexing %s items…"
     1823msgstr[0] ""
     1824msgstr[1] ""
     1825
     1826#: includes/Kb/class-status-report.php:124
     1827#: assets/js/admin/kb-status.js:167
     1828msgid "Checking your content…"
     1829msgstr ""
     1830
     1831#: includes/Kb/class-status-report.php:127
     1832msgid "Indexing finished. Some items could not be indexed."
     1833msgstr ""
     1834
     1835#: includes/Kb/class-status-report.php:130
     1836msgid "Everything is indexed."
     1837msgstr ""
     1838
     1839#: includes/Kb/class-status-report.php:133
     1840msgid "Nothing is indexed yet."
     1841msgstr ""
     1842
     1843#: includes/Kb/class-store-check.php:92
     1844msgid "The knowledge base is stored in this WordPress database. No extra server is required."
     1845msgstr ""
     1846
     1847#: includes/Kb/class-store-check.php:93
     1848msgid "The knowledge base tables are not available."
     1849msgstr ""
     1850
     1851#: includes/Kb/class-store-check.php:96
     1852msgid "Storage is ready."
     1853msgstr ""
     1854
     1855#: includes/Kb/class-store-check.php:97
     1856msgid "The custom storage did not answer."
     1857msgstr ""
     1858
     1859#: includes/Moderation/class-content-moderation.php:231
     1860msgid "Sorry, that message cannot be processed. Please rephrase and try again."
     1861msgstr ""
     1862
     1863#: includes/Rest/class-cart-controller.php:166
     1864#: includes/Rest/class-chat-controller.php:271
     1865#: includes/Rest/class-nonce-controller.php:98
     1866#: includes/Rest/class-recaptcha-controller.php:80
     1867msgid "The chatbot is currently disabled."
     1868msgstr ""
     1869
     1870#: includes/Rest/class-cart-controller.php:179
     1871msgid "The store cart is not available."
     1872msgstr ""
     1873
     1874#: includes/Rest/class-cart-controller.php:191
     1875#: includes/Security/class-human-check.php:61
     1876#: includes/Security/class-rate-limiter.php:139
     1877msgid "Too many requests. Please wait a moment and try again."
     1878msgstr ""
     1879
     1880#: includes/Rest/class-cart-controller.php:198
     1881msgid "Too many cart requests. Please wait a few minutes and try again."
     1882msgstr ""
     1883
     1884#: includes/Rest/class-chat-controller.php:156
     1885msgid "The conversation history is not valid."
     1886msgstr ""
     1887
     1888#: includes/Rest/class-chat-controller.php:225
    3861889msgid "Invalid security token. Please refresh the page and try again."
    3871890msgstr ""
    3881891
    389 #: includes/Rest/class-chat-controller.php:142
    390 msgid "The chatbot is currently disabled."
    391 msgstr ""
    392 
    393 #: includes/Rest/class-chat-controller.php:163
    394 msgid "Please enter a message."
    395 msgstr ""
    396 
    397 #. translators: %s: site name
    398 #: includes/Security/class-rate-limiter.php:260
     1892#: includes/Rest/class-kb-permission.php:51
     1893msgid "You are not allowed to manage the knowledge base."
     1894msgstr ""
     1895
     1896#: includes/Rest/class-request-guard.php:95
     1897msgid "Your message is too long to send. Please shorten the conversation and try again."
     1898msgstr ""
     1899
     1900#: includes/Security/class-access-check.php:49
     1901msgid "Sorry, the chat is not available to you."
     1902msgstr ""
     1903
     1904#. translators: %s: site name.
     1905#: includes/Security/class-escalation-mailer.php:80
    3991906#, php-format
    4001907msgid "[%s] ChatHearth - AI Chatbot: global rate limit escalation"
    4011908msgstr ""
    4021909
    403 #: includes/Security/class-rate-limiter.php:265
    404 msgid ""
    405 "ChatHearth - AI Chatbot blocked site-wide chat traffic after repeated global "
    406 "rate-limit hits."
    407 msgstr ""
    408 
    409 #. translators: %d: number of global limit hits in the current hour
    410 #: includes/Security/class-rate-limiter.php:269
     1910#: includes/Security/class-escalation-mailer.php:84
     1911msgid "ChatHearth - AI Chatbot blocked site-wide chat traffic after repeated global rate-limit hits."
     1912msgstr ""
     1913
     1914#. translators: %d: number of site-wide rate limit hits.
     1915#: includes/Security/class-escalation-mailer.php:87
    4111916#, php-format
    4121917msgid "Global limit hits in the last hour: %d"
    4131918msgstr ""
    4141919
    415 #. translators: 1: per-minute limit, 2: per-hour limit
    416 #: includes/Security/class-rate-limiter.php:274
     1920#. translators: 1: site-wide limit per minute, 2: site-wide limit per hour.
     1921#: includes/Security/class-escalation-mailer.php:89
    4171922#, php-format
    4181923msgid "Configured global limits: %1$d/minute, %2$d/hour"
    4191924msgstr ""
    4201925
    421 #: includes/Security/class-rate-limiter.php:282
    422 msgid ""
    423 "The chatbot has been automatically disabled. Re-enable it under Settings → "
    424 "ChatHearth - AI Chatbot → Protection when ready."
    425 msgstr ""
    426 
    427 #: includes/Security/class-rate-limiter.php:286
     1926#: includes/Security/class-escalation-mailer.php:93
     1927msgid "The chatbot has been automatically disabled. Re-enable it under Settings → ChatHearth - AI Chatbot → Protection when ready."
     1928msgstr ""
     1929
     1930#: includes/Security/class-escalation-mailer.php:95
     1931msgid "Switch the chat back on now (administrators only; works once, for 24 hours):"
     1932msgstr ""
     1933
     1934#. translators: %d: configured re-arm pause in minutes.
     1935#: includes/Security/class-escalation-mailer.php:100
     1936#, php-format
     1937msgid "The chat was not switched off, because it was switched back on less than %d minutes ago."
     1938msgstr ""
     1939
     1940#: includes/Security/class-escalation-mailer.php:103
    4281941msgid "Protection settings:"
    4291942msgstr ""
    4301943
    431 #: includes/Security/class-rate-limiter.php:322
    432 msgid ""
    433 "The chatbot is temporarily unavailable due to high demand. Please try again "
    434 "later."
    435 msgstr ""
    436 
    437 #: includes/Security/class-rate-limiter.php:333
    438 msgid "Too many requests. Please wait a minute and try again."
    439 msgstr ""
    440 
    441 #: includes/Security/class-rate-limiter.php:344
     1944#: includes/Security/class-rate-limiter.php:74
     1945msgid "The chatbot is temporarily unavailable due to high demand. Please try again later."
     1946msgstr ""
     1947
     1948#. translators: The window of a message limit, used in "You can send 10 messages per hour." Keep it a single lower-case word.
     1949#: includes/Security/class-rate-limiter.php:117
     1950msgid "hour"
     1951msgstr ""
     1952
     1953#. translators: The window of a message limit, used in "You can send 10 messages per minute." Keep it a single lower-case word.
     1954#: includes/Security/class-rate-limiter.php:119
     1955msgid "minute"
     1956msgstr ""
     1957
     1958#: includes/Security/class-rate-limiter.php:126
    4421959msgid "Hourly message limit reached. Please try again later."
    4431960msgstr ""
    4441961
    445 #: includes/Security/class-rate-limiter.php:355
    446 msgid "Too many requests. Please wait a moment and try again."
    447 msgstr ""
    448 
    449 #: includes/Security/class-recaptcha.php:54
     1962#: includes/Security/class-recaptcha-v3.php:88
     1963msgid "CAPTCHA verification failed. Please try again."
     1964msgstr ""
     1965
     1966#: includes/Security/class-recaptcha-v3.php:95
    4501967msgid "Please complete the CAPTCHA and try again."
    4511968msgstr ""
    4521969
    453 #: includes/Security/class-recaptcha.php:84
     1970#: includes/Security/class-recaptcha-v3.php:100
    4541971msgid "CAPTCHA verification is temporarily unavailable. Please try again."
    4551972msgstr ""
    4561973
    457 #: includes/Security/class-recaptcha.php:95
    458 msgid "CAPTCHA verification failed. Please try again."
    459 msgstr ""
    460 
    461 #. Description of the plugin/theme
    462 msgid "Site-wide AI chatbot powered by WordPress Connectors (OpenAI in v1)."
    463 msgstr ""
    464 
    465 #. Author of the plugin/theme
    466 msgid "PalWP"
    467 msgstr ""
    468 
    469 #. Author URI of the plugin/theme
    470 msgid "https://palwp.com/"
    471 msgstr ""
     1974#: includes/Settings/class-settings-repository.php:83
     1975msgid "ChatHearth settings."
     1976msgstr ""
     1977
     1978#. translators: 1: setting name, 2: the line numbers that were removed, such as "2 and 5".
     1979#: includes/Settings/class-settings-repository.php:244
     1980#, php-format
     1981msgid "%1$s: line %2$s was removed"
     1982msgid_plural "%1$s: lines %2$s were removed"
     1983msgstr[0] ""
     1984msgstr[1] ""
     1985
     1986#. translators: 1: setting name, 2: the value that was submitted, 3: the value that was kept.
     1987#: includes/Settings/class-settings-repository.php:256
     1988#, php-format
     1989msgid "%1$s: \"%2$s\" became \"%3$s\""
     1990msgstr ""
     1991
     1992#: includes/Settings/class-settings-repository.php:266
     1993msgid "ChatHearth corrected some values before saving:"
     1994msgstr ""
     1995
     1996#. translators: %s: contrast ratio such as 3.1 (shown as 3.1:1).
     1997#: assets/js/admin/appearance-preview.js:147
     1998#, js-format
     1999msgid "Low contrast (%s:1). Some visitors may find messages hard to read."
     2000msgstr ""
     2001
     2002#. translators: %d: number of settings that need correcting.
     2003#: assets/js/admin/error-summary.js:47
     2004#, js-format
     2005msgid "Please correct %d setting before saving:"
     2006msgid_plural "Please correct %d settings before saving:"
     2007msgstr[0] ""
     2008msgstr[1] ""
     2009
     2010#. translators: %s: the setting name and its problem.
     2011#: assets/js/admin/error-summary.js:68
     2012#, js-format
     2013msgid "Go to %s"
     2014msgstr ""
     2015
     2016#: assets/js/admin/kb-index.js:198
     2017msgid "Your session has expired. Reload the page to continue."
     2018msgstr ""
     2019
     2020#: assets/js/admin/kb-index.js:267
     2021msgid "Save your changes first"
     2022msgstr ""
     2023
     2024#: assets/js/admin/kb-index.js:271
     2025msgid "The Knowledge Base is off. Turn it on and save to sync."
     2026msgstr ""
     2027
     2028#: assets/js/admin/kb-index.js:310
     2029msgid "Sync could not be started. Try again."
     2030msgstr ""
     2031
     2032#: assets/js/admin/kb-index.js:367
     2033msgid "Storage could not be tested. Try again."
     2034msgstr ""
     2035
     2036#. translators: %s: number of items in the list.
     2037#: assets/js/admin/kb-index.js:438
     2038#, js-format
     2039msgid "%s item"
     2040msgid_plural "%s items"
     2041msgstr[0] ""
     2042msgstr[1] ""
     2043
     2044#. translators: %s: title of the item.
     2045#: assets/js/admin/kb-index.js:530
     2046#, js-format
     2047msgid "%s included"
     2048msgstr ""
     2049
     2050#. translators: %s: title of the item.
     2051#: assets/js/admin/kb-index.js:535
     2052#, js-format
     2053msgid "%s excluded"
     2054msgstr ""
     2055
     2056#: assets/js/admin/kb-index.js:550
     2057msgid "The change could not be saved. Try again."
     2058msgstr ""
     2059
     2060#. translators: %s: title of the item.
     2061#: assets/js/admin/kb-index.js:577
     2062#, js-format
     2063msgid "Include %s"
     2064msgstr ""
     2065
     2066#. translators: 1: current page, 2: number of pages.
     2067#: assets/js/admin/kb-index.js:650
     2068#, js-format
     2069msgid "Page %1$s of %2$s"
     2070msgstr ""
     2071
     2072#: assets/js/admin/kb-index.js:715
     2073msgid "The list could not be loaded. Try again."
     2074msgstr ""
     2075
     2076#. translators: 1: number of items done, 2: number of items in all.
     2077#: assets/js/admin/kb-status.js:176
     2078#, js-format
     2079msgid "Syncing… %1$s of %2$s item"
     2080msgid_plural "Syncing… %1$s of %2$s items"
     2081msgstr[0] ""
     2082msgstr[1] ""
     2083
     2084#. translators: %s: number of items that could not be indexed.
     2085#: assets/js/admin/kb-status.js:196
     2086#, js-format
     2087msgid "%s item could not be indexed."
     2088msgid_plural "%s items could not be indexed."
     2089msgstr[0] ""
     2090msgstr[1] ""
     2091
     2092#: assets/js/admin/kb-status.js:240
     2093msgid "Indexing paused."
     2094msgstr ""
     2095
     2096#: assets/js/admin/kb-status.js:242
     2097msgid "Indexing finished."
     2098msgstr ""
     2099
     2100#: assets/js/admin/status-report.js:26
     2101msgid "Could not copy the status report. Select the text and copy it manually."
     2102msgstr ""
     2103
     2104#: assets/js/admin/status-report.js:56
     2105msgid "Status report copied."
     2106msgstr ""
     2107
     2108#. translators: 1: the first line numbers, 2: the last line number, as in "1, 2 and 3".
     2109#: assets/js/admin/validation.js:32
     2110#, js-format
     2111msgid "%1$s and %2$s"
     2112msgstr ""
     2113
     2114#. translators: %s: line number.
     2115#: assets/js/admin/validation.js:54
     2116#, js-format
     2117msgid "Line %s is not a valid IP address or range."
     2118msgstr ""
     2119
     2120#. translators: %s: line numbers such as "1, 2 and 3".
     2121#: assets/js/admin/validation.js:62
     2122#, js-format
     2123msgid "Lines %s are not valid IP addresses or ranges."
     2124msgstr ""
     2125
     2126#. translators: %d: highest number of lines.
     2127#: assets/js/admin/validation.js:80
     2128#, js-format
     2129msgid "Use at most %d lines."
     2130msgstr ""
     2131
     2132#: assets/js/admin/validation.js:90
     2133msgid "Fill in this field."
     2134msgstr ""
     2135
     2136#: assets/js/admin/validation.js:94
     2137msgid "Enter a hex colour such as #0f172a."
     2138msgstr ""
     2139
     2140#: assets/js/admin/validation.js:95
     2141#: assets/js/admin/validation.js:118
     2142msgid "This value is not valid."
     2143msgstr ""
     2144
     2145#: assets/js/admin/validation.js:98
     2146msgid "Enter a number."
     2147msgstr ""
     2148
     2149#. translators: 1: lowest value, 2: highest value.
     2150#: assets/js/admin/validation.js:103
     2151#, js-format
     2152msgid "Enter a number between %1$s and %2$s."
     2153msgstr ""
     2154
     2155#: assets/js/admin/validation.js:110
     2156msgid "Enter a whole number."
     2157msgstr ""
     2158
     2159#. translators: %s: allowed step between values.
     2160#: assets/js/admin/validation.js:113
     2161#, js-format
     2162msgid "Enter a value in steps of %s."
     2163msgstr ""
  • chathearth/trunk/languages/index.php

    r3663506 r3833468  
    11<?php
    2 /**
    3  * Silence is golden.
    4  *
    5  * @package ChatHearth
    6  */
     2// Silence is golden.
  • chathearth/trunk/readme.txt

    r3673790 r3833468  
    11=== ChatHearth - AI Chatbot ===
    22Contributors: palwp, momadhoun
    3 Tags: chatbot, ai, openai, connectors, customer-support
     3Tags: chatbot, ai, openai, assistant, chat
    44Requires at least: 7.0
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.4.9
    8 License: GPLv2 or later
     7Stable tag: 2.0.0
     8License: GPL-2.0-or-later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Site-wide AI chatbot powered by WordPress Connectors. Version 1 uses OpenAI via the AI Provider for OpenAI plugin.
     11An AI chatbot for WordPress that answers from your own content and your shop, powered by the AI Provider for OpenAI plugin.
     12
    1213
    1314== Description ==
    1415
    15 ChatHearth - AI Chatbot adds a floating chat widget to your site. Visitors get a welcome message and starter phrases, then chat with an AI assistant configured through WordPress Connectors.
    16 
    17 Owned by [PalWP](https://palwp.com/). Support by [Mohammed Al-Madhoun](https://profiles.wordpress.org/momadhoun/) (`momadhoun`).
    18 
    19 **Version 1 highlights**
    20 
    21 * OpenAI via WordPress Connectors / AI Client (provider and chat model selectable in settings)
    22 * Settings page under Settings → ChatHearth - AI Chatbot (Welcome, Protection, Appearance, AI Settings, Knowledge Base)
    23 * Appearance controls (shape, colors, position, popup size)
    24 * Welcome message and clickable starter phrases
    25 * System prompt settings plus always-on website-only grounding
    26 * Knowledge Base (RAG): markdown from selected pages, posts, custom post types, products, and taxonomies; embeddings stored in the WordPress database; incremental updates
    27 * Product comparison in chat and add to WooCommerce cart from the widget
    28 * The chat icon is not shown on the site until an OpenAI API key is configured under Connectors
    29 * Answers questions about the page the visitor is currently viewing (public WordPress content for that URL)
    30 * Protection: kill switch, per-IP and site-wide (global) rate limits, escalation email/admin notice, optional auto-disable, max message length, content moderation (keyword list + optional OpenAI Moderations API), optional Google reCAPTCHA v3 overlay (once per hour after first success; enabled when both keys are set)
    31 * Conversation history in the browser (localStorage)
    32 * Non-streaming replies with a typing indicator and Markdown rendering
    33 
    34 Configure your OpenAI API key under **Connectors**. This plugin does not store the API key.
    35 
    36 **Planned: Evaluation and observability**
    37 
    38 Later releases are expected to add more CAPTCHA providers (Cloudflare Turnstile, hCaptcha), tokens and cost monitoring, hard cost ceilings with admin escalation, latency and reliability metrics, RAG quality evaluation, hallucination detection, explainability, transparency, and controllability. See the plugin `plan/` docs (especially `metrics-and-methods-for-quality.md` and `functionalities.md`) for details.
     16ChatHearth adds an AI chatbot to your WordPress site. Visitors ask a question in a chat window and get an answer from your own pages, posts and, with WooCommerce, your products, with links to the pages the answer comes from. It uses the AI connection that WordPress itself manages, through the **AI Provider for OpenAI** plugin, so your API key is never entered or stored in ChatHearth.
     17
     18**Requirements.** WordPress 7.0 or newer, PHP 7.4 or newer, and the **AI Provider for OpenAI** plugin with an OpenAI API key under Settings → Connectors. WordPress will not activate ChatHearth until that plugin is installed and active. WooCommerce is optional: the shop features only appear on a site that has it.
     19
     20**The chat widget.** A launcher in the corner of every public page, as an icon or as a pill with your own label, opens a chat panel. The panel shows your welcome message and suggestions, a "Tell me about this page" suggestion where the page is known, formatted answers (headings, lists, tables, code and safe links), the sources of an answer and product cards. It follows your appearance settings and keeps its look on any theme, works with the keyboard and screen readers, mirrors for right-to-left languages and fills the screen on phones. The launcher only appears when the chat is switched on and OpenAI is ready, and never in the admin area or on the login page.
     21
     22**Website grounding.** The assistant answers only about this website. With every message it is given a short summary of your public pages (and, with WooCommerce, your store and its product categories), so it can answer from your site and politely refuse unrelated questions. When a visitor asks about "this page" or "this product", it also reads the public content of the page they are on. A source, and for a product a product card, is shown only when the answer links to that page. Your own instructions in the AI Settings tab are added after these rules and cannot widen the scope. Drafts, private and password-protected content are never used.
     23
     24**Knowledge Base.** You choose which public content the assistant can learn from: content types (posts, pages, products and custom types), categories and tags, a summary of your site and, with WooCommerce, a summary of your store. The content is indexed in the background, in small steps, so even a site with thousands of posts never times out, and the Knowledge Base tab shows how far indexing has got. Later changes (new, edited, unpublished and deleted items, renamed categories, price and stock changes) update only what really changed, so nothing is paid for twice. Passages are stored once, in a compact form, in your WordPress database. Optional protected markdown copies of your content can be kept in your uploads folder. The index needs no extra server or account. Each question then finds the passages that match it best, in your language or another, and the answer lists the pages it links to under Sources. Questions that compare things use twice as many passages. The built-in store suits about 10,000 passages (roughly 2,500 pages); larger sites should use a persistent object cache or plug in another store through the `chathearth_vector_store` filter. A search never takes longer than about 2 seconds: it stops reading and uses the best passages found so far.
     25
     26**Shop.** With WooCommerce, the assistant shows products as cards: the products a visitor names, the product of the page they are on and the products it finds in your Knowledge Base. A card shows the picture, price and stock, a choice of option for a variable product and an Add to cart button that works for guests too, followed by View cart and Checkout links. Comparisons show exactly the products that were named and use their real price, stock, categories and attributes. Payment always happens at your store's own checkout. Nothing shop-related appears on a site without WooCommerce.
     27
     28**Protection and moderation.** Visitors and the whole site have rate limits, so a burst of messages cannot run up your bill. When the site-wide limits are hit repeatedly you get an alert, the chat can switch itself off, and a one-click link switches it back on. Content moderation refuses a message that holds a blocked word or phrase (whole words, in any language) or that OpenAI moderation flags, with a reply you wrote, before any answer is generated. Optional Google reCAPTCHA v3 asks a visitor to verify once before chatting.
     29
     30**Protection extras.** Logged-in users get their own message limits, counted per account instead of per network, and you can give a role a larger allowance (×1 to ×10). A list of blocked addresses and ranges, IPv4 and IPv6, refuses unwanted visitors before anything else happens. An invisible bot trap catches programs that fill in every form field. One button clears all rate-limit counters, for example after a false alarm. Your "limit reached" message can show the limit and the time window with `{limit}` and `{window}`. Behind a CDN or reverse proxy such as Cloudflare, turn on the trusted proxy and list its addresses, so limits and blocking use the real visitor address.
     31
     32The conversation is kept in the visitor's browser and removed after 24 hours without a new message, or sooner when the visitor clears the chat. The Knowledge Base setting is off by default. Nothing is sent to OpenAI or Google when a page loads: only a visitor's message, or the changes you make to the Knowledge Base, start a request (see External services).
     33
     34== Installation ==
     35
     361. Install and activate the **AI Provider for OpenAI** plugin first (Plugins → Add New). ChatHearth requires it, and WordPress will not activate ChatHearth without it.
     372. Add your OpenAI API key under **Settings → Connectors**. ChatHearth never sees or stores the key.
     383. Install ChatHearth: upload the `chathearth` folder to `/wp-content/plugins/`, or install it through Plugins → Add New, and activate it.
     394. Open **Settings → ChatHearth - AI Chatbot**. Check the Welcome and Appearance tabs, then **Switch the chat on** with "Enable chatbot" in the Protection tab and save. The chat icon appears on your public pages once the chat is on and OpenAI is ready.
     405. Optional: turn on the **Knowledge Base** tab to let the assistant learn from your content, enter both **reCAPTCHA** keys under Protection to verify visitors, and install **WooCommerce** to show product cards with Add to cart.
     41
     42== Frequently Asked Questions ==
     43
     44= Does this plugin store my OpenAI API key? =
     45
     46No. The key is managed by WordPress under Settings → Connectors (or by your server's environment), through the AI Provider for OpenAI plugin. ChatHearth never reads, stores or passes it on.
     47
     48= What does it cost to run? =
     49
     50ChatHearth itself is free. The replies, the optional moderation check and the optional Knowledge Base indexing are billed by OpenAI to your own account, by the amount of text sent. Rate limits for each visitor and for the whole site keep a burst of messages from running up the bill, and indexing only sends what changed (see "Does indexing cost anything?").
     51
     52= Why does WordPress refuse to activate ChatHearth? =
     53
     54ChatHearth requires the AI Provider for OpenAI plugin. Install and activate that plugin first, then activate ChatHearth.
     55
     56= Why don't I see the chat on my site? =
     57
     58The chat icon appears on your public pages only when the chat is switched on, OpenAI is ready (the plugin is active and an API key is saved under Settings → Connectors) and the page is not the admin area or the login page. The settings page shows whether the chat is live, off or not ready.
     59
     60= Where is the conversation kept? =
     61
     62In the visitor's browser only. It is kept in the visitor's browser and removed after 24 hours without a new message, or sooner when the visitor clears the chat. ChatHearth does not store conversations on your server.
     63
     64= Can customers buy from the chat? =
     65
     66Yes, when WooCommerce is active. The assistant shows product cards with a price, the stock and an Add to cart button, also to guests (visitors who are not signed in), and after an add the card offers View cart and Checkout. For a product with options such as a size, the visitor picks an option first; a product whose options cannot be chosen in a card gets a Choose options link to its page. The assistant never places an order: payment happens at your store's checkout. To keep the chat fair, one visitor network can add 30 products to the cart in 10 minutes.
     67
     68= Where are the settings? =
     69
     70Under Settings, ChatHearth - AI Chatbot, or through the Settings link on the Plugins screen. The page has six tabs: Welcome, Protection, Appearance, AI Settings, Knowledge Base and Advanced.
     71
     72= How does abuse and rate-limit protection work? =
     73
     74Under Protection you set message limits for each visitor network and for the whole site, separate limits for logged-in users, a list of blocked addresses, an invisible bot trap and an "Enable chatbot" switch. When the site-wide limits are hit repeatedly, ChatHearth emails you, shows an alert in the admin area and can switch the chat off by itself; a one-click link switches it back on. Optional content moderation checks each message against your blocked words and, if you choose, OpenAI moderation, before any answer is generated. Optional Google reCAPTCHA v3 asks a visitor to press Continue and verify once, and a short-lived cookie keeps the visitor from being asked again for an hour. The checks run in this order: kill switch, blocked addresses, bot trap, human verification, site-wide limits, visitor limits, moderation, then the AI.
     75
     76= Why do visitors behind a proxy share a limit? =
     77
     78Behind a content delivery network or proxy, all visitors share one limit until trusted proxies are set up. Behind a CDN or proxy such as Cloudflare, turn on "Use a trusted proxy" under Protection, Access rules, and list its addresses, so limits and blocking use the real visitor address.
     79
     80= Does the human verification overlay record consent? =
     81
     82The overlay explains the Google check before it starts. ChatHearth does not record consent through this overlay.
     83
     84= What happens if a visitor blocks cookies? =
     85
     86With human verification enabled, a browser that blocks cookies asks the visitor to verify before every message.
     87
     88= Is the Knowledge Base on? =
     89
     90No. The Knowledge Base is off by default. Turn it on in the Knowledge Base tab when you want answers to use content from your site. Indexing starts in the background when you save, and the Index section shows its progress.
     91
     92= Does indexing cost anything? =
     93
     94OpenAI charges for creating the embeddings. Only content that changed is embedded again: saving an item without changing it costs nothing. About US$0.10 indexes 5,000 average posts with the default model (the price at the time of writing).
     95
     96= Is there a limit to the size of the Knowledge Base? =
     97
     98The built-in store suits about 10,000 passages (roughly 2,500 pages). Above that, use a persistent object cache or a larger InnoDB buffer pool, or have a developer replace the store through the `chathearth_vector_store` filter. Every search stops reading after 2 seconds and uses the best passages found so far, so a very large index gives less complete answers instead of a slow chat.
     99
     100= How do I keep a page out of the assistant's answers? =
     101
     102Open the Knowledge Base tab, find the page in the Index list (search by title or address, or filter by type, status and Included), and turn off its Included switch. The assistant stops using the page at once, even for the very next question. Turn the switch on again to bring it back: the page is indexed again in the background.
     103
     104= Can I upgrade from ChatHearth 1.4.9 without indexing again? =
     105
     106Yes. Update the plugin as usual: your settings, Knowledge Base, alerts and visitors' saved chats are kept. An existing 1.4.9 index keeps working. It is converted to the smaller storage format in the background, without asking OpenAI again. Each old text copy of a vector is removed as soon as its converted copy is stored, so going back to 1.4.9 afterwards needs a new index there. If you use a page cache, clear it after the update.
     107
     108= How do I go back to 1.4.9? =
     109
     110Install the 1.4.9 package (`chathearth-1.4.9.zip`) over ChatHearth 2.0 on the Plugins screen, choosing to replace the current version, or run `wp plugin install chathearth-1.4.9.zip --force`. Nothing needs to be deleted first. 1.4.9 keeps your settings and the entries of your Knowledge Base, and it ignores the settings that only 2.0 has.
     111
     1121.4.9 cannot read the compact passage storage that 2.0 converted your index to, so it must index the Knowledge Base again. Mark every included entry for indexing with a database tool, using your own table prefix instead of `wp_`: `UPDATE wp_chathearth_kb_entries SET status = 'pending', error_message = NULL WHERE included = 1;` Then open the Knowledge Base tab and press Sync now. The cost is one embedding of your whole Knowledge Base, the same as the first indexing.
     113
     114The extra columns and options that 2.0 added stay in the database, unused by 1.4.9. Deleting the plugin removes them.
     115
     116== Screenshots ==
     117
     1181. Answers from your own website (what you sell, how to contact you, delivery), each with its source.
     1192. Helpful suggestions that link to the right categories and products, here for choosing a gift.
     1203. Product cards with price, stock and Add to cart, for guests too.
     1214. Ask about a product by name and get its price, stock and card.
     1225. Ask about the page you are on: the assistant answers from that product, with its options and Add to cart.
     1236. Product comparisons as a table, using only facts from your shop.
     1247. Store policies answered from your own pages, such as what to do when an item arrives broken.
     1258. Welcome settings: the greeting and the starter suggestions visitors can click.
     1269. Protection, Availability: switch the chat on or off for your whole site.
     12710. Protection, Message limits: the longest message and how much of the conversation is sent with each question.
     12811. Protection, Rate limits: questions per minute and per hour for each visitor and for the whole site, with extra allowance for logged-in roles.
     12912. Protection, Escalation: an e-mail and an admin notice when the site limit is hit again and again, and an optional automatic switch-off.
     13013. Protection, Access rules: blocked addresses, an invisible bot trap and support for proxies such as Cloudflare.
     13114. Protection, Human verification: optional Google reCAPTCHA v3 with no puzzles; a verified visitor chats for a set time before the next check.
     13215. Protection, Content moderation: OpenAI moderation and your own blocked words check each question before it reaches the AI.
     13316. Appearance: the launcher, the chat window and the product cards, with a live preview.
     13417. AI Settings: the model, your own instructions and the built-in website rules; the API key stays in WordPress Connectors.
     13518. Knowledge Base: what the assistant learns from, search tuning, and the index with its sync status.
     13619. Advanced: the system status report and what happens to your data when the plugin is deleted.
    39137
    40138== External services ==
    41139
    42 This plugin relies on the following third-party services to work. It does not send any data to these services until the site owner configures them and a visitor actively uses the chatbot. No visitor is tracked automatically, and the plugin adds no analytics, advertising, or usage-tracking calls of its own.
    43 
    44 = OpenAI (AI chat replies) =
    45 
    46 The chatbot generates replies using OpenAI's API, accessed through WordPress Connectors / the core AI Client and the required "AI Provider for OpenAI" plugin. This is the core service that produces the assistant's answers.
    47 
    48 * **What is sent:** the text of the message a visitor types, the recent conversation history from that visitor's browser session, the site's configured system prompt, the URL and WordPress id of the page they are viewing (so the assistant can load that page's public content from WordPress — not the raw HTML from the browser), and the selected model name.
    49 * **When it is sent:** only when a visitor actively submits a message in the chat widget. Nothing is sent on page load or in the background.
    50 * **Where the API key lives:** the OpenAI API key is configured under WordPress Connectors (or the `OPENAI_API_KEY` environment variable / constant). This plugin does not store the API key and does not store chat transcripts in the WordPress database.
    51 
    52 OpenAI Terms of Use: https://openai.com/policies/terms-of-use/
    53 OpenAI Privacy Policy: https://openai.com/policies/privacy-policy/
    54 OpenAI API data usage policy: https://openai.com/policies/usage-policies/
    55 
    56 = OpenAI Moderations API (content moderation) =
    57 
    58 When content moderation is enabled under Settings → ChatHearth - AI Chatbot → Protection and the OpenAI Moderations layer is on, visitor message text is checked with OpenAI’s Moderations endpoint before a chat reply is generated. This helps block harmful or disallowed content and ToS-violating usage.
    59 
    60 * **What is sent:** the text of the current message and prior user turns from that visitor’s browser session (truncated to a safe length). No system prompt is sent to Moderations.
    61 * **When it is sent:** only when a visitor submits a message, content moderation is enabled, the OpenAI Moderations option is on, and OpenAI is configured under Connectors. If moderation is off or only the keyword list is used, this endpoint is not called.
    62 * **Where the API key lives:** the same OpenAI API key from WordPress Connectors (or `OPENAI_API_KEY`). This plugin does not store a separate moderation key.
    63 * **Endpoint used:** `https://api.openai.com/v1/moderations`
    64 
    65 OpenAI Terms of Use: https://openai.com/policies/terms-of-use/
    66 OpenAI Privacy Policy: https://openai.com/policies/privacy-policy/
    67 OpenAI API data usage policy: https://openai.com/policies/usage-policies/
    68 
    69 = OpenAI Embeddings API (knowledge base) =
    70 
    71 When the Knowledge Base (RAG) is enabled, ChatHearth creates embeddings for selected site content and for visitor questions so matching passages can be retrieved. This uses the same OpenAI API key from Connectors.
    72 
    73 * **What is sent:** markdown generated from selected pages, posts, products, taxonomies, and site/store summaries (at index time), and the visitor’s current question (at chat time).
    74 * **When it is sent:** only when RAG is enabled and the site owner runs a sync / content changes, or a visitor sends a chat message while RAG is on.
    75 * **Endpoint used:** `https://api.openai.com/v1/embeddings`
    76 
    77 Embeddings and generated markdown stay on this WordPress site (custom tables and `uploads/chathearth/kb/`). The plugin does not contact Chroma, Pinecone, or any other vector-database service.
    78 
    79 = Google reCAPTCHA v3 (optional bot/abuse protection) =
    80 
    81 Google reCAPTCHA v3 is an optional, score-based human-verification service used only to protect the chat endpoint from automated abuse. It is **disabled by default** and only becomes active when the site owner provides both a reCAPTCHA site key and secret key (under Settings → ChatHearth - AI Chatbot → Protection, or via the `CHATHEARTH_RECAPTCHA_SITE_KEY` and `CHATHEARTH_RECAPTCHA_SECRET_KEY` environment variables).
    82 
    83 * **What is sent:** when enabled, the reCAPTCHA JavaScript is loaded from Google on front-end pages where the chat widget appears, and Google may collect device, browser, and usage data (including the visitor's IP address) to assess whether the visitor is human. When the chat opens, a verification token and the visitor's IP address are sent to Google's verification endpoint. A white, translucent, blurred overlay covers the chat window until verification succeeds.
    84 * **When it is sent:** only when the site owner has enabled reCAPTCHA (both keys set). If reCAPTCHA is not configured, no request is ever made to Google and Google's script is not loaded.
    85 * **Endpoints used:** `https://www.google.com/recaptcha/api.js` (script) and `https://www.google.com/recaptcha/api/siteverify` (server-side verification).
    86 
    87 Google Terms of Service: https://policies.google.com/terms
    88 Google Privacy Policy: https://policies.google.com/privacy
    89 
    90 = Privacy and consent =
    91 
    92 This plugin does not track users and does not contact any external server without consent:
    93 
    94 * **OpenAI** is only reached after the site owner installs the required provider plugin and configures an API key under Connectors. By installing, configuring, and activating that service, the site owner grants consent for chat messages to be sent to OpenAI (the Software as a Service exception). Data is sent only when a visitor actively submits a message. When content moderation with OpenAI Moderations is enabled, message text may also be sent to OpenAI’s Moderations endpoint before a reply is generated.
    95 * **Google reCAPTCHA** is opt-in and off by default. It loads and contacts Google only after the site owner enters both reCAPTCHA keys. With no keys set, Google is never contacted.
    96 * **No silent tracking:** the plugin includes no analytics, advertising, fingerprinting, or usage-tracking calls. The visitor's IP address is used locally for rate limiting and abuse protection only (short-lived counters), and is not sold, shared, or logged as a chat transcript.
    97 
    98 Site owners should review the privacy policies of any service they enable and update their own site's privacy policy accordingly. Suggested privacy-policy text is provided under Settings → Privacy.
    99 
    100 == Installation ==
    101 
    102 1. Install and activate the **AI Provider for OpenAI** plugin.
    103 2. Add your OpenAI API key under WordPress **Connectors**.
    104 3. Upload the `chathearth` folder to `/wp-content/plugins/`, or install the zip.
    105 4. Activate **ChatHearth - AI Chatbot**.
    106 5. Open **Settings → ChatHearth - AI Chatbot** and save your settings.
    107 
    108 == Frequently Asked Questions ==
    109 
    110 = Does this plugin store my OpenAI API key? =
    111 
    112 No. Use WordPress Connectors (or the OPENAI_API_KEY environment variable / constant).
    113 
    114 = Why don't replies stream token by token? =
    115 
    116 WordPress AI Client / Connectors do not expose streaming yet. v1 shows a typing indicator, then the full reply. Streaming is planned for a later release.
    117 
    118 = Where is chat history stored? =
    119 
    120 In the visitor's browser via localStorage. Server-side history is planned for a future release.
    121 
    122 = How does abuse / rate-limit protection work? =
    123 
    124 Under Settings → ChatHearth - AI Chatbot → Protection you can set per-IP limits, site-wide (global) limits, an escalation threshold, and optional auto-disable. Optionally add Google reCAPTCHA v3 site and secret keys — CAPTCHA turns on automatically when both are set (green status in settings). Visitors then see a white blurred overlay on the chat window until Google verifies them. Content moderation can check messages with a keyword list and/or OpenAI’s Moderations API before they reach the chat model. Chat requests are checked in order: kill switch, reCAPTCHA (if enabled), then global limits, then per-IP limits, then content moderation (if enabled), then the AI call. When global limits are hit repeatedly within an hour, the plugin emails the admin, shows an admin notice, and can turn the chatbot off automatically.
    125 
    126 = Will there be usage, cost, or quality monitoring? =
    127 
    128 Yes — planned under Evaluation and observability (tokens/cost, latency, groundedness, hallucination checks, admin dashboards). Request-count protection, admin escalation, and optional reCAPTCHA v3 ship now; hard dollar/token ceilings and additional CAPTCHA providers (Turnstile, hCaptcha) are still planned.
    129 
    130 == Screenshots ==
    131 
    132 1. Floating chat widget on the front end with welcome message and starter phrases.
    133 2. Settings → ChatHearth - AI Chatbot — Welcome tab (greeting and starter phrases).
    134 3. Settings → ChatHearth - AI Chatbot — Protection tab (rate limits, content moderation, and optional reCAPTCHA).
    135 4. Settings → ChatHearth - AI Chatbot — Appearance tab (colors, shape, position, and size).
    136 5. Settings → ChatHearth - AI Chatbot — AI Settings tab (provider, model, and system prompt).
    137 6. Settings → ChatHearth - AI Chatbot — Knowledge Base tab (RAG sources, sync).
     140ChatHearth sends text to OpenAI so that it can write a reply, check a message and search your content, and, when you turn it on, asks Google to check that a visitor is human. Nothing is sent when a page loads: only a visitor's message, a visitor pressing Continue, or the changes you make to the Knowledge Base start a request, and nothing is sent while the chat is switched off. ChatHearth never reads, stores or passes on your OpenAI API key.
     141
     142**OpenAI chat replies, through the AI Provider for OpenAI plugin**
     143
     144* **What is sent:** the visitor's message, the recent part of the conversation (up to the number of messages you allow in the settings) and the instructions you wrote in the AI Settings tab.
     145* **Website grounding:** with each message, ChatHearth also sends a summary of your public pages (their titles and addresses, up to 40) and, with WooCommerce, your store and up to 50 product categories, and the public content of the page the visitor is on. Drafts, private and password-protected content is never sent, and content is read as a guest sees it. The summary is kept on your server for up to 12 hours.
     146* **Shop facts:** when WooCommerce is active, the facts of the products named in a message or found in your Knowledge Base (name, price, stock, categories, attributes and short description) go with the message.
     147* **When:** only when a visitor sends a message. Nothing is sent when a page loads, and nothing is sent while the chat is switched off.
     148* **Where:** `https://api.openai.com/v1/`, through WordPress's own AI Client and the AI Provider for OpenAI plugin, which makes the request with your key and has its own disclosure: [AI Provider for OpenAI](https://wordpress.org/plugins/ai-provider-for-openai/).
     149* **Not stored:** ChatHearth does not store messages, conversations or replies.
     150* **OpenAI's terms and privacy policy:** [Terms of use](https://openai.com/policies/terms-of-use/) and [Privacy policy](https://openai.com/policies/privacy-policy/).
     151
     152**Knowledge Base indexing and search**
     153
     154* **What is sent:** The public content selected in the Knowledge Base settings is sent to the OpenAI embeddings service when it is indexed and when it changes, only while the Knowledge Base is on and OpenAI is connected. Each item is sent as readable text (its title, address, text, categories and, for a product, its price, stock and attributes), in batches. Drafts, private and password-protected content, comments and author e-mail addresses are never sent.
     155* **Where:** `https://api.openai.com/v1/embeddings`. WordPress's AI Client has no embeddings request, so ChatHearth sends this request to OpenAI's address itself, signed by the AI Client's own OpenAI connection (the AI Provider for OpenAI plugin). ChatHearth never reads, stores or passes on your API key, and no setting or filter changes the address. Plugin Check lists this as a direct integration.
     156* **Visitor questions:** While the Knowledge Base is on and OpenAI is connected, each visitor question is sent to the OpenAI embeddings service to find matching passages. ChatHearth does not store the question for this. It is sent once for each message that passed the protection checks, and not for a message that was refused.
     157* **When:** the content is sent in the background after you turn the Knowledge Base on, change its sources or the passage size, or change an item. A question is sent when a visitor sends a message. Nothing is sent while the Knowledge Base is off.
     158* **Stored:** the vectors and the readable text of your own public content stay in your WordPress database. The index holds no visitor or account data.
     159* **OpenAI's terms and privacy policy:** [Terms of use](https://openai.com/policies/terms-of-use/) and [Privacy policy](https://openai.com/policies/privacy-policy/).
     160
     161**OpenAI moderation**
     162
     163* **What is sent:** the new message and up to two earlier visitor messages of the same chat, never the assistant's replies. Only texts that were not checked in the last 24 hours are sent.
     164* **Where:** `https://api.openai.com/v1/moderations`. WordPress's AI Client has no moderation request, so ChatHearth sends this request to OpenAI's address itself, signed by the AI Client's own OpenAI connection. ChatHearth never reads, stores or passes on your API key. Plugin Check lists this as a direct integration.
     165* **When:** only when a visitor sends a message and both "Check messages before they reach the AI" and "Use OpenAI moderation" are on. If OpenAI does not answer in the time you choose, the message is sent without the check.
     166* **Remembered:** the result of a check is remembered for 24 hours under a salted hash. The text itself is never stored.
     167* **OpenAI's terms and privacy policy:** [Terms of use](https://openai.com/policies/terms-of-use/) and [Privacy policy](https://openai.com/policies/privacy-policy/).
     168
     169**Google reCAPTCHA v3**
     170
     171* **When Google is contacted.** The owner must configure both reCAPTCHA keys. The browser loads Google's script only after the visitor presses Continue. Your server contacts Google when verifying the resulting token.
     172* **Where:** `https://www.google.com/recaptcha/api.js` (the script, loaded by the visitor's browser) and `https://www.google.com/recaptcha/api/siteverify` (the check, made by your server).
     173* **What is sent.** Google's script sends its own technical data from the browser. Your server sends the verification token and the visitor's IP address to Google.
     174* **Cookie.** After a successful check ChatHearth sets a cookie called `chathearth_human` (HTTP-only) that lasts at most 60 minutes and is used only to skip repeated checks.
     175* [Google Terms of Service](https://policies.google.com/terms) and [Google Privacy Policy](https://policies.google.com/privacy).
     176
     177== Source code and build ==
     178
     179The scripts of the settings page are written as small readable modules in `assets/js/admin/`, and the script of the chat widget as modules in `assets/js/frontend/` and `assets/js/shared/`; all of them are included in this plugin. The files in `assets/js/build/` (`assets/js/build/index.js` for the settings page and `assets/js/build/widget.js` for the chat widget) are generated from them with the `@wordpress/scripts` package. The styles in `assets/css/admin.css` and `assets/css/widget.css` are written by hand and are not generated.
     180
     181To rebuild the scripts, open a terminal in the plugin folder and run:
     182
     1831. `npm install`
     1842. `npm run build`
     185
     186
     187== Credits ==
     188
     189The icons on the settings page are original line drawings created for ChatHearth. They are released under the GPL-2.0-or-later licence, like the rest of the plugin.
    138190
    139191== Changelog ==
     192
     193= 2.0.0 =
     194ChatHearth 2, a complete rewrite of 1.4.9. What changed since 1.4.9:
     195
     196**Chat**
     197* A new chat window: a launcher (icon or pill) on public pages opens a panel with your welcome message and suggestions, formatted answers, sources and product cards. It follows your appearance settings on any theme, works with the keyboard and screen readers, mirrors for right-to-left languages, fills the screen on phones and respects "reduce motion".
     198* The conversation is kept in the visitor's browser and removed after 24 hours without a new message. Answers are shown safely: nothing in an answer can add markup or run a script, and links are limited to web addresses.
     199* A temporary provider failure is retried once, and visitors only ever see a generic message. The 1.4.9 developer hooks work again, and a translation template (`languages/chathearth.pot`) ships with the plugin.
     200
     201**Website grounding**
     202* The assistant answers only about your website and politely refuses other topics. Every message carries a short summary of your public pages and, with WooCommerce, your store and its categories.
     203* "This page" and "this product" work: the public content of the page the visitor is on is added to the message. Sources, and for a product a product card, appear under an answer that links to that page.
     204* Your site's instructions in the AI Settings tab are added after the rules of the website and cannot widen the scope. Drafts, private and password-protected content is never used.
     205
     206**Knowledge Base**
     207* Your chosen public content is turned into readable documents and indexed in the background, in small steps, so large sites never time out. The Knowledge Base tab shows the progress, and indexing waits on its own while OpenAI is not ready.
     208* Later changes update only what changed: publishing, editing, unpublishing, deleting, renamed categories, price and stock changes. Saving an item without a change costs nothing. Changing the passage size or the embedding model re-indexes in the background.
     209* Every question that passes the protection checks is matched against your indexed passages, and the best passages are given to the assistant. Answers list their sources. Comparison questions use twice as many passages, in English and Arabic, and developers can add words with the `chathearth_comparison_words` filter.
     210* Searching stays light as the site grows: about 6 MB of memory at 10,000 passages and no more beyond, and an optional object cache keeps the searched data. The built-in vector store suits about 10,000 passages (roughly 2,500 pages) and every search stops after 2 seconds; the `chathearth_vector_store` filter works for larger sites.
     211* The Index card works: counts of indexed, pending, excluded and failed items, the time of the last sync, a Sync now button with a progress bar, a list of items you can search, filter by type, status and Included, and switch on or off, and a Failed alert that shows the reason for each item. Test storage checks that the index storage is ready.
     212* Optional protected markdown copies of your content are kept in the uploads folder and removed when you turn the setting off. An index from ChatHearth 1.4.9 keeps working and is converted to the new format in the background, without new OpenAI requests.
     213
     214**Protection**
     215* Per-visitor-network and site-wide rate limits; sustained abuse raises an alert by e-mail and in the admin area, and the chat can switch itself off with a one-click recovery link.
     216* Logged-in users are counted per account, with an optional larger allowance for each role (×1 to ×10). A list of blocked addresses and ranges (IPv4 and IPv6) refuses a visitor before anything else happens. An invisible bot trap refuses requests that fill in a hidden field. "Clear rate-limit counters" starts every count from zero, and the limit message can show `{limit}` and `{window}`.
     217* Behind a CDN or proxy such as Cloudflare, turn on "Use a trusted proxy" and list its addresses, so limits and blocking use the real visitor address.
     218* Optional Google reCAPTCHA v3 verification loads when the visitor selects Continue. A short-lived cookie lets verified visitors keep chatting on the same network.
     219
     220**Moderation**
     221* Messages that contain a blocked word or phrase, or that OpenAI moderation flags, are refused with your reply before any answer is generated. Blocked phrases now match whole words only, in any language, so "ass" no longer blocks "class". A 1.4.9 list that relied on matches inside words may block less.
     222* OpenAI moderation checks the new message and up to two earlier visitor messages, remembers results for 24 hours, and lets the message through when OpenAI is unavailable. "Moderation time limit" controls how long to wait.
     223
     224**Shop**
     225* With WooCommerce, the products a visitor names, the product of the page they are on and the products found in your Knowledge Base appear as cards with price, stock and, for a variable product, a choice of option. Cards are styled by the eight product card settings.
     226* Add to cart works from the chat, for guests too, with "Added to cart." and View cart and Checkout links. One visitor network can add 30 products in 10 minutes.
     227* Comparisons: when a visitor names two or more products and asks to compare them, the answer and the cards cover exactly those products, with their real price, stock, categories, attributes and short description.
     228* Product names are found through a cached index that is built in the background and kept current, so a shop of 50,000 products stays fast. Compatible with WooCommerce's custom order tables and the cart and checkout blocks. Without WooCommerce nothing of this appears.
     229
     230**Settings**
     231* A settings page under Settings, ChatHearth - AI Chatbot, with six tabs and a Settings link on the Plugins screen; a live preview of the chat window while you change colours, sizes and text, with a warning when text would be hard to read; unsaved changes are marked, and mistakes are explained with links to each field.
     232* The page shows whether the chat is live, off or not ready and a System status list with a report you can copy. Suggested privacy-policy text covers every way ChatHearth handles visitor data. The reCAPTCHA secret key is never shown after it is saved. Deleting the plugin removes all of its data, unless "Keep data on uninstall" is on.
     233
     234**Update from 1.4.9**
     235* Updating from 1.4.9 is checked end to end: a populated 1.4.9 site is updated and compared before and after. Your settings, Knowledge Base entries and passages, an abuse alert and visitors' saved chats are all kept, and nothing is embedded again. The unused Chroma and Pinecone settings are removed.
     236* A CAPTCHA pass earned in 1.4.9 keeps working until it expires, up to one hour after the update, and is never renewed. A pass earned after the update belongs to the visitor's network.
     237* The `chatHearth` script data prints the 1.4.9 keys that the 2.0 widget does not read again, for themes and plugins that read them. How to go back to 1.4.9 is explained in the FAQ.
    140238
    141239= 1.4.9 =
    … …  
    205303== Upgrade Notice ==
    206304
     305= 2.0.0 =
     306No action is needed after updating: your settings, Knowledge Base, alerts and visitors' saved chats are kept and nothing is embedded again. If you use a page cache, clear it after the update.
     307
    207308= 1.4.9 =
    208309Fixes chat button styling on themes such as WoodMart, and the Knowledge Base entries list on plain permalinks.
  • chathearth/trunk/uninstall.php

    r3663506 r3833468  
    11<?php
    22/**
    3  * Uninstall cleanup.
     3 * Runs when the plugin is deleted from the Plugins screen.
     4 *
     5 * Removes the plugin's data on every site unless "Keep data on uninstall" is on (see Lifecycle\Uninstaller).
    46 *
    57 * @package ChatHearth
    68 */
    7 
    8 declare(strict_types=1);
    99
    1010if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    … …  
    1212}
    1313
    14 delete_option( 'chathearth_settings' );
    15 delete_option( 'chathearth_abuse_alert' );
     14if ( ! defined( 'ABSPATH' ) ) {
     15        exit;
     16}
    1617
     18// The plugin itself is not loaded during an uninstall, so the autoloader is registered here.
    1719if ( ! defined( 'CHATHEARTH_PATH' ) ) {
    1820        define( 'CHATHEARTH_PATH', plugin_dir_path( __FILE__ ) );
     21}
     22
     23// Up to here the file only uses syntax PHP 5.6 can parse. On an unsupported site the cleanup code cannot
     24// run, so the data is left in place rather than ending the uninstall with a fatal error.
     25require_once CHATHEARTH_PATH . 'includes/class-requirements.php';
     26if ( ! ChatHearth\Requirements::met( isset( $GLOBALS['wp_version'] ) ? $GLOBALS['wp_version'] : '0', PHP_VERSION ) ) {
     27        return;
    1928}
    2029
    … …  
    2231ChatHearth\Autoloader::register();
    2332
    24 ChatHearth\Rag\Schema::uninstall();
     33ChatHearth\Lifecycle\Uninstaller::run();
Note: See TracChangeset for help on using the changeset viewer.