<?php
$acceptParam['log'] = array(
  'suspect',
  'success',
  'other',
  'retry'
);

if (isset($ui['pwd'])) {
  checkAdmin($ui['pwd']);
}

if (isset($ui['log']) && !in_array($ui['log'], $acceptParam['log']) || $_SESSION['login'] !== true) {
  die('Tell me, Mr Anderson, what good is a phone call if you\'re unable to speak ?');
}

if (empty($ui['log']) && empty($ui['ac'])) {
  $ui['log'] = 'success';
}

function clearLog($log) {
  if (file_exists('cache/logs/'.$log.'.txt') && is_file('cache/logs/'.$log.'.txt')) {
    file_put_contents('cache/logs/'.$log.'.txt', '');
  }
}

function parseSuccessLog() {
  if (file_exists('cache/logs/success.txt')) {
    $file = fopen('cache/logs/success.txt', "r");
    $res = '';
    if (!empty($file)) {
      while (!feof($file)) {
        $currentLine = trim(fgets($file));
        $currentLine = explode(' ', $currentLine);
        $currentLine = str_replace('s', '', $currentLine);
        if (!empty($currentLine[5])) {
          $res['genTime'][] = $currentLine[5];
        }
      }
    } else {
      $res['genTime'] = array();
    }
    fclose($file);
    return $res;
  }
}

function parseFailLog($log) {
  if (empty($log) || ($log !== 'suspect' && $log !== 'retry' && $log !== 'other')) {
    die('Are you sure about this.');
  }
  $res = '';
  $list = glob('cache/logs/'.$log.'/*.log');
  if (!empty($list)) {
    foreach ($list as $value) {
      $line = file_get_contents($value);
      $line = trim($line);
      $line = explode(' --- ', $line);
      if (!empty($line[7])) {
        $res[] = array(
          $line[1],
          $line[2],
          $line[4],
          'Error '.$line[7].' - '
        );
      } else {
        $res[] = array(
          $line[1],
          $line[2],
          $line[4],
          ''
        );
      }
    }
  }
  return $res;
}

function manualGen($hash, $log) {
  $line = file_get_contents('cache/logs/'.$log.'/'.$hash.'.log');
  $line = trim($line);
  $line = explode(' --- ', $line);
  $hash = sha1($GLOBALS['config']['salt'].rawurldecode($line[1]));
  file_put_contents('cache/tmp/manual.txt', $line[1]);
  chdir('bin/');
  exec('bash thumb_server.sh manual '.escapeshellarg($hash).' '.escapeshellarg($line[3]).' '.escapeshellarg($line[4]).' 0 1', $result);
  chdir('../');
  if ((int)$result[0] === 1) {
    $res['success'] = 1;
    $res['filePath'] = pathForFile($line[4], $hash).'.png';
    return $res;
  }
}

function delAndRegen($hash, $size) {
  $path = pathForFile($size, $hash);
  if (file_exists($path.'.png')) {
    unlink($path.'.png');
  }
  if (file_exists($path.'_thumb.png')) {
    unlink($path.'_thumb.png');
  }
}

function tryRootDomain($hash, $log) {
  $line = file_get_contents('cache/logs/'.$log.'/'.$hash.'.log');
  $line = trim($line);
  $line = explode(' --- ', $line);
  $hash = sha1($GLOBALS['config']['salt'].rawurldecode($line[1]));
  $parts = parse_url($line[1]);
  $url = $parts['scheme'].'://'.trim($parts['host']);
  file_put_contents('cache/tmp/manual.txt', $url);
  chdir('bin/');
  exec('bash thumb_server.sh manual '.escapeshellarg($hash).' '.escapeshellarg($line[3]).' '.escapeshellarg($line[4]).' 0 1', $result);
  chdir('../');
  if ((int)$result[0] === 1) {
    $res['success'] = 1;
    $res['filePath'] = pathForFile($line[4], $hash).'.png';
    $res['base64'] = 'data:image/png;base64,'.base64_encode(file_get_contents($res['filePath']));
    return $res;
  }
}

function keepThisThumb($hash, $log) {
  unlink('cache/logs/'.$log.'/'.$hash.'.log');
}

if (isset($ui['clear']) && (int)$ui['clear'] === 1) {
  clearLog($ui['log']);
}
if (isset($ui['ac']) && $ui['ac'] === 'delete' && isset($ui['thumb']) && !empty($ui['thumb'])) {
  $imgUrl = pathForFile('m', $ui['thumb']);
  if (file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$imgUrl.'.png')) {
    unlink($_SERVER['DOCUMENT_ROOT'].'/'.$imgUrl.'.png');
  }
  if (file_exists($imgUrl.'_thumb.png')) {
    unlink($_SERVER['DOCUMENT_ROOT'].'/'.$imgUrl.'_thumb.png');
  }
}
echo '<div class="hMenu">
  <ul>
    <li>
      <a href="?p=admin&log=success">Success</a>
    </li>
    <li>
      <a href="?p=admin&log=suspect">Suspect</a>
    </li>
    <li>
      <a href="?p=admin&log=retry">Retry</a>
    </li>
    <li>
      <a href="?p=admin&log=other">Other error</a>
    </li>
    <li>
      <a href="?p=admin&ac=delete">Delete thumbshot</a>
    </li>
    <li>
      <a href="?logout=1">Logout</a>
    </li>
  </ul>
</div>
<div id="log">';
if (isset($ui['ac']) && $ui['ac'] === 'delete') {
  if (isset($ui['deleteUrl']) && testValidUrl($ui['deleteUrl']) !== true) {
    unset($ui['deleteUrl']);
    echo '<div>Not a valid url.</div>';
  }
  echo '
  <form method="post" action="?">
    <p>
      <label>Url </label>';
  if (empty($ui['deleteUrl'])) {
    echo '<input type="text" name="deleteUrl"/>';
  } else {
    echo '<input type="text" name="deleteUrl" value="', $ui['deleteUrl'], '"/>';
  }
  echo '</p>
    <p>
      <input type="hidden" name="p" value="admin"/>
      <input type="hidden" name="ac" value="delete"/>
      <input type="submit"/>
    </p>
  </form>';
  if (!empty($ui['deleteUrl'])) {
    $ui['deleteUrl'] = trim(rawurldecode($ui['deleteUrl']));
    $ui['deleteUrl'] = rtrim($ui['deleteUrl'], '/');
    $hashUrl = sha1($GLOBALS['config']['salt'].$ui['deleteUrl']);
    $imgUrl = pathForFile('m', $hashUrl);
    echo '</div>
    <div id="result">
      <p>
        <a href="', $imgUrl, '.png"><img src="', $imgUrl, '_thumb.png"/></a>
      </p>
      <a href="?p=admin&amp;ac=delete&amp;thumb=', $hashUrl, '">Delete this thumb</a>
    </div>';
  }

}
if (isset($ui['log']) && $ui['log'] === 'success') {
  $logs = parseSuccessLog();
  if (!empty($logs)) {
    $nbThumb = 0;
    $nbThumb = count($logs['genTime']);
    echo 'Total request : ', $nbThumb, '</br>';
    echo 'Moyenne per request : ', round(array_sum($logs['genTime']) / $nbThumb, 2), 's  (min (', min($logs['genTime']), 's) max (', max($logs['genTime']), 's))</br>';
  } else {
    echo 'No result';
  }
  echo '<p class="clear" ><a href="?p=admin&log=success&clear=1">Clear success log</a></p>';
}
if (isset($ui['log']) && ($ui['log'] === 'suspect' || $ui['log'] === 'retry' || $ui['log'] === 'other')) {
  if (isset($ui['hash']) && !empty($ui['hash'])) {
    $ui['hash'] = validHash($ui['hash']);
    if (isset($ui['root']) && (int)$ui['root'] === 1) {
      $success = tryRootDomain($ui['hash'], $ui['log']);
    }
    if (isset($ui['cache']) && (int)$ui['cache'] === 1) {
      $success['filePath'] = pathForFile($ui['s'], $ui['hash']).'.png';
      $success['base64'] = 'data:image/png;base64,'.base64_encode(file_get_contents($success['filePath']));
      if (!file_exists($success['filePath'])) {
        $success['base64'] = 'data:image/png;base64,'.base64_encode(file_get_contents('bin/error.png'));
      }
    }
    if (isset($ui['keep']) && (int)$ui['keep'] === 1) {
      keepThisThumb($ui['hash'], $ui['log']);
    }
    if (isset($ui['mGen']) && (int)$ui['mGen'] === 1)
      $success = manualGen($ui['hash'], $ui['log']);
  }
  $logs = parseFailLog($ui['log']);
  if (!empty($logs)) {
    echo '<ul>';
    foreach ($logs as $value) {
      echo '<li>', htmlentities(strip_tags($value['3'])), htmlentities(strip_tags($value['0'])), '</br><a href="?p=admin&log=', $ui['log'], '&hash=', $value['1'], '&mGen=1#result">manuel launch</a> <a href="', htmlentities(strip_tags($value['0'])), '">view site</a> <a href="?p=admin&log=', $ui['log'], '&hash=', $value['1'], '&cache=1&s=', $value['2'], '#result">view image in cache</a></li>';
    }
    echo '</ul>';
  } else {
    echo 'No result';
  }
}
echo '</div>';
if (!empty($success)) {
  echo '<div id="result">';
  echo '<img src="', $success['base64'], '" style="width:100%;"/>';
  echo '<p><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['filePath'], '" onclick="this.select()"/></p>';
  echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&root=1">Try with root domain</a> / ';
  echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&keep=1">Keep this thumbshot</a>';
  echo '</div>';
}
?>