<?php
function random_keyword($list_file)
{
    $keyword = "預設";
    $lines = file($list_file);
    $rand_keys = array_rand($lines, 1);

    if (mb_strlen(trim($lines[$rand_keys]), "utf-8") == 2) {
        $keyword = trim($lines[$rand_keys]);
        }

    return $keyword;
}

function write_inline($times)
{
    $inline = "";

    for ($i = 0; $i < $times; $i ++) {
        $inline .= "\( -clone 0 -write inline:png:- \) ";

        if (($i + 1) != $times) {
            $inline .= "-delete 0 ";
            }
        }

    return $inline;
}

function json_maker($keyword, $data)
{
    $json = "{";
    $base64_images = explode("data:image/png;base64,", $data);
    array_shift($base64_images);
    $json .= sprintf("\"keyword\":\"%s\", \"base64\": {", $keyword);

    foreach ($base64_images as $key => $value) {
        $json .= sprintf("\"image%d\":\"%s\",", $key, $value);
        }

    $json = rtrim($json, ",");
    $json .= "}}";

    return $json;
}

$server_key = "Y2hpbmVzZV9wdXp6bGUK";
$convert_path = "/usr/local/bin/convert";
$pointsize = 240;
$horizontal_tiles = 6;
$vertical_tiles = 3;
$font = "font/SourceHanSerifTC-Bold.otf";
$list_file = "list.txt";
$auth_key = "";
$keyword = "";

if (isset($_GET["auth_key"])) {
    $auth_key = $_GET["auth_key"];
    }

if ($server_key != $auth_key) {
    exit;
    }

if (isset($_GET["keyword"])) {
    $keyword = $_GET["keyword"];

    if (mb_strlen($keyword, "utf-8") != 2) {
        exit;
        }
    }

if ($keyword == "") {
    $keyword = random_keyword($list_file);
    }

$total_tiles = $horizontal_tiles * $vertical_tiles;
$inlines = write_inline($total_tiles);
$cmd = sprintf("%s -pointsize %d -font %s label:\"%s\" -trim -strip -crop %dx%d@ %s null:",
$convert_path, $pointsize, $font, $keyword, $horizontal_tiles, $vertical_tiles, $inlines);
//echo $cmd;
$output = shell_exec($cmd);

if ($output) {
    echo json_maker($keyword, $output);
    }
?>
