Site Builder
Editing:
init.php
writable 0666
<?php /***************************************************************** * OpenAI helper (v1.8) · BestDealOn · Aug 2025 * ------------------------------------------------------------- * • AES‑encrypted API‑key cookie * • Re‑usable dark key‑bar (save / delete / model / usage link) * • ⚙ modal for per‑user defaults (temperature & max‑tokens) * • Reads the list of *allowed* models from /cache/models.json * ─── only entries with "active": true appear in the drop‑down *****************************************************************/ declare(strict_types=1); /* ---------- 0. CONFIG -------------------------------------------------- */ const AI_COOKIE = 'openai_key'; const AI_SECRET = 'openai-shared-v1'; // keep identical everywhere const AI_TTL = 30 * 24 * 3600; // 30 days const AI_MODEL_FILE = __DIR__ . '/../cache/models.json'; // editable list $AI_ROOT = (static function (): string { $h = $_SERVER['HTTP_HOST'] ?? ''; return (!filter_var($h, FILTER_VALIDATE_IP) && preg_match('/([a-z0-9-]+\.[a-z]{2,})$/i', $h, $m)) ? '.' . $m[1] : ''; })(); /* ---------- 1. CRYPTO --------------------------------------------------- */ function ai_enc(string $p): string { $algo = 'aes-128-ctr'; $key = substr(hash('sha256', AI_SECRET, true), 0, 16); $iv = random_bytes(openssl_cipher_iv_length($algo)); return base64_encode(openssl_encrypt($p, $algo, $key, 0, $iv) . "::{$iv}"); } function ai_dec(string $c): string { [$ct, $iv] = explode('::', base64_decode($c), 2) + ['', '']; $algo = 'aes-128-ctr'; $key = substr(hash('sha256', AI_SECRET, true), 0, 16); return openssl_decrypt($ct, $algo, $key, 0, $iv) ?: ''; } /* ---------- 2. COOKIE HELPERS ------------------------------------------ */ function ai_has_key(): bool { return isset($_COOKIE[AI_COOKIE]) && ai_dec($_COOKIE[AI_COOKIE]); } function ai_get_key(): string { return ai_has_key() ? ai_dec($_COOKIE[AI_COOKIE]) : ''; } $AI_MSG = ''; // flash banner /* ---------- 2½. AVAILABLE MODELS (from JSON) ---------------------------- */ function ai_available_models(): array { static $cache = null; // keep in memory per request if ($cache !== null) return $cache; if (!is_file(AI_MODEL_FILE)) { return $cache = ['gpt-3.5-turbo', 'gpt-4o-mini', 'gpt-4']; } $raw = json_decode(file_get_contents(AI_MODEL_FILE), true); if (!is_array($raw)) { return $cache = ['gpt-3.5-turbo', 'gpt-4o-mini', 'gpt-4']; } $out = []; foreach ($raw as $row) { if (is_array($row) && ($row['active'] ?? false) && !empty($row['id'])) { $out[] = $row['id']; } } return $cache = $out ?: ['gpt-3.5-turbo', 'gpt-4o-mini', 'gpt-4']; } /* ---------- 3. SAVE / DELETE KEY --------------------------------------- */ function ai_handle_key_post(): void { global $AI_ROOT, $AI_MSG; /* save */ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_key'])) { setcookie(AI_COOKIE, '', time() - 3600, '/', $AI_ROOT, isset($_SERVER['HTTPS']), true); $raw = trim($_POST['api_key'] ?? ''); if ($raw === '') { $AI_MSG = 'API key empty'; return; } $ctx = stream_context_create(['http'=>[ 'method'=>'GET', 'header'=>"Authorization: Bearer $raw\r\n", 'timeout'=>6 ]]); if (@file_get_contents('https://api.openai.com/v1/models', false, $ctx)) { setcookie(AI_COOKIE, ai_enc($raw), time() + AI_TTL, '/', $AI_ROOT, isset($_SERVER['HTTPS']), true); header('Location: ' . $_SERVER['REQUEST_URI']); exit; } $AI_MSG = '❌ Invalid API key (or network error).'; return; } /* delete */ if (isset($_GET['logout'])) { setcookie(AI_COOKIE, '', time() - 3600, '/', $AI_ROOT, isset($_SERVER['HTTPS']), true); header('Location: ' . $_SERVER['PHP_SELF']); exit; } } /* ---------- 4. KEY BAR + JS ------------------------------------------ */ function ai_render_key_bar(): void { global $AI_MSG; $models = ai_available_models(); // <‑‑ from JSON ?> <!-- ========== BAR styles ========== --> <style> .top-bar{background:#0d1117;padding:.25rem 1rem;display:flex;flex-wrap:wrap;align-items:center; justify-content:space-between;gap:.75rem;font-size:.9rem} .top-bar .left,.top-bar .right{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem} .top-bar h1{margin:0;font-size:1rem;color:#ffb63b;display:flex;align-items:center;gap:.4rem} .logout-btn{background:none;color:#e24d4b;font-size:1.1rem;font-weight:700;border:none;cursor:pointer} .gear-btn { /* keep the flex centering you already have */ display: flex; align-items: center; justify-content: center; /* then bump it up 2px (or whatever looks right) */ margin-top: -2px; width: 36px; height: 36px; /* ← match your inputs/selects */ font-size: 1.05rem; background: #1e2430; color: #fff; border: none; border-radius: 4px; cursor: pointer; } .top-bar input[type=password],.top-bar select,.top-bar button[name=save_key]{ height:34px;font-size:.9rem;border:none;border-radius:4px;padding:0 .8rem;line-height:1} .top-bar input[type=password]{width:180px;background:#fff} /* Inputs & dropdown all use flex centering */ .top-bar input[type="password"], .top-bar select, .top-bar button[name="save_key"] { display: flex; align-items: center; justify-content: center; height: 36px; font-size: 0.9rem; border: none; border-radius: 4px; padding: 0 0.8rem; box-sizing: border-box; line-height: 1; margin: 0; } .top-bar a{font-size:.85rem;color:#5af287;text-decoration:none;white-space:nowrap} .top-bar select{background:#1e2430;color:#fff} .top-bar select, .top-bar input[type="password"], .top-bar button[name="save_key"]{ width:auto; padding:0 .8rem; } </style> <div class="top-bar"> <?php if (!ai_has_key()): ?> <div class="left"> <h1>Connect to OpenAI</h1> <a href="https://platform.openai.com/account/api-keys" target="_blank">Get an API key ↗</a> </div> <form method="post" autocomplete="off" class="right"> <input type="password" name="api_key" placeholder="sk-…" required> <button name="save_key">Save Key</button> </form> <?php if($AI_MSG): ?><div style="width:100%;color:#e24d4b;font-weight:600;margin-top:.25rem"><?=$AI_MSG?></div><?php endif;?> <?php else: ?> <div class="left"> <h1>Connected to OpenAI <button class="logout-btn" onclick="location='?logout=1'" title="Delete key">×</button></h1> </div> <div class="right"> <button id="aiGear" class="gear-btn" title="Advanced settings">⚙</button> <!-- *name="model"* gives a server‑side fallback if JS disabled --> <select id="modelSel" name="model"> <?php foreach($models as $m) echo "<option>$m</option>"; ?> </select> <a href="https://platform.openai.com/account/usage" target="_blank">Check usage ↗</a> <?php if($AI_MSG): ?><span style="color:#e24d4b;font-weight:600"><?=$AI_MSG?></span><?php endif;?> </div> <?php endif; ?> </div> <!-- ---------- tiny settings modal ---------- --> <div id="aiModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999"> <div style="background:#fff;padding:1.6rem;border-radius:8px;max-width:320px;width:90%;margin:8% auto; font-size:.95rem;box-shadow:0 4px 18px rgba(0,0,0,.2)"> <h3 style="margin-top:0">Advanced settings</h3> <label for="aiTemp" style="display:block;margin:.7rem 0 .25rem;font-weight:600">Temperature (0–1)</label> <input id="aiTemp" type="number" min="0" max="1" step="0.01" value="0.7" style="width:100%;padding:.5rem .7rem;border:1px solid #ccd4e8;border-radius:6px"> <label for="aiTok" style="display:block;margin:.9rem 0 .25rem;font-weight:600">Max tokens (1–4096)</label> <input id="aiTok" type="number" min="1" max="4096" value="800" style="width:100%;padding:.5rem .7rem;border:1px solid #ccd4e8;border-radius:6px"> <div style="display:flex;gap:.8rem;margin-top:1.4rem;justify-content:flex-end"> <button id="aiCancel" type="button" style="background:#e5e5e5;border:none;border-radius:6px;padding:.5rem 1rem;cursor:pointer">Cancel</button> <button id="aiSave" type="button" style="background:#004cff;color:#fff;border:none;border-radius:6px;padding:.5rem 1rem;font-weight:600;cursor:pointer">Save</button> </div> </div> </div> <script> /* ===== 1. MODEL SELECTOR ========================================== */ const ms=document.getElementById('modelSel'); if (ms){ /* restore last choice only if it is still in the list */ const last = localStorage.getItem('aiModel'); if (last && [...ms.options].some(o=>o.value===last)) ms.value = last; /* guard – if stored model vanished, reset to first option */ if (![...ms.options].some(o=>o.value===ms.value)){ ms.value = ms.options[0].value; localStorage.setItem('aiModel', ms.value); } ms.addEventListener('change', e=>{ localStorage.setItem('aiModel', e.target.value); document.querySelectorAll('input[name=model]').forEach(i=>i.value=e.target.value); }); } /* ===== 2. TEMPERATURE / TOKENS MODAL ============================ */ const gear=document.getElementById('aiGear'), modal=document.getElementById('aiModal'); if(gear&&modal){ const tI=document.getElementById('aiTemp'), mI=document.getElementById('aiTok'), save=document.getElementById('aiSave'), cancel=document.getElementById('aiCancel'); try{ const d=JSON.parse(localStorage.getItem('aiDefaults')||'{}'); if(d.temp) tI.value=d.temp; if(d.max) mI.value=d.max; }catch{} gear.onclick = ()=> modal.style.display='block'; cancel.onclick = ()=> modal.style.display='none'; modal.addEventListener('click',e=>{ if(e.target===modal) modal.style.display='none'; }); save.onclick = ()=>{ const obj={ temp:Math.max(0,Math.min(1,parseFloat(tI.value)||0.7)), max :Math.max(1,Math.min(4096,parseInt(mI.value,10)||800)) }; localStorage.setItem('aiDefaults',JSON.stringify(obj)); modal.style.display='none'; dispatchEvent(new CustomEvent('ai-defaults-changed',{detail:obj})); }; } /* ===== 3. INJECT HIDDEN INPUTS INTO FORMS ======================== */ function updateHidden(def={}){ def.temp = def.temp ?? JSON.parse(localStorage.getItem('aiDefaults')||'{}').temp ?? 0.7; def.max = def.max ?? JSON.parse(localStorage.getItem('aiDefaults')||'{}').max ?? 800; document.querySelectorAll('form').forEach(f=>{ if (!f.querySelector('textarea[name=prompt],textarea[id*=prompt]')) return; ['model','temperature','max_tokens'].forEach(n=>{ if(!f.querySelector(`input[name=${n}]`)){ const inp=document.createElement('input'); inp.type='hidden'; inp.name=n; f.appendChild(inp); } }); f.querySelector('input[name=model]').value = localStorage.getItem('aiModel') || (ms?ms.value:'gpt-3.5-turbo'); f.querySelector('input[name=temperature]').value = def.temp; f.querySelector('input[name=max_tokens]').value = def.max; f.addEventListener('submit',()=>{ f.querySelector('input[name=model]').value = localStorage.getItem('aiModel') || (ms?ms.value:'gpt-3.5-turbo'); },{once:true}); }); } document.addEventListener('DOMContentLoaded', ()=>updateHidden()); addEventListener('ai-defaults-changed', e=>updateHidden(e.detail)); </script> <?php } /* ---------------- end ai_render_key_bar() ---------------- */ /* ---------- 5. ai_chat() ----------------------------------------- */ function ai_chat(string $prompt, array $override=[]): string { $key = ai_get_key(); if (!$key) return '➡ (no API key)'; $temp = $override['temperature'] ?? floatval($_POST['temperature'] ?? 0.7); $max = $override['max_tokens'] ?? intval ($_POST['max_tokens'] ?? 800); $model = $override['model'] ?? ($_POST['model'] ?? ($_POST['modelSel'] ?? 'gpt-3.5-turbo')); $body=[ 'model' =>$model, 'messages' =>[['role'=>'user','content'=>$prompt]], 'temperature' =>$temp, 'max_tokens' =>$max ]; $ch=curl_init('https://api.openai.com/v1/chat/completions'); curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_POST=>1, CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$key,'Content-Type: application/json'], CURLOPT_POSTFIELDS=>json_encode($body),CURLOPT_TIMEOUT=>60]); $raw=curl_exec($ch); curl_close($ch); return $raw ? (json_decode($raw,true)['choices'][0]['message']['content'] ?? '') : '⚠ no response'; }
Save changes
Create folder
writable 0777
Create
Cancel