<?php

if (isset($_GET['sauce'])) { highlight_file(__FILE__); die(); }

// Caching.
if(count($_GET) > 0 && !isset($_GET['nocachepls']) && !isset($_GET['cachepls'])) {
    $keys = array_keys($_GET);
    $hash = array_shift($keys);
    $file = 'covers/' . basename($hash) . '.jpg';
    $meta = json_decode(file_get_contents('covers/meta.json'), true);

    if (!file_exists($file) || !isset($meta[$file])) {
        $res = ''; $id = 0;
    } else {

    $res = $meta[$file]['title'];
    $id = $meta[$file]['gelbooru_id']; }
} elseif (true || !isset($_GET['nocachepls']) && (isset($_GET['cachepls']) || time() - file_get_contents('covers/timestamp') < 3)) {
    // Serve a random result.
    $meta = json_decode(file_get_contents('covers/meta.json'), true);
    $file = array_rand($meta);
    $hash = str_replace(array('covers/', '.jpg'), '', $file);
    header('HTTP/1.1 302 Found');
    header('Location: https://salty-salty-studios.com/shiz/lncovers.php?' . $hash);
    die();
} else {

file_put_contents('covers/timestamp', time());

global $subjects, $actions, $followactions, $prefixes, $adverbs, $adjectives, $connectors, $firstnames, $surnames;
require 'lncovers.dataset.txt';

if (isset($_GET['override'])) {
  $res = $_GET['override'];
} else {
// !!! HERE BE DRAGONS !!!
function mksentence($prev = '', $prevgender = '', $tense = 1) {
  global $subjects, $actions, $followactions, $prefixes, $adverbs;

  $res = '';
  if ($prevgender != '') {
    if (!rand(0, 3)) {
      $subject = array_rand($subjects);
      $gender = $subjects[$subject];
      if ($gender == -1) {
        $gender = rand(0, 1);
      }
    } else {
      $subject = ($prevgender == 0 ? 'he' : ($prevgender == 1 ? 'she' : ($prevgender == 2 || $prevgender == 4 ? 'they' : ($prevgender == 3 ? 'i' : ''))));
      $gender = $prevgender;
    }
  } else {
    if (rand(0, 3)) {
      $subject = array_rand($subjects);
    } else {
      $subject = 'i';
    }
    $gender = $subjects[$subject];
    if ($gender == -1) {
      $gender = rand(0, 1);
    }
  }

  if (!$prev && !rand(0,10)) {
    $res .= $prefixes[array_rand($prefixes)] . ' ';
  }

  do {
    $action = array_rand($prev ? array_merge($followactions, $actions) : $actions);
    $orig = $action;
  } while ($action == $prev);
  if ((isset($actions[$action]) && $actions[$action]) || (isset($followactions[$action]) && $followactions[$action])) {
    $res .= $subject;
  }

  $ngender = $gender;
  if (strstr($action, '%o')) {
    if (strstr($action, '%a')) {
       do {
         $osubject = array_rand($subjects);
       } while (($gender == 4 && $subjects[$osubject] != 4) || ($gender != 4 && $subjects[$osubject] == 4));
    } else {
       if ($prevgender != '') {
           if (rand(0, 2)) {
              if ($prevgender == $gender) {
                 $osubject = '%r';
              } else {
                 $osubject = $prevgender == 0 ? 'him' : ($prevgender == 1 ? 'her' : ($prevgender == 2 ? 'them' : ($prevgender == 3 ? 'me' : 'them')));
              }
              $ogender = $prevgender;
           } else {
              $osubject = array_rand($subjects);
              $ogender = $subjects[$osubject];
              if ($ogender == -1) {
                $ogender = rand(0, 1);
              }
           }
       } else {
           if (rand(0, 4)) {
              $osubject = array_rand($subjects);
              $ogender = $subjects[$osubject];
              if ($ogender == -1) {
                $ogender = rand(0, 1);
              }
           } else {
              $osubject = '%r';
              $ogender = $gender;
           }
       }
    }
    if ($osubject == 'i') { $osubject = 'me'; }
    $action = str_replace('%o', $osubject, $action);
    if (rand(0, 1)) {
      $ngender = $ogender;
    }
  }

  $action = str_replace('%a', ($tense ? (($gender <= 2 && $subject != 'they') ? 'is' : ($gender == 3 ? 'am' : 'are')) : ($gender == 4  || ($gender == 2 && $subject == 'they') ? 'were' : 'was')) . ' %y', $action);
  $action = str_replace('%h', ($tense ? (($gender == 2 && $subject == 'they') || $gender == 3 || $gender == 4 ? 'have' : 'has') : 'had'), $action);
  $action = str_replace('%p', $gender == 0 ? 'his' : ($gender == 1 ? 'her' : ($gender == 2 ? 'their' : ($gender == 3 ? 'my' : 'their'))), $action);
  $action = str_replace('%r', $gender == 0 ? 'himself' : ($gender == 1 ? 'herself' : ($gender == 2 ? 'themselves' : ($gender == 3 ? 'myself' : 'themselves'))), $action);
  $action = str_replace('%m', $gender == 0 ? 'his own' : ($gender == 1 ? 'her own' : ($gender == 2 ? 'their own' : ($gender == 3 ? 'my own' : 'their own'))), $action);
  $action = str_replace('%s', ($gender == 2 && $subject == 'they') || $gender == 3 || $gender == 4 ? '' : 's', $action);
  $action = str_replace('%t(', '%y %t(', $action);
  $action = preg_replace('/%v\[(.*?)\|(.*?)\|(.*?)\]/', $gender == 3 ? '$1' : ($gender == 4 || ($gender == 2 && $subject == 'they') ? '$3' : '$2'), $action);
  while (strstr($action, '%y')) {
    if (rand(0, 2)) {
      $action = preg_replace('/%y /', '', $action, 1);
    } else {
      $action = preg_replace('/%y/', $adverbs[array_rand($adverbs)], $action, 1);
    }
  }

  $res .= ' ' . $action;

  return array($res, $orig, $ngender);
}

// Sentence forming
list($res, $prev, $prevgender) = mksentence();
$c = 1;
if (rand(0, 4)) {
  // Add another sentence.
  $connector = array_rand($connectors);
  $c = $connectors[$connector];
  if ($c == -1) {
    $c = rand(0, 1);
  }

  $res = trim($res) . ', ' . $connector . ' ' . mksentence($prev, $prevgender, $c)[0];
}
$res = preg_replace('/\%t\((.*?)\,(.*?)\)/', $c ? '$1' : '$2', $res);
$res = ucwords($res);

if (!rand(0, 7)) {
   $res .= '?!';
} elseif (!rand(0, 11)) {
   $res .= '~';
} elseif (!rand(0, 10)) {
   $res .= '...';
} else {
   $res .= '!';
}
}

// Generate name.
$author = $surnames[array_rand($surnames)] . ' ' . $firstnames[array_rand($firstnames)];
// Generate illustrator.
if (!rand(0, 3)) {
  $illustrator = $surnames[array_rand($surnames)] . ' ' . $firstnames[array_rand($firstnames)];
} else {
  $illustrator = '';
  for ($i = 0, $len = rand(2, 4); $i < $len; $i++) {
    $illustrator .= $kana[array_rand($kana)];
  }
  if (!rand(0, 4)) {
    $illustrator .= 'n';
  }
  $illustrator = ucfirst($illustrator);
}

// Grab an image from Gelbooru.
// Grab their post count.
$gelindex = file_get_contents('http://gelbooru.com/index.php?page=dapi&q=index&s=post&limit=1');
$gelxml = simplexml_load_string($gelindex);
$count = intval($gelxml->attributes()['count']);

$url = '';
// Grab a random post.
do {
   mt_srand(microtime(true));
   $id = mt_rand(1, $count);
   $gelpost = file_get_contents('http://gelbooru.com/index.php?page=dapi&q=index&s=post&limit=1&id=' . $id);
   $gelxml = simplexml_load_string($gelpost);
   if(!$gelxml) continue;
   if($gelxml->post->attributes()['rating'] == 'e') continue;
   if(strstr($gelxml->post->attributes()['tags'], 'photo') !== FALSE) continue;
   if(strstr($gelxml->post->attributes()['tags'], 'comic') !== FALSE) continue;
   $url = $gelxml->post->attributes()['file_url'];
} while(!$url);

// Load it up in GD.
$image = file_get_contents($url);
$gdi = imagecreatefromstring($image);
$gd = imagecreatetruecolor(600, 900);

$gdiw = imagesx($gdi);
$gdih = imagesy($gdi);
if(!$gdi) { die('no gd 4 u'); }

function resizeImage($gdSourceImage, $intTargetWidth, $intTargetHeight, $gdTargetImage) {
    $gdIntermediateImage = FALSE;
    $intSourceWidth = 0;
    $intSourceHeight = 0;
    $intSourceRatio = 0;
    $intNewWidth = 0;
    $intNewHeight = 0;
    $intNewXOffset = 0;
    $intNewYOffset = 0;
    $intTargetRatio = 0;

    $intSourceWidth = imagesx($gdSourceImage);
    $intSourceHeight = imagesy($gdSourceImage);

    $intSourceRatio = $intSourceWidth / $intSourceHeight;
    $intTargetRatio = $intTargetWidth / $intTargetHeight;

    if($intSourceRatio < $intTargetRatio) {
        $intNewWidth = $intTargetWidth;
        $intNewHeight = ($intTargetWidth / $intSourceWidth) * $intSourceHeight;
        $intNewXOffset = 0;
        $intNewYOffset = ($intNewHeight - $intTargetHeight) / 2;
    } elseif($intSourceRatio > $intTargetRatio) {
        $intNewWidth = ($intTargetHeight / $intSourceHeight) * $intSourceWidth;
        $intNewHeight = $intTargetHeight;
        $intNewXOffset = ($intNewWidth - $intTargetWidth) / 2;
        $intNewYOffset = 0;
    } else {
        $intNewWidth = $intTargetWidth;
        $intNewHeight = $intTargetHeight;
        $intNewXOffset = 0;
         $intNewYOffset = 0;
    }

    $gdIntermediateImage = imagecreatetruecolor($intNewWidth, $intNewHeight);

    if(!imagecopyresampled($gdIntermediateImage, $gdSourceImage, 0, 0, 0, 0, $intNewWidth, $intNewHeight, $intSourceWidth, $intSourceHeight)) {
        die(':(');
    }

    if(!imagecopy($gdTargetImage, $gdIntermediateImage, 0, 0, $intNewXOffset, $intNewYOffset, $intTargetWidth, $intTargetHeight)) {
        die(':(');
    }
}

resizeImage($gdi, 600, 900, $gd);
imagedestroy($gdi);

// Calculate font size and cutoff.
$reslen = strlen($res);
$fontmin = 16;
$fontmax = 72;
$linesmax = 3;
$imagew = imagesx($gd);
$imageh = imagesy($gd);

$fsize = 0;
$currsize = $fontmax;
$reswords = explode(' ', $res);

while (!$fsize) {
   if ($currsize < $fontmin) { die('could not place text'); }
   $reslines = array('');
   $cwcount = 0; $cwi = 0;
   while (true) {
       if ($cwi == count($reswords)) { $fsize = $currsize; break 2; }
       if ($cwcount + $currsize * (strlen($reswords[$cwi]) + 1) * 0.60 + 10 >= $imagew) {
           $cwcount = (strlen($reswords[$cwi]) + 1) * $currsize * 0.60;
           $reslines[] = $reswords[$cwi++] . ' ';
           if (count($reslines) > $linesmax) {
               $currsize -= 4;
               continue 2;
           }
       } else {
           $cwcount += (strlen($reswords[$cwi]) + 1) * $currsize * 0.60;
           $reslines[count($reslines)-1] .= $reswords[$cwi++] . ' ';
       }
   }
}

// Add barcode
require 'Image/Barcode2.php';

function add_barcode($gd, $hash, $height, $offset = 10) {
  // Create a barcode.
  $ean13 = (rand(0, 1) ? '45' : '49'); // Japan.
  $ean13 .= strtr(substr($hash, 0, 10), 'abcdef', '678942');
  
  // Checksum.
  $chk = 0;
  for ($i = 11; $i >= 0; $i--) {
    $chk += ($i % 2 ? $ean13[$i] * 3 : $ean13[$i]);
  }
  $ean13 .= strval((10 - ($chk % 10)) % 10);
		    
  // Create barcode.
  $bargd = Image_Barcode2::draw($ean13, Image_Barcode2::BARCODE_EAN13, Image_Barcode2::IMAGE_JPEG, false, $height);
  imagecopy($gd, $bargd, $offset, imagesy($gd) - $height - $offset * 2, 0, 0, imagesx($bargd), imagesy($bargd) - 8);
  imagedestroy($bargd);
}

$hash = sha1(mt_rand() . uniqid());
add_barcode($gd, $hash, 60);

// Draw.
//$yoff = rand(50, $imageh - 25 - $fsize * (1 + count($reslines)));
$rot = (($b = rand(0, 2)) == 0 ? 10 : (($b == 1) ? -10 : 0));
$yoff = $imageh - 30 - 1.33 * $fsize * (($b == 2 ? 1 : 2) + count($reslines));
$color = imagecolorexact($gd, rand(35, 255), rand(35, 255), rand(35, 255));

function draw_text($gd, $text, $font, $fsize, $color, $yoff, $rot) {
  $bb = imageftbbox($fsize, 0, $font, $text);
  $bbs = imageftbbox($fsize, 0, $font, ' ');

  $topad = (600 / cos(deg2rad($rot)) - ($bb[2] - $bb[0])) / ($bbs[2] - $bbs[0]);
  $text = str_repeat(' ', $topad / 2) . $text . str_repeat(' ', $topad / 2);
  $black = imagecolorexact($gd, 0, 0, 0);

  if ($rot && $prevwidth) {
     $distance = $prevwidth / 2;
     $yoff -= sin(deg2rad($rot)) * ($distance - ($bb[2] - $bb[0]) / 2);
  }

  imagefttext($gd, $fsize, $rot, 10 - 2, $yoff - 2, $black, $font, $text);
  imagefttext($gd, $fsize, $rot, 10 - 2, $yoff + 2, $black, $font, $text);
  imagefttext($gd, $fsize, $rot, 10 + 2, $yoff - 2, $black, $font, $text);
  imagefttext($gd, $fsize, $rot, 10 + 2, $yoff + 2, $black, $font, $text);
  imagefttext($gd, $fsize, $rot, 10 - 2, $yoff - 2, $black, $font, $text);
  imagefttext($gd, $fsize, $rot, 10, $yoff, $color, $font, $text);
}

draw_text($gd, $author, './lnfont.ttf', 24, imagecolorexact($gd, rand(25, 255), rand(35, 255), rand(35, 255)), $yoff - 10 - $fsize, $rot);

foreach ($reslines as $line) {
    $line = strtoupper($line);
    draw_text($gd, $line, './lnfont.ttf', $fsize, $color, $yoff, $rot);

    $yoff += $fsize * 1.33;
}
draw_text($gd, 'Illustration: ' . $illustrator, './lnfont.ttf', 24, imagecolorexact($gd, rand(25, 255), rand(35, 255), rand(35, 255)), $yoff - 1.33 * $fsize + 35, $rot);

// Save.
$file = 'covers/' . $hash . '.jpg';
imagejpeg($gd, $file, 80);
imagedestroy($gd);

// Save meta.
$origmeta = json_decode(file_get_contents('covers/meta.json'), true);
$origmeta[$file] = array('title' => $res, 'gelbooru_id' => $id);
file_put_contents('covers/meta.json', json_encode($origmeta));

// Redirect.
header('HTTP/1.1 302 Found');
header('Location: https://salty-salty-studios.com/shiz/lncovers.php?' . $hash);
exit();
}
?>

<!DOCTYPE html>

<html>
    <head profile="http://gmpg.org/xfn/11">
        <title><?php echo htmlentities($res); ?> | LN cover generator</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="canonical" href="https://salty-salty-studios.com/shiz/lncovers.php?<?php echo $hash; ?>" />
        <meta property="twitter:card" content="photo" />
        <meta property="twitter:image" content="https://salty-salty-studios.com/shiz/<?php echo htmlentities($file); ?>" />
        <meta property="twitter:image:width" content="600" />
        <meta property="twitter:image:height" content="900" />
        <meta property="og:image" content="https://salty-salty-studios.com/shiz/<?php echo htmlentities($file); ?>" />

        <style type="text/css">
        *, html, body, div, center, img, span, a { margin: 0; padding: 0; }
        body {
            background-image: url('covers/bg.png');
            background-repeat: repeat;
            background-attachment: fixed;
            font-family: Helvetica, Arial, sans-serif;
            color: gray;
            line-height:32px;
        }
        a {
            color: darkgray;
            text-decoration: none;
        }

        #footerl {
            position: fixed;
            bottom: 0px;
            left:0px;
            padding: 20px;
            text-align:left;
        }
        #footerr {
            position: fixed;
            bottom: 0px;
            right:0px;
            padding: 20px;
            text-align:right;
        }

        #lnimg {
            text-align:center;
            width:100%;
        }

        img {
            margin: 20px;
            border-top-left-radius: 10px;
            border-bottom-left-radius: 10px;
            box-shadow: 5px 5px 10px #000000;
        }
        .twitter-share-button {
            margin-top: 2px;
            height: 20px !important;
        }
        </style>
    </head>

    <body>
        <div id="lnimg">
            <img src="<?php echo htmlentities($file); ?>" alt="<?php echo htmlentities($res); ?>" />
        </div>
        <div id="footerl">
             <a href="lncovers.php">View new</a><br />
             <a href="http://gelbooru.com/index.php?page=post&amp;s=view&amp;id=<?php echo intval($id); ?>">Original image</a><br />
             <a href="https://twitter.com/share" class="twitter-share-button" data-url="https://salty-salty-studios.com/shiz/lncovers.php?<?php echo htmlentities($hash); ?>" data-text="<?php echo htmlentities($res); ?>" data-count="none" data-hashtags="lncovers" data-dnt="true">Tweet</a>
             <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
        </div>
        <div id="footerr">
             <a href="https://twitter.com/dev_console">@dev_console</a><br />
             <a href="https://twitter.com/deltakurshiva">@deltakurshiva</a><br />
<!--             <a href="https://twitter.com/coldacid">@coldacid</a> -->
        </div>
	<!-- Piwik -->
	<script type="text/javascript">
	var pkBaseURL = "http://piwik.salty-salty-studios.com/";
	document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
	</script><script type="text/javascript">
	try {
	var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 2);
	piwikTracker.trackPageView();
	piwikTracker.enableLinkTracking();
	} catch( err ) {}
	</script><noscript><p><img src="http://piwik.salty-salty-studios.com/piwik.php?idsite=2" style="border:0" alt="" /></p></noscript>
	<!-- End Piwik Tracking Code -->
    </body>
</html>
