Site Builder
Editing:
inidropt.php
writable 0666
<?php /***************************************************************** * OpenAI helper (v1.9) · BestDealOn · Aug‑2025 * – NEW: reads /cache/models.json to decide which models * appear in the drop‑down (global, admin‑controlled) *****************************************************************/ declare(strict_types=1); /* ---------- 0. CONFIG -------------------------------------------------- */ const AI_COOKIE = 'openai_key'; const AI_SECRET = 'openai-shared-v1'; const AI_TTL = 30 * 24 * 3600; // 30 days const MODEL_FILE = '/cache/models.json'; // site‑relative, writable $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 { $m='aes-128-ctr'; $k=substr(hash('sha256',AI_SECRET,true),0,16); $iv=random_bytes(openssl_cipher_iv_length($m)); return base64_encode(openssl_encrypt($p,$m,$k,0,$iv)."::{$iv}"); } function ai_dec(string $c): string { [$ct,$iv]=explode('::',base64_decode($c),2)+['','']; $m='aes-128-ctr'; $k=substr(hash('sha256',AI_SECRET,true),0,16); return openssl_decrypt($ct,$m,$k,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 /* ---------- 3. SAVE / DELETE KEY --------------------------------------- */ function ai_handle_key_post(): void { global $AI_ROOT,$AI_MSG; 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; } if (isset($_GET['logout'])) { setcookie(AI_COOKIE,'',time()-3600,'/',$AI_ROOT,isset($_SERVER['HTTPS']),true); header('Location: '.$_SERVER['PHP_SELF']); exit; } } /* ---------- 4. READ *GLOBAL* MODEL LIST -------------------------------- */ function ai_active_models(): array { $fallback = ['gpt-3.5-turbo','gpt-4o-mini','gpt-4']; $file = $_SERVER['DOCUMENT_ROOT'].MODEL_FILE; if (!is_file($file)) return $fallback; $json = json_decode(file_get_contents($file), true); if (!is_array($json)) return $fallback; $active = array_values(array_column( array_filter($json, fn($row)=>($row['active']??false)), 'id' )); return $active ?: $fallback; } /* ---------- 5. KEY BAR (HTML + JS) ----------------------------------- */ function ai_render_key_bar(): void { global $AI_MSG; $models = ai_active_models(); // << HERE ?> <style> /* identical styles … (truncated for brevity) */ .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{background:#1e2430;color:#fff;border:none;border-radius:4px;width:34px;height:34px;font-size:1.05rem;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} .top-bar button[name=save_key]{background:#004cff;color:#fff;font-weight:600;padding:0 1rem;cursor:pointer} .top-bar a{font-size:.85rem;color:#5af287;text-decoration:none;white-space:nowrap} .top-bar select{background:#1e2430;color:#fff} </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> <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> <!-- modal + JS identical to v1.8 (omitted for brevity) --> <script> /* ===== 1. MODEL SELECTOR ========================================== */ const ms = document.getElementById('modelSel'); if (ms){ ms.value = localStorage.getItem('aiModel') || ms.value; // restore 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 *EVERY* FORM ================= */ function updateHidden(def={}){ /* set defaults if none supplied */ 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=>{ /* ensure 3 inputs exist */ ['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; /* guard: last‑millisecond sync on submit */ 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() -------- */ /* ---------- 6. ai_chat() (NO CHANGE) ------------------------------- */ 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'] ?? '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