<?php
$accesstoken="IGQWRQaGFUVURIcjhnTzRwaFhqM1ZAfRlJzREVSdGJRdXE3WnRIenl1MGZA1MkYzOENELVdwR2hDaDhjREZAOOTExVGJXZA2d4Mk90VmJoc181Qzg3bHBPS0ptZAGdRMFFoWVctLTJLYU1OdW13MjhmZAU5KaDVRbVpWVlkZD";
$medias = [];
//if(!isset($_SESSION["medias"])){
$opts = [
    "http" => [
	"method" => "GET",
	"header" => "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"
    ]
];
$context = stream_context_create($opts);
$raw = [];
if(intval(file_get_contents("import.insta.time"))<(time()-(3600*12))){
    $u = "https://www.instagram.com/graphql/query/?query_hash=e769aa130647d2354c40ea6a439bfc08&variables=%7B%22id%22%3A%225408546825%22,%20%22first%22%3A%2250%22,%20%22after%22%3A%20%22%22%7D";
    $json = file_get_contents($u, false, $context);
    die(print_r($json,true));
    $data = json_decode($json, true);
    $raw = $data['data']['user']['edge_owner_to_timeline_media']['edges'];
    file_put_contents("import.insta.json",json_encode($raw, JSON_PRETTY_PRINT));
    file_put_contents("import.insta.time",strval(time()));
}else{
    $u = "import.insta.json";
    $json = file_get_contents($u);
    $raw= json_decode($json,true);
}
$medias = [];
foreach ($raw as $rawMedia) {
    $rawMedia = $rawMedia['node'];

    $caption = NULL;
    if (count($rawMedia['edge_media_to_caption']['edges']) > 0) {
	$caption = $rawMedia['edge_media_to_caption']['edges'][0]['node']['text'];
    }

    $medias[] = [
	'id'        => $rawMedia['id'],
	'caption'   => $caption,
	'thumbnail' => $rawMedia['thumbnail_src'],
	'original'  => $rawMedia['display_url'],
	'link'      => 'https://www.instagram.com/p/' . $rawMedia['shortcode'] . '/',
	'taken_at'  => $rawMedia['taken_at_timestamp']
    ];
}
$_SESSION["medias"]=json_encode($medias);
//}
$medias = json_decode($_SESSION["medias"],true);
if(isset($_GET["id"])){
    $newarr = [];
    foreach($medias as $k => $v){
	$newarr[$v['id']] = $v;
    }
    if(!isset($newarr[$_GET["id"]]) and !in_array($_GET["id"],$newarr)){
	die(print_r($newarr,true));
    }
    header('Content-Type: image/png');
    die( file_get_contents($newarr[$_GET["id"]]["thumbnail"]));
}
$supclass="";
if(isset($_GET["limit"])){
    $limit = intval($_GET["limit"]);
    $medias = array_slice($medias, 0, $limit);
    $supclass="";
    if(count($medias)<4){
	$supclass = "photos-list-photos-len-".strval(count($medias));
    }
}
?>
<div
class="photos-list-photos <?=$supclass?>">
<?php
foreach($medias as $m){
?>
<a
style="background-image:url(/getallphotos?id=<?=$m["id"]?>);"
title="<?=$m["caption"]?>"
class="photos-list-item"
href="<?=$m["link"]?>"
target="_blank"
>
<span id=caption><?=htmlspecialchars($m["caption"])?></span>
</a>
<?php
}
?>
</div>
