<?php /** * Plugin Name: Sheni Supra * Plugin URI: https://shenisupra.ge * Description: The single article engine for shenisupra.ge — daily calendar of 20 slots (shenisupra-N): 15 ♻︎ Refresh (own archive rewritten as new articles, same images, old URL 301 → new) + 5 ✦ Fresh (external & sister sources by weekday). Replaces Sheni Recycler, Supra Calendar and Republish Old Posts. * Version: 2.4.3 * Author: Sheni Network * Text Domain: shenisupra */ if (!defined('ABSPATH')) exit; /* ---- self-healing guard: if this plugin ever fatals, it deactivates itself and records the error (never takes the site down) ---- */ register_shutdown_function(function(){ $e = error_get_last(); if (!$e || !in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR], true)) return; if (strpos(str_replace('\\','/',$e['file']), '/plugins/shenisupra/') === false && stripos($e['message'], 'Sheni_Supra') === false && stripos($e['message'], 'shsup') === false) return; $msg = gmdate('c') . ' | PHP ' . PHP_VERSION . ' | mem ' . ini_get('memory_limit') . ' | ' . $e['message'] . ' in ' . $e['file'] . ':' . $e['line']; if (function_exists('update_option')) update_option('shsup_fatal', $msg, false); $me = plugin_basename(__FILE__); if (function_exists('get_option') && function_exists('update_option')) { $ap = (array) get_option('active_plugins', []); $k = array_search($me, $ap, true); if ($k !== false) { unset($ap[$k]); update_option('active_plugins', array_values($ap)); } } if (function_exists('wp_insert_post')) @wp_insert_post(['post_type' => 'post', 'post_status' => 'private', 'post_title' => 'SheniSupra fatal log', 'post_content' => $msg]); }); if (version_compare(PHP_VERSION,'7.4','<')) { add_action('admin_notices',function(){ echo '<div class="notice notice-error"><p>Sheni Supra needs PHP 7.4+ (server has '.PHP_VERSION.').</p></div>'; }); return; } define('SHSUP_VER','2.4.3'); define('SHSUP_FILE',__FILE__); define('SHSUP_PREFIX','shenisupra-'); class Sheni_Supra_Engine { private static $inst; public static function i(){ return self::$inst?:(self::$inst=new self()); } public static function t_slots(){ global $wpdb; return $wpdb->prefix.'ss_slots'; } public static function t_sources(){ global $wpdb; return $wpdb->prefix.'ss_sources'; } public static function t_redirects(){ global $wpdb; return $wpdb->prefix.'ss_redirects'; } public function __construct(){ register_activation_hook(SHSUP_FILE,[$this,'activate']); register_deactivation_hook(SHSUP_FILE,[$this,'deactivate']); add_action('init',[$this,'ensure_cron']); add_action('admin_menu',[$this,'menu']); add_action('admin_notices',function(){ if($f=get_option('shsup_fatal')){ $backup=get_option('shsup_recovery_backup_20261116',[]);$historical=is_array($backup)&&isset($backup['fatal'])&&hash_equals((string)$backup['fatal'],(string)$f); if($historical){$page=sanitize_key($_GET['page']??'');if(in_array($page,['ss-openai','ss-health','sheni-supra'],true))echo '<div class="notice notice-info"><p><b>Historical incident — not a new failure.</b> The previously recorded crash is retained below. The false crash-detection match has been corrected. Publication is still paused for the article test.</p><details><summary>Show the previous incident details</summary><pre style="white-space:pre-wrap;overflow-wrap:anywhere">'.esc_html($f).'</pre></details></div>';} else echo '<div class="notice notice-error"><p><b>New recorded Supra failure:</b> <code>'.esc_html($f).'</code></p></div>'; } if($e=get_option('shsup_activation_error')) echo '<div class="notice notice-error"><p><b>Sheni Supra:</b> activation problem — '.esc_html($e).'</p></div>'; if(get_option('shsup_notice_retire')){ require_once ABSPATH.'wp-admin/includes/plugin.php'; $on=[]; foreach(['shenisupra-calendar/shenisupra-calendar.php'=>'Sheni Supra Calendar (v1)','republish-old-posts-pro/republish-old-posts-pro.php'=>'Republish Old Posts Pro','sheni-recycler/sheni-recycler.php'=>'Sheni Recycler'] as $f=>$n) if(is_plugin_active($f)) $on[]=$n; if($on) echo '<div class="notice notice-warning is-dismissible"><p><b>Sheni Supra</b> replaces: '.esc_html(implode(', ',$on)).' — please deactivate them so only one engine publishes.</p></div>'; else delete_option('shsup_notice_retire'); } }); add_action('admin_post_ss_action',[$this,'handle_action']); add_action('ss_cron_fill',[$this,'cron_fill']); add_action('ss_cron_publish',[$this,'cron_publish']); add_filter('cron_schedules',function($s){ $s['ss_5min']=['interval'=>300,'display'=>'Every 5 min']; $s['ss_15min']=['interval'=>900,'display'=>'Every 15 min']; return $s; }); add_action('template_redirect',[$this,'redirect_old_urls'],1); add_action('rest_api_init',[$this,'rest']); add_filter('manage_posts_columns',function($c){ $c['ss_slot']='Slot'; return $c; }); add_action('manage_posts_custom_column',function($col,$id){ if($col==='ss_slot') echo esc_html(get_post_meta($id,'_ss_slot',true)); },10,2); add_filter('the_content',[$this,'network_footer']); add_filter('the_content',[$this,'image_credit_line'],9); } /* ================= setup ================= */ public function activate(){ try{ $this->activate_inner(); }catch(\Throwable $e){ update_option('shsup_activation_error',$e->getMessage()); } } private function activate_inner(){ global $wpdb; $cs=$wpdb->get_charset_collate(); require_once ABSPATH.'wp-admin/includes/upgrade.php'; dbDelta("CREATE TABLE ".self::t_slots()." ( id bigint unsigned NOT NULL AUTO_INCREMENT, slot_no bigint unsigned NOT NULL, slot_time datetime NOT NULL, category_id bigint unsigned NOT NULL DEFAULT 0, type varchar(10) NOT NULL DEFAULT 'refresh', source_id bigint unsigned NOT NULL DEFAULT 0, post_id bigint unsigned NOT NULL DEFAULT 0, origin_id bigint unsigned NOT NULL DEFAULT 0, status varchar(20) NOT NULL DEFAULT 'empty', note text NULL, updated datetime NULL, PRIMARY KEY (id), UNIQUE KEY slot_no (slot_no), KEY slot_time (slot_time), KEY status (status)) $cs;"); dbDelta("CREATE TABLE ".self::t_sources()." ( id bigint unsigned NOT NULL AUTO_INCREMENT, name varchar(120) NOT NULL, url text NOT NULL, kind varchar(12) NOT NULL DEFAULT 'auto', category_id bigint unsigned NOT NULL DEFAULT 0, days varchar(20) NOT NULL DEFAULT '1234567', lang varchar(5) NOT NULL DEFAULT 'en', active tinyint NOT NULL DEFAULT 1, last_status varchar(200) NULL, last_run datetime NULL, produced int NOT NULL DEFAULT 0, PRIMARY KEY (id)) $cs;"); dbDelta("CREATE TABLE ".self::t_redirects()." ( id bigint unsigned NOT NULL AUTO_INCREMENT, old_path varchar(255) NOT NULL, new_post_id bigint unsigned NOT NULL, old_post_id bigint unsigned NOT NULL, created datetime NULL, hits int NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE KEY old_path (old_path)) $cs;"); if(!get_option('ss_settings')) update_option('ss_settings',$this->defaults()); if(!$wpdb->get_var("SELECT COUNT(*) FROM ".self::t_sources())) $this->seed_sources(); // adopt Supra Calendar v1 slots if present $old=$wpdb->prefix.'ssc_slots'; if($wpdb->get_var("SHOW TABLES LIKE '$old'") && !$wpdb->get_var("SELECT COUNT(*) FROM ".self::t_slots())){ $wpdb->query("INSERT INTO ".self::t_slots()." (slot_no,slot_time,category_id,type,post_id,status,note,updated) SELECT slot_no,slot_time,category_id,IF(source='sister','fresh','refresh'),post_id,status,note,updated FROM $old"); } $this->ensure_cron(); update_option('shsup_notice_retire',1); // Preserve the recorded failure for diagnosis. // Existing public bylines are preserved during activation. } public function distribute_bylines($force=false){ global $wpdb; if(!$force&&get_option('ss_bylines_done')) return 0; $ids=get_users(['role__in'=>['author','editor','administrator'],'fields'=>'ID','orderby'=>'ID','order'=>'ASC','number'=>50]); $ids=array_values(array_filter(array_map('intval',$ids),function($id){ $u=get_userdata($id); return $u && $u->first_name!==''; })); if(count($ids)<2) return 0; $n=count($ids); $case='CASE (ID % '.$n.')'; foreach($ids as $k=>$id) $case.=" WHEN $k THEN $id"; $case.=' END'; $r=$wpdb->query("UPDATE {$wpdb->posts} SET post_author = $case WHERE post_type='post' AND post_status IN ('publish','future','draft','private')"); update_option('ss_bylines_done',gmdate('Y-m-d H:i:s'),false); wp_cache_flush(); do_action('litespeed_purge_all'); return (int)$r; } public function deactivate(){ wp_clear_scheduled_hook('ss_cron_fill'); wp_clear_scheduled_hook('ss_cron_publish'); } public function ensure_cron(){ if(!wp_next_scheduled('ss_cron_fill')) wp_schedule_event(time()+60,'ss_15min','ss_cron_fill'); if(!wp_next_scheduled('ss_cron_publish')) wp_schedule_event(time()+120,'ss_5min','ss_cron_publish'); } public function defaults(){ return [ 'enabled'=>1,'daily_target'=>20,'fresh_per_day'=>5,'days_ahead'=>14,'window_start'=>'07:00','window_end'=>'23:00','timezone'=>'Asia/Tbilisi', 'lookahead_hours'=>24,'cat_min'=>"9=6",'cooldown_days'=>180,'min_age_days'=>30,'thin_cat_threshold'=>50,'cat_weights'=>'','exclude_cats'=>'1', 'claude_key'=>'','claude_model'=>'claude-sonnet-4-5','byline_user'=>0,'network_links'=>1, ]; } public function s($k=null){ $s=wp_parse_args(get_option('ss_settings',[]),$this->defaults()); return $k===null?$s:($s[$k]??null); } public function tz(){ try{ return new DateTimeZone($this->s('timezone')); }catch(Exception $e){ return wp_timezone(); } } private function seed_sources(){ global $wpdb; $t=self::t_sources(); $rows=[ // name, url, kind, cat, days(1=Mon..7=Sun), lang ['Georgian Wine Association','https://gwa.ge/feed','rss',8,'1','ka'], ['Decanter','https://www.decanter.com/feed','rss',8,'1','en'], ['Vinoge','https://vinoge.com/feed','rss',8,'1','ka'], ['bm.ge economy (food business)','https://bm.ge/feed','rss',5,'2','ka'], ['Georgia Today','https://georgiatoday.ge/feed','rss',5,'2','en'], ['Eater','https://www.eater.com/rss/index.xml','rss',5,'2','en'], ['Restaurant Business','https://www.restaurantbusinessonline.com/rss.xml','rss',1482,'2','en'], ['Wikipedia ka — იმერული სამზარეულო','იმერული სამზარეულო კერძები','wikipedia',1469,'3','ka'], ['Wikipedia ka — მეგრული სამზარეულო','მეგრული სამზარეულო','wikipedia',1470,'3','ka'], ['Wikipedia ka — კახური სამზარეულო','კახური კერძები','wikipedia',1475,'3','ka'], ['Wikipedia ka — აჭარული სამზარეულო','აჭარული სამზარეულო','wikipedia',1476,'3','ka'], ['Wikipedia ka — სვანური სამზარეულო','სვანური კერძები','wikipedia',1474,'3','ka'], ['Wikipedia ka — რაჭული სამზარეულო','რაჭული კერძები','wikipedia',1473,'3','ka'], ['Wikipedia ka — თუშური სამზარეულო','თუშური კერძები','wikipedia',1471,'3','ka'], ['Wikipedia ka — მესხური სამზარეულო','მესხური სამზარეულო','wikipedia',1472,'3','ka'], ['Wikipedia ka — გურული სამზარეულო','გურული კერძები','wikipedia',1477,'3','ka'], ['Wikipedia — Armenian cuisine','Armenian cuisine dishes','wikipedia',1479,'3','en'], ['Wikipedia — Azerbaijani cuisine','Azerbaijani cuisine dishes','wikipedia',1480,'3','en'], ['Sheni Interieri','https://sheniinterieri.ge','wp',1468,'4','ka'], ['ArchDaily','https://www.archdaily.com/feed','rss',1468,'4','en'], ['Houzz kitchens','https://www.houzz.com/magazine/kitchens','rss',11,'4','en'], ['Sheni Ekimi','https://sheniekimi.ge','wp',12,'5','ka'], ['Harvard Nutrition Source','https://nutritionsource.hsph.harvard.edu/feed','rss',12,'5','en'], ['BBC Good Food','https://www.bbcgoodfood.com/feed','rss',12,'5','en'], ['Serious Eats','https://feeds.feedburner.com/seriouseatsfeaturesvideos','rss',559,'67','en'], ['Guardian Food','https://www.theguardian.com/food/rss','rss',559,'67','en'], ['Food & Wine','https://www.foodandwine.com/rss','rss',7,'67','en'], ['Sheni Silamaze','https://shenisilamaze.ge','wp',12,'67','ka'], ]; foreach($rows as $r) $wpdb->insert($t,['name'=>$r[0],'url'=>$r[1],'kind'=>$r[2],'category_id'=>$r[3],'days'=>$r[4],'lang'=>$r[5],'active'=>1]); } /* ================= categories ================= */ public function category_weights(){ $excl=array_filter(array_map('intval',preg_split('/[\s,]+/',$this->s('exclude_cats')))); $custom=[]; foreach(preg_split('/\r?\n/',$this->s('cat_weights')) as $l) if(preg_match('/^\s*(\d+)\s*=\s*([\d.]+)/',$l,$m)) $custom[(int)$m[1]]=(float)$m[2]; $w=[]; foreach(get_categories(['hide_empty'=>false]) as $c){ if(in_array($c->term_id,$excl)) continue; if(isset($custom[$c->term_id])){ if($custom[$c->term_id]>0) $w[$c->term_id]=$custom[$c->term_id]; continue; } if($c->count>0) $w[$c->term_id]=max(1.0,sqrt($c->count)); } return $w; } private function pick_weighted($w){ $t=array_sum($w); $r=mt_rand()/mt_getrandmax()*$t; foreach($w as $k=>$v){ $r-=$v; if($r<=0) return $k; } $k=array_keys($w); return end($k); } private function day_sequence($weights,$n){ arsort($weights); $tot=array_sum($weights); $seq=[]; foreach($weights as $id=>$w){ for($k=0,$q=(int)round($n*$w/$tot);$k<$q;$k++) $seq[]=$id; } $d=array_keys($weights); for($i=0;count($seq)<$n;$i++) $seq[]=$d[$i%count($d)]; $seq=array_slice($seq,0,$n); foreach(array_slice($d,0,$n) as $id) if(!in_array($id,$seq)) $seq[count($seq)-1]=$id; shuffle($seq); return $seq; } /* ================= calendar generation ================= */ private function to_utc($local){ $d=new DateTime($local,$this->tz()); $d->setTimezone(new DateTimeZone('UTC')); return $d->format('Y-m-d H:i:s'); } private function to_local($utc){ return (new DateTime($utc,new DateTimeZone('UTC')))->setTimezone($this->tz()); } private function slot_times($day,$n){ [$sh,$sm]=array_map('intval',explode(':',$this->s('window_start'))); [$eh,$em]=array_map('intval',explode(':',$this->s('window_end'))); $st=(clone $day)->setTime($sh,$sm)->getTimestamp(); $en=(clone $day)->setTime($eh,$em)->getTimestamp(); $step=max(600,$en-$st)/max(1,$n); $out=[]; for($i=0;$i<$n;$i++){ $ts=$st+(int)($step*$i)+mt_rand(-(int)($step*0.2),(int)($step*0.2)); $out[]=$ts-$ts%60; } sort($out); return $out; } public function generate($days=null){ global $wpdb; $t=self::t_slots(); $n=(int)$this->s('daily_target'); $fresh=min($n,(int)$this->s('fresh_per_day')); $days=$days?:(int)$this->s('days_ahead'); $w=$this->category_weights(); if(!$w) return 0; $created=0; $today=(new DateTime('now',$this->tz()))->setTime(0,0); $no=(int)$wpdb->get_var("SELECT MAX(slot_no) FROM $t")+1; for($d=0;$d<$days;$d++){ $day=(clone $today)->modify("+$d day"); $a=$this->to_utc($day->format('Y-m-d 00:00:00')); $b=$this->to_utc($day->format('Y-m-d 23:59:59')); $have=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $t WHERE slot_time BETWEEN %s AND %s",$a,$b)); if($have>=$n) continue; $seq=$this->day_sequence($w,$n); $seq=$this->apply_cat_min($seq,$n); $times=$this->slot_times($day,$n); $need=$n-$have; // fresh slots spread evenly through the day, category from that weekday's sources $fresh_idx=[]; for($i=0;$i<$fresh;$i++) $fresh_idx[]=(int)floor(($i+0.5)*$n/$fresh); $dow=(int)$day->format('N'); $fresh_cats=$this->fresh_categories_for_day($dow); foreach($times as $i=>$ts){ if($need<=0) break; if($ts<time()-900) continue; $is_fresh=in_array($i,$fresh_idx); $cat=$is_fresh&&$fresh_cats?$fresh_cats[$i%count($fresh_cats)]:$seq[$i]; $wpdb->insert($t,['slot_no'=>$no,'slot_time'=>gmdate('Y-m-d H:i:s',$ts),'category_id'=>$cat,'type'=>$is_fresh?'fresh':'refresh','status'=>'empty','updated'=>gmdate('Y-m-d H:i:s')]); $no++; $created++; $need--; } } return $created; } private function apply_cat_min($seq,$n){ $mins=[]; foreach(preg_split('/\r?\n/',(string)$this->s('cat_min')) as $l) if(preg_match('/^\s*(\d+)\s*=\s*(\d+)/',$l,$m)) $mins[(int)$m[1]]=(int)$m[2]; foreach($mins as $cat=>$min){ $have=count(array_keys($seq,$cat)); if($have>=$min) continue; $need=$min-$have; $counts=array_count_values($seq); for($k=0;$k<count($seq)&&$need>0;$k++){ $i=(int)floor($k*count($seq)/max(1,$min)); $i=min($i,count($seq)-1); if($seq[$i]==$cat) continue; if(($counts[$seq[$i]]??0)<=1) continue; $counts[$seq[$i]]--; $seq[$i]=$cat; $need--; } for($i=0;$i<count($seq)&&$need>0;$i++){ if($seq[$i]==$cat) continue; if(($counts[$seq[$i]]??0)<=1) continue; $counts[$seq[$i]]--; $seq[$i]=$cat; $need--; } } return $seq; } private function fresh_categories_for_day($dow){ global $wpdb; $rows=$wpdb->get_results($wpdb->prepare("SELECT DISTINCT category_id FROM ".self::t_sources()." WHERE active=1 AND days LIKE %s",'%'.$dow.'%')); $cats=array_map(function($r){ return (int)$r->category_id; },$rows); // thin categories first $th=(int)$this->s('thin_cat_threshold'); usort($cats,function($x,$y)use($th){ $cx=get_category($x); $cy=get_category($y); return (($cx&&$cx->count<$th)?0:1)<=>(($cy&&$cy->count<$th)?0:1); }); return $cats; } /* ================= filling ================= */ public function cron_fill(){ if(!$this->s('enabled')) return; $this->generate(); global $wpdb; $t=self::t_slots(); $until=gmdate('Y-m-d H:i:s',time()+3600*(int)$this->s('lookahead_hours')); foreach($wpdb->get_results($wpdb->prepare("SELECT * FROM $t WHERE status='empty' AND slot_time<=%s ORDER BY slot_time ASC LIMIT 6",$until)) as $s){ try { $this->fill_slot($s); } catch(\Throwable $e){ $this->upd($s->id,['note'=>'error: '.mb_substr($e->getMessage(),0,150)]); update_option('ss_last_error',$e->getMessage()); } } } public function fill_slot($slot){ $r=$this->fill_draft($slot); if($r) return $r; // free: existing drafts (Recycler leftovers) go first $r=$slot->type==='fresh'?$this->fill_fresh($slot):$this->fill_refresh($slot); if($r) return $r; $r=$slot->type==='fresh'?$this->fill_refresh($slot):false; if($r) return $r; // fresh fallback → refresh so the day still hits 20 $this->upd($slot->id,['note'=>'nothing available '.gmdate('H:i')]); return false; } private function upd($id,$d){ global $wpdb; $d['updated']=gmdate('Y-m-d H:i:s'); $wpdb->update(self::t_slots(),$d,['id'=>$id]); } private function label($slot){ return SHSUP_PREFIX.$slot->slot_no; } private function schedule($pid,$slot){ wp_update_post(['ID'=>$pid,'post_status'=>'future','post_date'=>get_date_from_gmt($slot->slot_time),'post_date_gmt'=>$slot->slot_time,'edit_date'=>true]); update_post_meta($pid,'_ss_slot',$this->label($slot)); update_post_meta($pid,'_ss_slot_id',$slot->id); } private function author(){ if($fixed=(int)$this->s('byline_user')) return $fixed; $ids=get_users(['role__in'=>['author','editor','administrator'],'fields'=>'ID','orderby'=>'ID','order'=>'ASC','number'=>50]); $ids=array_values(array_filter(array_map('intval',$ids),function($id){ $u=get_userdata($id); return $u && $u->first_name!==''; })); if(!$ids) return get_current_user_id()?:1; $i=(int)get_option('ss_author_rr',0); update_option('ss_author_rr',$i+1,false); return $ids[$i%count($ids)]; } private function fill_draft($slot){ $base=['post_type'=>'post','post_status'=>'draft','posts_per_page'=>1,'orderby'=>'date','order'=>'ASC','fields'=>'ids','meta_query'=>[['key'=>'_ss_slot','compare'=>'NOT EXISTS']]]; $q=new WP_Query($base+['cat'=>$slot->category_id]); if(!$q->posts) $q=new WP_Query($base); if(!$q->posts) return false; $pid=$q->posts[0]; if(!has_term($slot->category_id,'category',$pid)) wp_set_post_categories($pid,[$slot->category_id],true); $this->schedule($pid,$slot); $this->upd($slot->id,['post_id'=>$pid,'status'=>'scheduled','note'=>'existing draft']); return $pid; } /* ---- ♻︎ Refresh: archive post → new article, same images, old URL 301 → new ---- */ private function fill_refresh($slot){ $key=$this->claude_key(); if(!$key){ $this->upd($slot->id,['note'=>'no OpenAI key']); return false; } $cool=(int)$this->s('cooldown_days'); $age=(int)$this->s('min_age_days'); $args=['post_type'=>'post','post_status'=>'publish','posts_per_page'=>1,'fields'=>'ids','orderby'=>'date','order'=>'ASC','cat'=>$slot->category_id, 'date_query'=>[['before'=>"-$age days"]], 'meta_query'=>['relation'=>'AND', ['relation'=>'OR',['key'=>'_ss_refreshed_at','compare'=>'NOT EXISTS'],['key'=>'_ss_refreshed_at','value'=>gmdate('Y-m-d H:i:s',time()-86400*$cool),'compare'=>'<','type'=>'DATETIME']], ['key'=>'_ss_reserved','compare'=>'NOT EXISTS'],['key'=>'_ss_replaced_by','compare'=>'NOT EXISTS']]]; $q=new WP_Query($args); if(!$q->posts){ unset($args['cat']); $q=new WP_Query($args); } if(!$q->posts) return false; $old=get_post($q->posts[0]); update_post_meta($old->ID,'_ss_reserved',$slot->id); // separate images from text $imgs=[]; $text=preg_replace_callback('/<figure\b[^>]*>.*?<\/figure>|<img\b[^>]*>/is',function($m)use(&$imgs){ $imgs[]=$m[0]; return '[[IMG'.count($imgs).']]'; },$old->post_content); $plain=wp_strip_all_tags(strip_shortcodes($text)); $plain=preg_replace('/\n{3,}/',"\n\n",$plain); $is_news=false; foreach(wp_get_post_categories($old->ID) as $c){ $t=get_category($c); if($t&&(mb_stripos($t->name,'სიახლე')!==false||mb_stripos($t->name,'ამბებ')!==false)) $is_news=true; } $out=$this->claude_json($key,$this->prompt_refresh($old->post_title,mb_substr($plain,0,11000),count($imgs),$is_news)); if(!$out){ delete_post_meta($old->ID,'_ss_reserved'); $this->upd($slot->id,['note'=>'Claude failed on #'.$old->ID]); return false; } $html=wp_kses_post($out['html']); foreach($imgs as $i=>$tag) $html=str_replace('[[IMG'.($i+1).']]',$tag,$html); $html=preg_replace('/\[\[IMG\d+\]\]/','',$html); $pid=wp_insert_post(['post_type'=>'post','post_status'=>'draft','post_title'=>$out['title'],'post_content'=>$html,'post_excerpt'=>$out['excerpt'], 'post_author'=>$this->author(),'post_category'=>wp_get_post_categories($old->ID),'tags_input'=>wp_get_post_tags($old->ID,['fields'=>'names'])]); if(!$pid||is_wp_error($pid)){ delete_post_meta($old->ID,'_ss_reserved'); return false; } if(!empty($out['image_query'])) update_post_meta($pid,'_ss_image_query',sanitize_text_field($out['image_query'])); if($th=get_post_thumbnail_id($old->ID)) set_post_thumbnail($pid,$th); else $this->ensure_image($pid); update_post_meta($pid,'_ss_refreshed_from',$old->ID); update_post_meta($pid,'_ss_type','refresh'); update_post_meta($old->ID,'_ss_replaced_by',$pid); update_post_meta($old->ID,'_ss_refreshed_at',gmdate('Y-m-d H:i:s')); delete_post_meta($old->ID,'_ss_reserved'); $this->schedule($pid,$slot); $this->upd($slot->id,['post_id'=>$pid,'origin_id'=>$old->ID,'status'=>'scheduled','note'=>'refresh of #'.$old->ID]); return $pid; } private function prompt_refresh($title,$text,$nimg,$is_news=false){ $year=date('Y'); $news=$is_news?" ეს არის სიახლეების კატეგორიის ძველი სტატია: არ წარმოადგინო როგორც ახალი ამბავი და არ შეცვალო ფაქტები/თარიღები — გადააკეთე განახლებულ განმარტებით სტატიად (რა მოხდა, რატომ არის მნიშვნელოვანი, რა ვიცით დღეს, პრაქტიკული დასკვნა მკითხველისთვის), ძველი მოვლენის თარიღი ტექსტში მიუთითე.":''; return "შენ ხარ shenisupra.ge-ს (ქართული კულინარიული საიტი: რეცეპტები, ჯანსაღი კვება, ქართული სამზარეულო, სასმელები, რესტორნები) მთავარი რედაქტორი. ქვემოთ არის ჩვენი ძველი სტატია. დაწერე მის საფუძველზე სრულიად ახალი სტატია $year წლისთვის: ახალი, უფრო მიმზიდველი სათაური (50–70 სიმბოლო, არ გაიმეორო ძველი), ახლებურად აგებული სტრუქტურა (შესავალი, 3–6 <h2> სექცია, სადაც საჭიროა <ul>/<ol> ნაბიჯები ან ინგრედიენტები, ბოლოს <h2>ხშირად დასმული კითხვები</h2> 3 კითხვა-პასუხით), განახლებული და გამდიდრებული ინფორმაცია, პრაქტიკული რჩევები. არ გადმოწერო წინადადებები ძველი ტექსტიდან — ყველაფერი ხელახლა ჩამოაყალიბე ისე, რომ ტექსტი ორიგინალურად ჩაითვალოს. ტექსტში არის $nimg სურათის ადგილი ნიშნებით [[IMG1]]…[[IMG$nimg]] — ყველა ეს ნიშანი აუცილებლად ჩასვი ახალ ტექსტში შესაბამის ადგილას, ცალკე ხაზზე, ისევე დანომრილი. მოცულობა: ძველის მსგავსი ან ოდნავ მეტი (მინ. 600 სიტყვა თუ ძველი ამდენია).$news\n\nუპასუხე მხოლოდ JSON-ით, სხვა ტექსტის გარეშე: {\"title\":\"...\",\"excerpt\":\"...(1–2 წინადადება)\",\"html\":\"...(სრული HTML: <p>,<h2>,<h3>,<ul>,<ol>,<li>,<strong>)\",\"image_query\":\"2-4 English words for a stock photo search\"}\n\nძველი სათაური: $title\n\nძველი ტექსტი:\n$text"; } /* ---- ✦ Fresh: external / sister sources ---- */ private function fill_fresh($slot){ $key=$this->claude_key(); if(!$key){ $this->upd($slot->id,['note'=>'no OpenAI key']); return false; } global $wpdb; $dow=(int)$this->to_local($slot->slot_time)->format('N'); $srcs=$wpdb->get_results($wpdb->prepare("SELECT * FROM ".self::t_sources()." WHERE active=1 AND days LIKE %s ORDER BY (category_id=%d) DESC, last_run ASC",'%'.$dow.'%',$slot->category_id)); if(!$srcs) $srcs=$wpdb->get_results("SELECT * FROM ".self::t_sources()." WHERE active=1 ORDER BY last_run ASC"); $seen=get_option('ss_seen',[]); foreach($srcs as $src){ $wpdb->update(self::t_sources(),['last_run'=>gmdate('Y-m-d H:i:s')],['id'=>$src->id]); try { $items=$this->fetch_source($src); } catch(\Throwable $e){ $items='error: '.$e->getMessage(); } if(is_string($items)){ $wpdb->update(self::t_sources(),['last_status'=>mb_substr($items,0,190)],['id'=>$src->id]); continue; } $wpdb->update(self::t_sources(),['last_status'=>'ok, '.count($items).' items'],['id'=>$src->id]); foreach($items as $it){ $k=md5($it['link']); if(isset($seen[$k])) continue; $seen[$k]=time(); update_option('ss_seen',array_slice($seen,-5000,null,true)); if(mb_strlen($it['text'])<350) continue; $out=$this->claude_json($key,$this->prompt_fresh($it['title'],mb_substr($it['text'],0,10000),$it['link'],$src->lang)); if(!$out) continue; $cat=$src->category_id?:$slot->category_id; $pid=wp_insert_post(['post_type'=>'post','post_status'=>'draft','post_title'=>$out['title'],'post_content'=>wp_kses_post($out['html']),'post_excerpt'=>$out['excerpt'],'post_author'=>$this->author(),'post_category'=>[$cat]]); if(!$pid||is_wp_error($pid)) continue; update_post_meta($pid,'_ss_source_url',$it['link']); update_post_meta($pid,'_ss_source',$src->name); update_post_meta($pid,'_ss_type','fresh'); if(!empty($out['tags'])&&is_array($out['tags'])) wp_set_post_tags($pid,array_map('sanitize_text_field',$out['tags'])); update_post_meta($pid,'_ss_image_query',sanitize_text_field($out['image_query']??$it['title'])); if($it['image']) $this->sideload($pid,$it['image'],$out['title']); if(!has_post_thumbnail($pid)) $this->ensure_image($pid); if($cat!=$slot->category_id) $this->upd($slot->id,['category_id'=>$cat]); $this->schedule($pid,$slot); $wpdb->query($wpdb->prepare("UPDATE ".self::t_sources()." SET produced=produced+1 WHERE id=%d",$src->id)); $this->upd($slot->id,['post_id'=>$pid,'source_id'=>$src->id,'status'=>'scheduled','note'=>'from '.$src->name]); return $pid; } } return false; } private function prompt_fresh($title,$text,$link,$lang){ $tr=$lang==='ka'?'':' ტექსტი შეიძლება იყოს ინგლისურად — თარგმნა კი არა, ქართველი მკითხველისთვის ადაპტირებული ახალი სტატია დაწერე (ადგილობრივი კონტექსტი, ქართული ინგრედიენტები/ანალოგები, მეტრული ერთეულები).'; return "შენ ხარ shenisupra.ge-ს (ქართული კულინარიული საიტი) რედაქტორი. მოცემული წყაროს საფუძველზე დაწერე სრულიად ორიგინალური ქართული სტატია: SEO სათაური 50–70 სიმბოლო, შესავალი, 3–6 <h2> სექცია, სია სადაც საჭიროა, პრაქტიკული რჩევები, ბოლოს <h2>ხშირად დასმული კითხვები</h2> (3). არ გადმოწერო ფრაზები, გადმოსცი აზრი შენი სიტყვებით.$tr ტექსტის ბოლოს დაამატე: <p><em>წყარო: <a href=\"$link\" rel=\"nofollow noopener\" target=\"_blank\">$link</a></em></p>. მინ. 500 სიტყვა.\n\nუპასუხე მხოლოდ JSON-ით: {\"title\":\"...\",\"excerpt\":\"...\",\"html\":\"...\",\"tags\":[\"3-5 ქართული თეგი\"],\"image_query\":\"2-4 English words for a stock photo search\"}\n\nწყაროს სათაური: $title\n\nწყაროს ტექსტი:\n$text"; } private function fetch_source($src){ $kind=$src->kind; $url=trim($src->url); if($kind==='auto') $kind=preg_match('/\/feed\/?$|\.xml$|rss/i',$url)?'rss':(preg_match('/^https?:/',$url)?'wp':'wikipedia'); if($kind==='wikipedia'){ $host=$src->lang==='ka'?'ka.wikipedia.org':'en.wikipedia.org'; $r=wp_remote_get("https://$host/w/api.php?action=query&list=search&srlimit=12&format=json&srsearch=".rawurlencode($url),['timeout'=>20,'user-agent'=>'SheniSupra/2.0 (shenisupra.ge)']); if(is_wp_error($r)) return 'wiki: '.$r->get_error_message(); $j=json_decode(wp_remote_retrieve_body($r),true); $out=[]; foreach((is_array($j)?($j['query']['search']??[]):[]) as $p){ $t=$p['title']; $e=wp_remote_get("https://$host/w/api.php?action=query&prop=extracts|pageimages&explaintext=1&piprop=original&format=json&titles=".rawurlencode($t),['timeout'=>20,'user-agent'=>'SheniSupra/2.0']); if(is_wp_error($e)) continue; $pg=json_decode(wp_remote_retrieve_body($e),true); if(empty($pg['query']['pages'])||!is_array($pg['query']['pages'])) continue; $pg=reset($pg['query']['pages']); if(empty($pg['extract'])) continue; $out[]=['title'=>$t,'link'=>"https://$host/wiki/".rawurlencode(str_replace(' ','_',$t)),'text'=>$pg['extract'],'image'=>$pg['original']['source']??'']; } return $out?:'wiki: no pages'; } if($kind==='wp'){ $base=rtrim($url,'/'); $r=wp_remote_get("$base/wp-json/wp/v2/posts?per_page=10&_embed=1&_fields=id,link,title,content,_links,_embedded",['timeout'=>25]); if(is_wp_error($r)) return 'wp: '.$r->get_error_message(); if(wp_remote_retrieve_response_code($r)!=200) return 'wp: HTTP '.wp_remote_retrieve_response_code($r); $out=[]; foreach((array)json_decode(wp_remote_retrieve_body($r),true) as $p) if(is_array($p)&&isset($p['link'])) $out[]=['title'=>wp_strip_all_tags($p['title']['rendered']??''),'link'=>$p['link'],'text'=>wp_strip_all_tags($p['content']['rendered']??''),'image'=>$p['_embedded']['wp:featuredmedia'][0]['source_url']??'']; return $out?:'wp: empty'; } // rss include_once ABSPATH.WPINC.'/feed.php'; add_filter('wp_feed_cache_transient_lifetime',function(){ return 1800; }); $f=fetch_feed($url); if(is_wp_error($f)) return 'rss: '.$f->get_error_message(); $out=[]; foreach($f->get_items(0,12) as $it){ $img=''; if($enc=$it->get_enclosure()) $img=$enc->get_thumbnail()?:$enc->get_link(); $txt=wp_strip_all_tags($it->get_content()?:$it->get_description()); $link=$it->get_permalink(); if(mb_strlen($txt)<800){ $full=$this->fetch_article($link); if($full){ $txt=$full['text']; if(!$img) $img=$full['image']; } } if(!$img&&preg_match('/<img[^>]+src="([^"]+)"/i',$it->get_content()?:'',$m)) $img=$m[1]; $out[]=['title'=>wp_strip_all_tags($it->get_title()),'link'=>$link,'text'=>$txt,'image'=>$img]; } return $out?:'rss: no items'; } private function fetch_article($url){ // lightweight readability $r=wp_remote_get($url,['timeout'=>20,'user-agent'=>'Mozilla/5.0 (compatible; SheniSupra/2.0; +https://shenisupra.ge)']); if(is_wp_error($r)||wp_remote_retrieve_response_code($r)!=200) return false; $h=wp_remote_retrieve_body($r); $img=''; if(preg_match('/<meta[^>]+property="og:image"[^>]+content="([^"]+)"/i',$h,$m)||preg_match('/<meta[^>]+content="([^"]+)"[^>]+property="og:image"/i',$h,$m)) $img=$m[1]; $h=preg_replace('/<(script|style|nav|header|footer|aside|form)\b.*?<\/\1>/is','',$h); if(preg_match('/<article\b.*?<\/article>/is',$h,$m)) $h=$m[0]; elseif(preg_match('/<main\b.*?<\/main>/is',$h,$m)) $h=$m[0]; preg_match_all('/<p\b[^>]*>(.*?)<\/p>/is',$h,$ps); $txt=trim(implode("\n\n",array_map('wp_strip_all_tags',$ps[1]))); return $txt?['text'=>html_entity_decode($txt),'image'=>$img]:false; } /* ---- images: Openverse (CC-licensed, commercial use) ---- */ public function openverse_search($q,$n=12){ $r=wp_remote_get('https://api.openverse.org/v1/images/?page_size='.(int)$n.'&license_type=commercial&mature=false&q='.rawurlencode($q),['timeout'=>20,'user-agent'=>'SheniSupra/2.1 (shenisupra.ge)']); if(is_wp_error($r)) return []; $j=json_decode(wp_remote_retrieve_body($r),true); $out=[]; foreach($j['results']??[] as $im){ if(empty($im['url'])) continue; $out[]=['url'=>$im['url'],'thumb'=>$im['thumbnail']??$im['url'],'title'=>$im['title']??'','creator'=>$im['creator']??'','license'=>strtoupper(($im['license']??'').' '.($im['license_version']??'')),'source'=>$im['foreign_landing_url']??'','w'=>$im['width']??0,'h'=>$im['height']??0]; } usort($out,function($a,$b){ return ($b['w']>=800)-($a['w']>=800); }); return $out; } public function sideload($pid,$url,$title='',$credit=null){ require_once ABSPATH.'wp-admin/includes/media.php'; require_once ABSPATH.'wp-admin/includes/file.php'; require_once ABSPATH.'wp-admin/includes/image.php'; $tmp=download_url($url,60); if(is_wp_error($tmp)){ update_option('ss_last_error','image download: '.$tmp->get_error_message()); return false; } $mime=wp_get_image_mime($tmp); $ext=['image/jpeg'=>'jpg','image/png'=>'png','image/webp'=>'webp','image/gif'=>'gif'][$mime]??''; if(!$ext){ @unlink($tmp); update_option('ss_last_error','image: not an image ('.$mime.')'); return false; } $name=sanitize_title(mb_substr($title?:get_the_title($pid),0,60))?:'image'; $file=['name'=>$name.'-'.wp_rand(100,999).'.'.$ext,'tmp_name'=>$tmp,'type'=>$mime]; $aid=media_handle_sideload($file,$pid,$title?:get_the_title($pid)); if(is_wp_error($aid)){ @unlink($tmp); update_option('ss_last_error','image: '.$aid->get_error_message()); return false; } set_post_thumbnail($pid,$aid); update_post_meta($aid,'_wp_attachment_image_alt',$title?:get_the_title($pid)); if($credit){ update_post_meta($pid,'_ss_image_credit',$credit); update_post_meta($aid,'_ss_image_credit',$credit); } else delete_post_meta($pid,'_ss_image_credit'); return $aid; } public function ensure_image($pid){ if(has_post_thumbnail($pid)) return true; $q=get_post_meta($pid,'_ss_image_query',true)?:get_the_title($pid); foreach($this->openverse_search($q,6) as $im){ if($this->sideload($pid,$im['url'],get_the_title($pid),$this->credit($im))) return true; } return false; } private function credit($im){ return trim(($im['creator']?$im['creator']:'Openverse').' · '.$im['license'].($im['source']?' · '.$im['source']:'')); } public function image_credit_line($c){ if(is_admin()||!is_singular('post')||!in_the_loop()||!is_main_query()) return $c; $cr=get_post_meta(get_the_ID(),'_ss_image_credit',true); if(!$cr) return $c; $parts=explode(' · ',$cr); $src=end($parts); $txt=esc_html($parts[0].(isset($parts[1])?' · '.$parts[1]:'')); return $c.'<p class="ss-photo-credit"><small>ფოტო: '.(filter_var($src,FILTER_VALIDATE_URL)?'<a href="'.esc_url($src).'" rel="nofollow noopener" target="_blank">'.$txt.'</a>':$txt).'</small></p>'; } /* ---- Claude ---- */ private function claude_key(){ return Sheni_Supra_OpenAI::key(); } public function claude_call($prompt,$max=6000,$key=null){ $text=Sheni_Supra_OpenAI::request($prompt,$max); if(is_wp_error($text)){update_option('ss_last_error',$text->get_error_message(),false);return false;} $j=json_decode(trim(preg_replace('/^```(?:json)?|```$/m','',trim($text))),true); if(!is_array($j)){update_option('ss_last_error','OpenAI returned invalid JSON; draft retained',false);return false;}return $j; } private function claude_json($key,$prompt){ $j=$this->claude_call($prompt,12000,$key); if(!$j||empty($j['title'])||empty($j['html'])){ if($j) update_option('ss_last_error','JSON missing title/html'); return false; } $j['title']=sanitize_text_field($j['title']); $j['excerpt']=sanitize_text_field($j['excerpt']??''); return $j; } public function claude_key_public(){ return $this->claude_key(); } /* ================= publishing at slot time ================= */ public function cron_publish(){ if(!$this->s('enabled')) return; global $wpdb; $t=self::t_slots(); $now=gmdate('Y-m-d H:i:s'); foreach($wpdb->get_results($wpdb->prepare("SELECT * FROM $t WHERE status='scheduled' AND slot_time<=%s LIMIT 20",$now)) as $slot){ $p=get_post($slot->post_id); if(!$p){ $this->upd($slot->id,['status'=>'empty','post_id'=>0,'note'=>'post gone']); continue; } if(!has_post_thumbnail($p->ID)) $this->ensure_image($p->ID); if($p->post_status==='future') wp_publish_post($p->ID); $p=get_post($p->ID); if($p->post_status!=='publish') continue; if($slot->origin_id) $this->retire_old($slot->origin_id,$p->ID); $this->upd($slot->id,['status'=>'published']); do_action('ss_post_published',$p->ID,$slot); } $wpdb->query($wpdb->prepare("UPDATE $t SET status='missed',updated=%s WHERE status='empty' AND slot_time<%s",$now,gmdate('Y-m-d H:i:s',time()-3600))); } private function retire_old($old_id,$new_id){ global $wpdb; $old=get_post($old_id); if(!$old||$old->post_status!=='publish') return; $path=wp_parse_url(get_permalink($old),PHP_URL_PATH); $path='/'.trim($path,'/').'/'; $wpdb->replace(self::t_redirects(),['old_path'=>$path,'new_post_id'=>$new_id,'old_post_id'=>$old_id,'created'=>gmdate('Y-m-d H:i:s')]); wp_update_post(['ID'=>$old_id,'post_status'=>'private']); // gone from site/feeds/sitemap, kept for history } public function redirect_old_urls(){ if(!is_404()) return; global $wpdb; $path='/'.trim(wp_parse_url($_SERVER['REQUEST_URI']??'',PHP_URL_PATH),'/').'/'; $row=$wpdb->get_row($wpdb->prepare("SELECT * FROM ".self::t_redirects()." WHERE old_path=%s",$path)); if(!$row) return; $to=get_permalink($row->new_post_id); if(!$to) return; $wpdb->query($wpdb->prepare("UPDATE ".self::t_redirects()." SET hits=hits+1 WHERE id=%d",$row->id)); wp_redirect($to,301); exit; } public function network_footer($c){ if(is_admin()||(defined('REST_REQUEST')&&REST_REQUEST)||!$this->s('network_links')||!is_singular('post')||!in_the_loop()||!is_main_query()) return $c; return $c.'<p class="ss-network"><small>შენი ქსელი: <a href="https://sheniekimi.ge" target="_blank" rel="noopener">შენი ექიმი</a> · <a href="https://sheniambebi.ge" target="_blank" rel="noopener">შენი ამბები</a></small></p>'; } /* ================= REST ================= */ public function rest(){ register_rest_route('ss/v1','/status',['methods'=>'GET','permission_callback'=>function(){ return current_user_can('edit_posts'); },'callback'=>function(){ return $this->stats(); }]); register_rest_route('ss/v1','/produce',['methods'=>'POST','permission_callback'=>function(){ return current_user_can('manage_options'); },'callback'=>function(){ $this->cron_fill(); $this->cron_publish(); return $this->stats(); }]); } public function stats(){ global $wpdb; $t=self::t_slots(); $o=['version'=>SHSUP_VER,'target'=>(int)$this->s('daily_target')]; foreach(['empty','scheduled','published','missed'] as $s) $o[$s]=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $t WHERE status=%s",$s)); $o['today_published']=(int)$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $t WHERE status='published' AND slot_time>=%s",$this->to_utc((new DateTime('now',$this->tz()))->format('Y-m-d 00:00:00')))); $o['drafts']=(int)wp_count_posts()->draft; $o['redirects']=(int)$wpdb->get_var("SELECT COUNT(*) FROM ".self::t_redirects()); $o['last_error']=get_option('ss_last_error',''); return $o; } /* ================= admin ================= */ public function menu(){ add_menu_page('Sheni Supra','Sheni Supra','manage_options','sheni-supra',[$this,'page_calendar'],'dashicons-calendar-alt',3); add_submenu_page('sheni-supra','Calendar','Calendar','manage_options','sheni-supra',[$this,'page_calendar']); add_submenu_page('sheni-supra','Sources','Sources','manage_options','ss-sources',[$this,'page_sources']); add_submenu_page('sheni-supra','Health & fixes','Health & fixes','manage_options','ss-health',[Sheni_Supra_Health::i(),'page']); add_submenu_page('sheni-supra','Settings','Settings','manage_options','ss-settings',[$this,'page_settings']); } private function btn($do,$label,$extra=[],$class='button'){ $u=wp_nonce_url(add_query_arg(array_merge(['action'=>'ss_action','do'=>$do],$extra),admin_url('admin-post.php')),'ss_'.$do); return '<a class="'.$class.'" href="'.esc_url($u).'">'.esc_html($label).'</a> '; } public function handle_action(){ if(!current_user_can('manage_options')) wp_die('no'); $do=sanitize_key($_GET['do']??$_POST['do']??''); check_admin_referer('ss_'.$do); global $wpdb; $t=self::t_slots(); $msg=''; $page='sheni-supra'; switch($do){ case 'produce': set_time_limit(280); $this->generate(); for($i=0;$i<3;$i++){ $this->cron_fill(); } $this->cron_publish(); $st=$this->stats(); $msg='Produce done — '.$st['scheduled'].' scheduled, '.$st['empty'].' empty'.($st['last_error']?' · last error: '.$st['last_error']:''); break; case 'toggle': $s=$this->s(); $s['enabled']=$s['enabled']?0:1; update_option('ss_settings',$s); $msg=$s['enabled']?'Engine running':'Engine paused'; break; case 'fill_one': set_time_limit(200); $sl=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",(int)$_GET['id'])); if($sl){ $r=$this->fill_slot($sl); $msg=$r?"Slot filled → post #$r":'Nothing available'.(get_option('ss_last_error')?' · '.get_option('ss_last_error'):''); } break; case 'release': $sl=$wpdb->get_row($wpdb->prepare("SELECT * FROM $t WHERE id=%d",(int)$_GET['id'])); if($sl&&$sl->post_id&&($p=get_post($sl->post_id))){ delete_post_meta($p->ID,'_ss_slot'); delete_post_meta($p->ID,'_ss_slot_id'); if($p->post_status==='future') wp_update_post(['ID'=>$p->ID,'post_status'=>'draft']); if($sl->origin_id){ delete_post_meta($sl->origin_id,'_ss_replaced_by'); delete_post_meta($sl->origin_id,'_ss_reserved'); } } $this->upd((int)$_GET['id'],['post_id'=>0,'origin_id'=>0,'status'=>'empty','note'=>'released']); $msg='Slot released'; break; case 'set_image': $pid=(int)$_GET['post']; $im=['url'=>esc_url_raw(wp_unslash($_GET['u'])),'creator'=>sanitize_text_field(wp_unslash($_GET['c']??'')),'license'=>sanitize_text_field(wp_unslash($_GET['l']??'')),'source'=>esc_url_raw(wp_unslash($_GET['s']??''))]; $r=$this->sideload($pid,$im['url'],get_the_title($pid),$this->credit($im)); $msg=$r?'Image replaced':'Could not download that image — try another'; break; case 'auto_image': $pid=(int)$_GET['post']; delete_post_thumbnail($pid); $msg=$this->ensure_image($pid)?'Image found':'No free image found for this topic — use the search box'; break; case 'bylines': $n=$this->distribute_bylines(true); $msg="Bylines redistributed across the team: $n articles"; $page='ss-settings'; break; case 'delete_slot': $wpdb->delete($t,['id'=>(int)$_GET['id']]); $msg='Slot deleted'; break; case 'retype': $wpdb->update($t,['type'=>$_GET['type']==='fresh'?'fresh':'refresh'],['id'=>(int)$_GET['id']]); $msg='Slot type changed'; break; case 'regen': $wpdb->query("DELETE FROM $t WHERE status='empty' AND slot_time>UTC_TIMESTAMP()"); $n=$this->generate(); $msg="Regenerated $n empty slots"; break; case 'src_save': $page='ss-sources'; $id=(int)$_POST['id']; $d=['name'=>sanitize_text_field($_POST['name']),'url'=>sanitize_text_field(wp_unslash($_POST['url'])),'kind'=>sanitize_key($_POST['kind']),'category_id'=>(int)$_POST['category_id'],'days'=>preg_replace('/[^1-7]/','',$_POST['days']?:'1234567'),'lang'=>sanitize_key($_POST['lang']),'active'=>!empty($_POST['active'])?1:0]; if($id) $wpdb->update(self::t_sources(),$d,['id'=>$id]); else $wpdb->insert(self::t_sources(),$d); $msg='Source saved'; break; case 'src_del': $page='ss-sources'; $wpdb->delete(self::t_sources(),['id'=>(int)$_GET['id']]); $msg='Source deleted'; break; case 'src_test': $page='ss-sources'; $src=$wpdb->get_row($wpdb->prepare("SELECT * FROM ".self::t_sources()." WHERE id=%d",(int)$_GET['id'])); $r=$this->fetch_source($src); $st=is_string($r)?$r:'ok, '.count($r).' items — e.g. "'.mb_substr($r[0]['title'],0,60).'"'; $wpdb->update(self::t_sources(),['last_status'=>mb_substr($st,0,190),'last_run'=>gmdate('Y-m-d H:i:s')],['id'=>$src->id]); $msg='Test: '.$st; break; case 'src_toggle': $page='ss-sources'; $wpdb->query($wpdb->prepare("UPDATE ".self::t_sources()." SET active=1-active WHERE id=%d",(int)$_GET['id'])); $msg='Source toggled'; break; case 'save_settings': $page='ss-settings'; $in=wp_unslash($_POST['ss']??[]); $s=$this->s(); foreach($this->defaults() as $k=>$v){ if(!isset($in[$k])){ if(in_array($k,['enabled','network_links'])) $s[$k]=0; continue; } $s[$k]=is_int($v)?(int)$in[$k]:sanitize_textarea_field($in[$k]); } update_option('ss_settings',$s); $msg='Settings saved'; break; } wp_redirect(add_query_arg(['page'=>$page,'msg'=>rawurlencode($msg),'day'=>sanitize_text_field($_GET['day']??'')],admin_url('admin.php'))); exit; } private function css(){ return '<style>.ss-grid{display:grid;grid-template-columns:repeat(8,1fr);gap:6px;margin:12px 0}.ss-day{border:1px solid #ccd0d4;background:#fff;padding:8px;border-radius:4px;text-decoration:none;color:#1d2327}.ss-day.sel{outline:2px solid #2271b1}.ss-day.full{border-color:#00a32a}.ss-day b{display:block}.ss-bar{height:6px;background:#eee;border-radius:3px;margin-top:6px;overflow:hidden;display:flex}.ss-bar i{display:block;height:100%}.st-published{background:#00a32a}.st-scheduled{background:#2271b1}.st-empty{background:#dcdcde}.st-missed{background:#d63638}.ss-pill{display:inline-block;padding:1px 7px;border-radius:9px;color:#fff;font-size:11px}.ss-pill.st-empty{color:#333}.ss-type{font-size:15px}.ss-th{width:48px;height:36px;object-fit:cover;border-radius:3px;display:block}.ss-pick{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;margin:10px 0}.ss-pick figure{margin:0;background:#fff;border:1px solid #ccd0d4;border-radius:4px;padding:6px}.ss-pick img{width:100%;height:120px;object-fit:cover;border-radius:3px}.ss-pick figcaption{font-size:11px;color:#666;margin:4px 0;height:30px;overflow:hidden}.ss-imgpanel{background:#f6f7f7;border:1px solid #ccd0d4;border-radius:4px;padding:12px 16px;margin:12px 0}</style>'; } public function page_calendar(){ global $wpdb; $t=self::t_slots(); $tz=$this->tz(); $st=$this->stats(); $n=(int)$this->s('daily_target'); $day=preg_match('/^\d{4}-\d{2}-\d{2}$/',$_GET['day']??'')?$_GET['day']:(new DateTime('now',$tz))->format('Y-m-d'); $start=(new DateTime('now',$tz))->modify('-2 days')->setTime(0,0); $span=(int)$this->s('days_ahead')+2; $days=[]; for($i=0;$i<$span;$i++){ $d=(clone $start)->modify("+$i day"); $days[$d->format('Y-m-d')]=['empty'=>0,'scheduled'=>0,'published'=>0,'missed'=>0]; } $rows=$wpdb->get_results($wpdb->prepare("SELECT * FROM $t WHERE slot_time BETWEEN %s AND %s ORDER BY slot_time",$this->to_utc($start->format('Y-m-d 00:00:00')),$this->to_utc((clone $start)->modify("+$span day")->format('Y-m-d 23:59:59')))); $byday=[]; foreach($rows as $r){ $ld=$this->to_local($r->slot_time)->format('Y-m-d'); if(isset($days[$ld])) $days[$ld][$r->status]++; $byday[$ld][]=$r; } echo '<div class="wrap">'.$this->css().'<h1>Sheni Supra <small style="color:#888;font-weight:400">v'.SHSUP_VER.' · '.$n.'/day ('.($n-(int)$this->s('fresh_per_day')).' ♻︎ + '.(int)$this->s('fresh_per_day').' ✦) · '.esc_html($this->s('timezone')).'</small></h1>'; if(!empty($_GET['msg'])) echo '<div class="notice notice-success is-dismissible"><p>'.esc_html($_GET['msg']).'</p></div>'; if(!$this->s('enabled')) echo '<div class="notice notice-warning"><p>Engine is <b>paused</b>.</p></div>'; if(!empty($_GET['img'])) $this->image_panel((int)$_GET['img'],$day); if(!$this->claude_key()) echo '<div class="notice notice-error"><p>No OpenAI API key — open OpenAI publishing. Keep automatic publication paused until the article checks pass.</p></div>'; echo '<p>'.$this->btn('produce','▶ Produce now',[],'button button-primary button-hero').$this->btn('toggle',$this->s('enabled')?'⏸ Pause':'▶ Resume',[],'button button-hero').' &nbsp; <span style="color:#666">Today <b>'.$st['today_published'].'</b>/'.$n.' published · '.$st['scheduled'].' scheduled · '.$st['empty'].' empty · '.$st['missed'].' missed · '.$st['drafts'].' drafts waiting · '.$st['redirects'].' redirects</span></p>'; if($st['last_error']) echo '<p style="color:#d63638">Last error: '.esc_html($st['last_error']).'</p>'; echo '<div class="ss-grid">'; foreach($days as $ld=>$c){ $tot=array_sum($c); $filled=$c['published']+$c['scheduled']; echo '<a class="ss-day'.($ld===$day?' sel':'').($filled>=$n?' full':'').'" href="'.esc_url(add_query_arg(['page'=>'sheni-supra','day'=>$ld],admin_url('admin.php'))).'"><b>'.esc_html((new DateTime($ld))->format('D d M')).'</b><span>'.$filled.' / '.$n.'</span><div class="ss-bar">'; foreach(['published','scheduled','empty','missed'] as $s) if($c[$s]) echo '<i class="st-'.$s.'" style="width:'.round(100*$c[$s]/max($n,$tot)).'%"></i>'; echo '</div></a>'; } echo '</div><h2>'.esc_html((new DateTime($day))->format('l, d F Y')).'</h2><table class="widefat striped"><thead><tr><th>Time</th><th>Slot</th><th>Type</th><th>Category</th><th>Status</th><th>Img</th><th>Article</th><th>Note</th><th></th></tr></thead><tbody>'; foreach($byday[$day]??[] as $r){ $cat=get_category($r->category_id); $p=$r->post_id?get_post($r->post_id):null; echo '<tr><td>'.$this->to_local($r->slot_time)->format('H:i').'</td><td><code>'.SHSUP_PREFIX.$r->slot_no.'</code></td><td class="ss-type" title="'.$r->type.'">'.($r->type==='fresh'?'✦':'♻︎').'</td><td>'.esc_html($cat?$cat->name:'—').'</td><td><span class="ss-pill st-'.$r->status.'">'.$r->status.'</span></td><td>'.($p?($th=get_the_post_thumbnail_url($p->ID,'thumbnail'))?'<a href="'.esc_url(add_query_arg(['page'=>'sheni-supra','day'=>$day,'img'=>$p->ID],admin_url('admin.php'))).'"><img src="'.esc_url($th).'" class="ss-th"></a>':'<a class="button button-small" style="color:#d63638" href="'.esc_url(add_query_arg(['page'=>'sheni-supra','day'=>$day,'img'=>$p->ID],admin_url('admin.php'))).'">no image</a>':'').'</td><td>'.($p?'<a href="'.get_edit_post_link($p->ID).'">'.esc_html(mb_substr($p->post_title,0,80)).'</a>'.($p->post_status==='publish'?' <a href="'.get_permalink($p).'" target="_blank">↗</a>':''):'—').'</td><td><small>'.esc_html($r->note).'</small></td><td>'; if(in_array($r->status,['empty','missed'])) echo $this->btn('fill_one','Fill',['id'=>$r->id,'day'=>$day],'button button-small').$this->btn('retype',$r->type==='fresh'?'→♻︎':'→✦',['id'=>$r->id,'day'=>$day,'type'=>$r->type==='fresh'?'refresh':'fresh'],'button button-small'); if($r->post_id&&$r->status!=='published') echo $this->btn('release','Release',['id'=>$r->id,'day'=>$day],'button button-small'); if($r->status!=='published') echo $this->btn('delete_slot','✕',['id'=>$r->id,'day'=>$day],'button button-small'); echo '</td></tr>'; } if(empty($byday[$day])) echo '<tr><td colspan="9">No slots — click <b>Produce now</b>.</td></tr>'; echo '</tbody></table><p>'.$this->btn('regen','Regenerate empty future slots').'</p>'; echo '<h2>Category coverage</h2><table class="widefat striped" style="max-width:640px"><thead><tr><th>Category</th><th>Posts</th><th>Weight</th><th>≈ ♻︎/day</th></tr></thead><tbody>'; $w=$this->category_weights(); $tot=array_sum($w); arsort($w); $ref=$n-(int)$this->s('fresh_per_day'); foreach($w as $id=>$x){ $c=get_category($id); echo '<tr><td>'.esc_html($c?$c->name:$id).'</td><td>'.($c?$c->count:'').'</td><td>'.round($x,1).'</td><td>'.round($ref*$x/$tot,1).'</td></tr>'; } echo '</tbody></table><p class="description">✦ Fresh slots target the categories of that weekday’s sources, thin categories (&lt;'.(int)$this->s('thin_cat_threshold').' posts) first — see Sources.</p></div>'; } private function image_panel($pid,$day){ $p=get_post($pid); if(!$p) return; $q=sanitize_text_field(wp_unslash($_GET['q']??''))?:(get_post_meta($pid,'_ss_image_query',true)?:$p->post_title); $back=add_query_arg(['page'=>'sheni-supra','day'=>$day],admin_url('admin.php')); $cur=get_the_post_thumbnail_url($pid,'medium'); $cr=get_post_meta($pid,'_ss_image_credit',true); echo '<div class="ss-imgpanel"><p style="margin:0 0 8px"><b>Image for:</b> '.esc_html(mb_substr($p->post_title,0,90)).' &nbsp; <a href="'.esc_url($back).'">✕ close</a></p>'; echo '<div style="display:flex;gap:16px;align-items:flex-start"><div>'.($cur?'<img src="'.esc_url($cur).'" style="width:220px;height:150px;object-fit:cover;border-radius:4px">':'<div style="width:220px;height:150px;background:#ddd;border-radius:4px;display:flex;align-items:center;justify-content:center;color:#666">no image</div>').'<div style="font-size:11px;color:#666;max-width:220px">'.esc_html($cr?:'own image').'</div></div>'; echo '<div style="flex:1"><form method="get" action="'.esc_url(admin_url('admin.php')).'"><input type="hidden" name="page" value="sheni-supra"><input type="hidden" name="day" value="'.esc_attr($day).'"><input type="hidden" name="img" value="'.$pid.'"><input name="q" value="'.esc_attr($q).'" class="regular-text" placeholder="search free images (English works best)"> <button class="button">Search</button> '.$this->btn('auto_image','Auto-pick',['post'=>$pid,'day'=>$day,'img'=>$pid]).'<span class="description">Free-to-use images (Creative Commons, commercial allowed) via Openverse — credit line is added automatically.</span></form>'; $res=$this->openverse_search($q,12); echo '<div class="ss-pick">'; foreach($res as $im){ $u=wp_nonce_url(add_query_arg(['action'=>'ss_action','do'=>'set_image','post'=>$pid,'day'=>$day,'u'=>rawurlencode($im['url']),'c'=>rawurlencode($im['creator']),'l'=>rawurlencode($im['license']),'s'=>rawurlencode($im['source'])],admin_url('admin-post.php')),'ss_set_image'); echo '<figure><img src="'.esc_url($im['thumb']).'" loading="lazy"><figcaption>'.esc_html(mb_substr($im['creator']?:$im['title'],0,30)).' · '.esc_html($im['license']).' · '.(int)$im['w'].'px</figcaption><a class="button button-small button-primary" href="'.esc_url($u).'">Use this</a></figure>'; } if(!$res) echo '<p>No results — try other English words.</p>'; echo '</div></div></div></div>'; } public function page_sources(){ global $wpdb; $rows=$wpdb->get_results("SELECT * FROM ".self::t_sources()." ORDER BY days,name"); $cats=get_categories(['hide_empty'=>false]); $dn=['','Mon','Tue','Wed','Thu','Fri','Sat','Sun']; echo '<div class="wrap">'.$this->css().'<h1>Sources — ✦ Fresh articles</h1>'; if(!empty($_GET['msg'])) echo '<div class="notice notice-success is-dismissible"><p>'.esc_html($_GET['msg']).'</p></div>'; echo '<p class="description">Each weekday the 5 Fresh slots pull from the sources marked for that day. Kinds: <b>rss</b> feed URL · <b>wp</b> WordPress site (REST) · <b>wikipedia</b> search query (ka or en). Some feeds block bots — use Test.</p>'; echo '<table class="widefat striped"><thead><tr><th>On</th><th>Days</th><th>Name</th><th>URL / query</th><th>Kind</th><th>→ Category</th><th>Lang</th><th>Produced</th><th>Last status</th><th></th></tr></thead><tbody>'; foreach($rows as $r){ $c=get_category($r->category_id); $dd=implode(' ',array_map(function($x)use($dn){ return $dn[(int)$x]; },str_split($r->days))); echo '<tr style="'.($r->active?'':'opacity:.5').'"><td>'.$this->btn('src_toggle',$r->active?'●':'○',['id'=>$r->id],'button button-small').'</td><td>'.$dd.'</td><td>'.esc_html($r->name).'</td><td><small>'.esc_html(mb_substr($r->url,0,60)).'</small></td><td>'.$r->kind.'</td><td>'.esc_html($c?$c->name:$r->category_id).'</td><td>'.$r->lang.'</td><td>'.$r->produced.'</td><td><small>'.esc_html($r->last_status).'</small></td><td>'.$this->btn('src_test','Test',['id'=>$r->id],'button button-small').'<a class="button button-small" href="'.esc_url(add_query_arg(['page'=>'ss-sources','edit'=>$r->id],admin_url('admin.php'))).'">Edit</a> '.$this->btn('src_del','✕',['id'=>$r->id],'button button-small').'</td></tr>'; } echo '</tbody></table>'; $e=!empty($_GET['edit'])?$wpdb->get_row($wpdb->prepare("SELECT * FROM ".self::t_sources()." WHERE id=%d",(int)$_GET['edit'])):null; echo '<h2>'.($e?'Edit source':'Add source').'</h2><form method="post" action="'.esc_url(admin_url('admin-post.php')).'"><input type="hidden" name="action" value="ss_action"><input type="hidden" name="do" value="src_save"><input type="hidden" name="id" value="'.($e?$e->id:0).'">'.wp_nonce_field('ss_src_save','_wpnonce',true,false); echo '<table class="form-table"><tr><th>Name</th><td><input name="name" class="regular-text" value="'.esc_attr($e->name??'').'" required></td></tr><tr><th>URL / query</th><td><input name="url" class="large-text" value="'.esc_attr($e->url??'').'" required></td></tr>'; echo '<tr><th>Kind</th><td><select name="kind">'; foreach(['auto','rss','wp','wikipedia'] as $k) echo '<option '.selected($e->kind??'auto',$k,false).'>'.$k.'</option>'; echo '</select></td></tr>'; echo '<tr><th>Category</th><td><select name="category_id">'; foreach($cats as $c) echo '<option value="'.$c->term_id.'" '.selected($e->category_id??0,$c->term_id,false).'>'.esc_html($c->name).' ('.$c->count.')</option>'; echo '</select></td></tr>'; echo '<tr><th>Days</th><td>'; for($i=1;$i<=7;$i++) echo '<label style="margin-right:10px"><input type="checkbox" name="d'.$i.'" onchange="this.form.days.value=[1,2,3,4,5,6,7].filter(i=>this.form[\'d\'+i].checked).join(\'\')" '.(strpos($e->days??'1234567',(string)$i)!==false?'checked':'').'> '.$dn[$i].'</label>'; echo '<input type="hidden" name="days" value="'.esc_attr($e->days??'1234567').'"></td></tr>'; echo '<tr><th>Language</th><td><select name="lang"><option '.selected($e->lang??'en','ka',false).'>ka</option><option '.selected($e->lang??'en','en',false).'>en</option></select></td></tr><tr><th>Active</th><td><input type="checkbox" name="active" value="1" '.checked($e->active??1,1,false).'></td></tr></table><p><button class="button button-primary">Save source</button></p></form></div>'; } public function page_settings(){ $s=$this->s(); $f=function($k,$type='text',$x='')use($s){ return '<input type="'.$type.'" name="ss['.$k.']" value="'.esc_attr($s[$k]).'" class="regular-text" '.$x.'>'; }; echo '<div class="wrap"><h1>Sheni Supra — Settings</h1>'; if(!empty($_GET['msg'])) echo '<div class="notice notice-success is-dismissible"><p>'.esc_html($_GET['msg']).'</p></div>'; echo '<form method="post" action="'.esc_url(admin_url('admin-post.php')).'"><input type="hidden" name="action" value="ss_action"><input type="hidden" name="do" value="save_settings">'.wp_nonce_field('ss_save_settings','_wpnonce',true,false).'<table class="form-table">'; echo '<tr><th>Engine</th><td><label><input type="checkbox" name="ss[enabled]" value="1" '.checked($s['enabled'],1,false).'> Running (fill every 15 min, publish every 5 min)</label></td></tr>'; echo '<tr><th>Per day</th><td>total '.$f('daily_target','number','style="width:80px"').' &nbsp; of which ✦ Fresh '.$f('fresh_per_day','number','style="width:80px"').' <span class="description">(rest are ♻︎ Refresh)</span></td></tr>'; echo '<tr><th>Window</th><td>'.$f('window_start','time','style="width:110px"').' – '.$f('window_end','time','style="width:110px"').' &nbsp; '.$f('timezone','text','style="width:150px"').' &nbsp; days ahead '.$f('days_ahead','number','style="width:70px"').' &nbsp; look-ahead h '.$f('lookahead_hours','number','style="width:70px"').'</td></tr>'; echo '<tr><th>♻︎ Refresh rules</th><td>article older than '.$f('min_age_days','number','style="width:70px"').' days, not refreshed in the last '.$f('cooldown_days','number','style="width:70px"').' days. Old URL gets a 301 to the new article; old post becomes private.</td></tr>'; echo '<tr><th>Thin category threshold</th><td>'.$f('thin_cat_threshold','number','style="width:70px"').' posts — Fresh slots prioritise categories below this</td></tr>'; echo '<tr><th>Minimum per category / day</th><td><textarea name="ss[cat_min]" rows="2" class="large-text code">'.esc_textarea($s['cat_min']).'</textarea><p class="description"><code>category_id=count</code> per line — guaranteed slots per day for that category (9 = სიახლეები). Applied on top of the weights.</p></td></tr>'; echo '<tr><th>Category weights</th><td><textarea name="ss[cat_weights]" rows="4" class="large-text code">'.esc_textarea($s['cat_weights']).'</textarea><p class="description"><code>category_id=weight</code> per line; blank = √count</p></td></tr>'; echo '<tr><th>Exclude categories</th><td>'.$f('exclude_cats').'</td></tr>'; echo '<tr><th>Claude</th><td>'.$f('claude_key','password').' '.($this->claude_key()?'✅':'❌').' &nbsp; model '.$f('claude_model','text','style="width:220px"').'</td></tr>'; echo '<tr><th>Byline user ID</th><td>'.$f('byline_user','number','style="width:80px"').' <span class="description">0 = rotate equally between all users with a first name (the journalist team)</span> '.$this->btn('bylines','Redistribute all articles equally now').'</td></tr>'; echo '<tr><th>Network links</th><td><label><input type="checkbox" name="ss[network_links]" value="1" '.checked($s['network_links'],1,false).'> add შენი ექიმი · შენი ამბები footer to every article</label></td></tr>'; echo '</table><p><button class="button button-primary">Save</button></p></form></div>'; } } /* Controlled recovery: retain settings and stop all automatic article/bulk-edit work until tested. */ if(!get_option('shsup_openai_recovery_20261116')){ add_option('shsup_recovery_backup_20261116',['settings'=>get_option('ss_settings'), 'health'=>get_option('ss_health'),'fatal'=>get_option('shsup_fatal'),'activation_error'=>get_option('shsup_activation_error'),'utc'=>gmdate('c')],'','no'); $recover=(array)get_option('ss_settings',[]);$recover['enabled']=0;update_option('ss_settings',$recover,false); $health=(array)get_option('ss_health',[]);if(empty($health['jobs']))foreach(['site','alt','images','meta'] as $job)$health['jobs'][$job]=['done'=>0,'total'=>0,'status'=>'paused','note'=>'Recovery review','ai'=>0];$health['enabled']=0;update_option('ss_health',$health,false); update_option('shsup_openai_recovery_20261116',gmdate('c'),false); } final class Sheni_Supra_OpenAI { static function key(){ if(defined('SHENI_OPENAI_API_KEY'))return (string)SHENI_OPENAI_API_KEY; $j=get_option('ss_openai_encrypted',[]);if(!is_array($j)||empty($j['data'])||!function_exists('openssl_decrypt'))return ''; return (string)openssl_decrypt(base64_decode($j['data']),'aes-256-gcm',hash('sha256',wp_salt('auth'),true),OPENSSL_RAW_DATA,base64_decode($j['iv']),base64_decode($j['tag'])); } static function request($prompt,$max=6000){ $key=self::key();if(!$key)return new WP_Error('openai_key','OpenAI key missing on Supra. Enter it privately in OpenAI publishing.'); $r=wp_remote_post('https://api.openai.com/v1/chat/completions',['timeout'=>170,'redirection'=>0,'headers'=>['Content-Type'=>'application/json','Authorization'=>'Bearer '.$key],'body'=>wp_json_encode(['model'=>get_option('ss_openai_model','gpt-4.1-mini'),'store'=>false,'temperature'=>0.2,'max_tokens'=>max(100, 'response_format' => array( 'type' => 'json_object' ),min(12000,(int)$max)),'messages'=>[['role'=>'system','content'=>'Write natural Georgian. Use only supported source facts. Never fabricate dates, current events, quotations, health claims, links or personal authorship. Short accurate headline, H2/H3 headings, useful FAQ only if supported. Missing evidence must be flagged.'],['role'=>'user','content'=>$prompt]]])]); if(is_wp_error($r))return new WP_Error('openai_network','OpenAI network request failed; existing work retained.'); $b=json_decode(wp_remote_retrieve_body($r),true); if ( ! is_array( $b ) ) { $b = array(); error_log( 'SS bad AI JSON' ); }$code=wp_remote_retrieve_response_code($r); if($code!==200){$err=preg_replace('/[^a-zA-Z0-9_-]/','',$b['error']['code']??'request_failed');return new WP_Error('openai_http','OpenAI HTTP '.(int)$code.' ['.$err.']; no Claude fallback.');} $c=$b['choices'][0]??[];if(($c['finish_reason']??'')!=='stop'||!empty($c['message']['refusal'])||empty($c['message']['content']))return new WP_Error('openai_incomplete','OpenAI response incomplete; no article accepted.'); return $c['message']['content']; } static function page(){ if(!current_user_can('manage_options'))return; if(isset($_POST['ss_oa'])){check_admin_referer('ss_openai');$act=sanitize_key($_POST['ss_oa']); if($act==='save'){$model=sanitize_text_field(wp_unslash($_POST['model']??'gpt-4.1-mini'));if(!preg_match('/^gpt-[a-zA-Z0-9._-]{1,70}$/',$model))$model='gpt-4.1-mini';update_option('ss_openai_model',$model,false); if(!empty($_POST['openai_key'])&&function_exists('openssl_encrypt')){$key=trim(wp_unslash($_POST['openai_key']));$iv=random_bytes(12);$tag='';$data=openssl_encrypt($key,'aes-256-gcm',hash('sha256',wp_salt('auth'),true),OPENSSL_RAW_DATA,$iv,$tag);if($data!==false)update_option('ss_openai_encrypted',['data'=>base64_encode($data),'iv'=>base64_encode($iv),'tag'=>base64_encode($tag)],false);} }elseif($act==='test'){$r=self::request('Reply OK only. Connection test; do not create an article.',100);$msg=is_wp_error($r)?$r->get_error_message():'OpenAI connection passed';update_option('ss_openai_health',['message'=>$msg,'ok'=>!is_wp_error($r),'utc'=>gmdate('c')],false);} } $health=get_option('ss_openai_health',[]);echo '<div class="notice '.(!empty($health['ok'])?'notice-success':'notice-info').'"><p><strong>'.esc_html($health['message']??'OpenAI connection has not been tested yet').'</strong> '.esc_html($health['utc']??'').'</p></div>';echo '<div class="wrap"><h1>Supra — OpenAI publishing</h1><p>Current PHP memory limit: <strong>'.esc_html(ini_get('memory_limit')).'</strong>. PHP version: '.esc_html(PHP_VERSION).'.</p><p>Provider: OpenAI only. Key: <strong>'.(self::key()?'configured (hidden)':'MISSING on this website').'</strong>.</p><p>'.esc_html($health['message']??'Not tested yet').' '.esc_html($health['utc']??'').'</p><p>Recovery mode: article generation and bulk archive repairs are paused. Original posts, bylines, source tables and recorded errors are retained. Do not resume until source accuracy, links, images and duplicate protection have passed a draft test.</p><form method="post" autocomplete="off">';wp_nonce_field('ss_openai');echo '<p><label>OpenAI API key — enter privately; blank retains saved key<br><input type="password" name="openai_key" autocomplete="new-password" size="60" value=""></label></p><p><label>OpenAI model <input name="model" value="'.esc_attr(get_option('ss_openai_model','gpt-4.1-mini')).'"></label></p><button class="button button-primary" name="ss_oa" value="save">Save OpenAI settings</button> <button class="button" name="ss_oa" value="test">Test OpenAI connection</button></form></div>'; } } add_action('admin_menu',function(){add_submenu_page('sheni-supra','OpenAI publishing','OpenAI publishing','manage_options','ss-openai',[Sheni_Supra_OpenAI::class,'page']);},20); if(!class_exists('Sheni_Supra_Engine_Loaded')){ class Sheni_Supra_Engine_Loaded{} Sheni_Supra_Engine::i(); require_once __DIR__.'/health.php'; Sheni_Supra_Health::i(); require_once __DIR__.'/feed.php'; Sheni_Supra_Feed::i(); } ქართული სამზარეულო | შენი სუფრა | Page 7

ჭდე: ქართული სამზარეულო

გაიცანით ქართველი შეფ მზარეული სტრასბურგში

ავტორი: თინათინ თავხელიძე “სამზარეულო საზღვრებს გარეშე” - ამ სათაურით დაიბეჭდა ქართველი შეფ…

ნინო ბერიძე

რა უნდა იცოდეთ ალადასტურის შესახებ

„არ დამსაჯოთ, ამ ღვინის დალევაზე ალაჰმა დასტური მომცა!“ – ზოგიერთი ისტორიკოსი საქართველოში…

თაკო ფრიცხელაური

აი, თურმე რატომ აქვს ქართულ ღვინის დოქს გრეხილი სახელური 🙂

იმერულ „ხარადოქებზე“ და იშვიათად სხვა კუთხის მოზრდილ დოქებზე ხშირად გვხვდება ერთგვარი გრეხილიანი…

მარიამ გოგოლაძე

ამ ღვეზელზე უარის თქმა იმასაც უჭირს, ვისაც ქათმის ღვიძლი არ უყვარს.

1.6K შემწვარი ღვეზელები ღვიძლთან და ბრინჯთან ერთად ქმარს არ მოსწონს ღვიძლის კერძები,…

მარიამ გოგოლაძე

ვარშავაში ქართული ღვინის მასშტანური დეგუსტაცია გაიმართა

ღვინის ეროვნული სააგენტოს მხარდაჭერით, ვარშავაში ქართული ღვინის მასშტაბური დეგუსტაცია გაიმართა პოლონეთის დედაქალაქ…

ანა ჭელიძე

ცხარე პომიდვრის სოუსი “კობრა”, 80-იანი წლების პოპულარული საწებელი.

11.5K საწებელისთვის გამოიყენეთ სქელძირიანი ქვაბი, დუღილის დროს პერიოდულად ხის კოვზით ურიეთ, რომ…

მარიამ გოგოლაძე

ახალი წლის ტრადიციები და საჭმელები

ახალი წლის დღესასწაული განსაკუთრებული მოვლენაა ყველა ქვეყანაში და მათ შორის საქართველოშიც. ამ…

თაკო ფრიცხელაური

ბაქოში, სოფლის მეურნეობის საერთაშორისო გამოფენაზე საქართველო მონაწილეობდა

ბაქოში, გამოფენაზე „CASPIAN AGRO 2024” საქართველოდან მეწარმეებმა საკუთარი პროდუქცია წარადგინეს გარემოს დაცვისა…

ნინო ბერიძე