<?php
    error_reporting(E_ALL & ~E_NOTICE);
    date_default_timezone_set("Europe/Oslo");

    function IsJsonString($string) {
        if(substr($string,0,1)=="{" || substr($string,0,1)=="[") {
            return true;
        } else {
            return false;
        }
    }

    $_POST = json_decode(file_get_contents('php://input'), true);

    if(isset($_POST['setting'])) {
        $setting=stripslashes(htmlspecialchars($_POST['setting']));
        $value=utf8_encode(base64_decode(stripslashes(htmlspecialchars($_POST['value']))));
        $key=base64_decode(stripslashes(htmlspecialchars($_POST['key'])),true);

        $output="";
        $tnow=time();

        switch($setting) {
            case "update": //
                $newObj=array(
                    "author" => "twily.info",
                    "time" => $tnow,
                    "date" => date("Y M jS D h:i:s A"),
                    "data" => array(
                        "value" => $value,
                        "key" => $key,
                    ),
                );
                $output=json_encode($newObj,JSON_FORCE_OBJECT);
                break;
            case "getdata":
                $f1="./chats.json";
                if (!file_exists($f1)) return;

                $fdata = json_decode(file_get_contents($f1), true) ?: [];
                $output="<br>Preparing file conversation of existing json databases to plain *.log (jsonl line separated invidivual jsons)...<br><br>---<br>converting...<br>";
                foreach ($fdata as &$item) {
                    $id=$item['id'];
                    $f2="./chats/".$id.".json";
                    $f3="./chats/".$id.".log";

                    if(!file_exists($f2)) continue;

                    $cdata = json_decode(file_get_contents($f2), true) ?: [];

                    $output.="".$f2." => ".$f3."<br />";
                    $strdat="";
                    for($i=0;$i<count($cdata);$i++) {
                        $msg=$cdata[$i];

                        if(!empty($msg['is_image'])) {
                            $imgpath=$msg['content']; // ./chats/../.png
                            $imgpath = $msg['content']; // e.g., ./chats/chat-ID/generated/img-XXX.png
                            $localImg = __DIR__ . '/' . ltrim($imgpath, './');

                            $width = 512;  // Fallback defaults
                            $height = 512;

                            if (file_exists($localImg)) {
                                $size = @getimagesize($localImg);
                                if ($size !== false) {
                                    $width = $size[0];
                                    $height = $size[1];
                                }
                            }

                            $msg['metadata'] = array(
                                "width" => $width,
                                "height" => $height
                            );
                        }
                        //$strdat.=json_encode($msg)."\n";
                        $strdat .= json_encode($msg, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
                    }

                    file_put_contents($f3, $strdat);
                }

                $output.="_<br>---<br><br>completed converting all json to new simpler log format (jsonl) support partial reading/writing and now storing image dimensions in metadata.<br><br>you can delete all the old ./chats/*.json files if you see the log files and everything is working on latest version x) (don't delete the main chats.json file!)";

                break;
            default:
        }

        echo $output;
        exit;
    }
?>
<!DOCTYPE html>
<!--

    Author:        Twily  2015 - 2021
    Website:       http://twily.info/

-->
<html>
<head>
<title>&gt;_</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />

<!--<link id="favicon" rel="shortcut icon" href="http://twily.info/favicon.ico" />-->
<!--<link rel="stylesheet" type="text/css" href="./css/style.css?v=1" />-->
<style type="text/css">
html,body {
    width: 100%; height: 100%; margin: 0; padding: 0; overflow: auto;
    font-family: "Droid Sans", "Liberation Sans", "DejaVu Sans", "Segoe UI", Sans;
    font-size: 12pt; font-weight: bold;
    background: #17181A; color: #AAABAD;
}
* { box-sizing: border-box; }
*:focus { outline: none !important; }

a:link, a:visited { color: #606163; text-decoration: none; }
a:hover, a:active { color: #EA75BC; }

.tbl { display: table; width: 100%; height: 100%; }
.tr { display: table-row; }
.td { display: table-cell; vertical-align: top; border: 1px solid #606163; box-shadow: inset 0 0 2px 2px #000; }

.sides { width: 200px; min-width: 200px; vertical-align: middle; }

.green { color: #080; }
.red { color: #800; }

textarea, input[type="text"] {
    background: #000; color: #fff;
    border: 1px solid #666;
    width: 100%;
}

/*
#wrap { width: 100%; height: 100%; display: flex; position: absolute; z-index: 9; }
#wrap #box { padding: 128px; background: #111113; margin: auto; display: inline-block; position: relative; }*/

</style>

<!--<script type="text/javascript" src="./js/main.js?v=1"></script>-->
<script type="text/javascript">
var $=function(id) { return document.getElementById(id); };
var enableLS=(typeof(Storage)!=="undefined")?true:false;
var rndMinMax=function(min,max) { return Math.floor(Math.random()*(max-min+1)+min); }
var IsJsonString=function(str) { try { JSON.parse(str); } catch(e) { return false; } return true; }

function b64Enc(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,function(match,p1) {
        return String.fromCharCode(parseInt(p1,16));
    }));
}
function b64Dec(str) {
    try {
        return decodeURIComponent(Array.prototype.map.call(atob(str),function(c) {
            return '%'+('00'+c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
    } catch(e) {
        return str;
    }
}

var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var days=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
function getLocalTime(t=0) {
    if(t>0) {
        var d=new Date(t*1000);
    } else {
        var d=new Date();
    }
    var year=d.getFullYear();
    var month=months[d.getMonth()]; //Jan-Dec
    var day=days[d.getDay()];//Mon-Sun
    var dd=d.getDate(); //1-31
    var hh=d.getHours(); //0-23
    var mm=d.getMinutes(); //0-59
    var ss=d.getSeconds(); //0-59
    var ampm=(hh>=12)?"PM":"AM";
    hh=hh%12||12;
    hh=hh<10?"0"+hh:hh;
    mm=mm<10?"0"+mm:mm;
    ss=ss<10?"0"+ss:ss;
    var dth=dd.toString();
    dth=(((dth==1)?"st":dth==2)?"nd":dth==3)?"rd":"th";

    return year+" "+month+" "+dd+dth+" "+day+" "+hh+":"+mm+":"+ss+" "+ampm;
}

function ajaxThis(x,y,z,cb) {
    var xhr;
    if(window.XMLHttpRequest) xhr=new XMLHttpRequest();
    else                      xhr=new ActiveXObject("Microsoft.XMLHTTP");

    var data;
    xhr.onreadystatechange=function() {
        if(xhr.readyState==4 && xhr.status==200) {

            if(typeof cb==='function') {
                cb(xhr.responseText);
            }
        }
    }

    xhr.open("POST","./convert-databases-v1.0.2-to-v1.0.3.php",true);
    //xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //xhr.send("setting="+x+"&value="+b64Enc(y)+"&key="+b64Enc(z));

    // or with json to prevent issues with special chars and url encoding~

    xhr.setRequestHeader("Content-Type","application/json");
    xhr.send(JSON.stringify({setting: x, value: b64Enc(y), key: b64Enc(z)}));
}

function finddata() {
    ajaxThis('getdata','','',function(data) {
        $('div').innerHTML=data;
    });
}


function init() {
    finddata();
}
</script>
</head>
<body onload="init();">


<div class="tbl">
    <div class="tr" style="height: 50px;">
        <div class="td" style="text-align: center; vertical-align: middle;">
            convert-database-v1.0.2-to-v1.0.3
        </div>
    </div>
    <div class="tr">
        <div class="td">

        <div class="tbl">
            <div class="tr">
                <div class="td sides">

                &nbsp;

                </div>
                <div class="td" style="word-break: break-word;">

<div id="div"></div>

                </div>
                <div class="td sides">

                &nbsp;

                </div>
            </div>
        </div>

        </div>
    </div>
    <div class="tr" style="height: 50px;">
        <div class="td" style="text-align: center; vertical-align: middle;">
            keeps the original .json in case but don't run this again later!
        </div>
    </div>
</div>


</body>
</html>

