<?php

include('myUtility.class.php');

function recreateThumb($id, $width, $height, $file, $thumb) {
  if (file_exists($thumb) && filesize($thumb) > 0) return;
  if (!file_exists($file) || filesize($file) == 0) return;

  $path = substr($thumb, 0, strrpos($thumb, '/'));
  if (!file_exists($path)) {
    echo "mkdir $path\n";
    mkdir($path, 0777, true);
  }
  if (myUtility::SizeImage($width, $height, $file, $thumb)) {
    echo "create $id $thumb\n";
    global $count;
    $count++;
  }
}

$count = 0;
umask(0);
for ($c = $argv[1]; $c <= $argv[2]; $c++) {
  $start = $c * 1000;
  $end = ($c+1) * 1000;

  echo "Check from $start to $end\n";
  $dbh = new PDO('mysql:host=115.84.178.137;dbname=tvtl', 'tvtl2007', 'tVtL2007remote', array( PDO::ATTR_PERSISTENT => false));
  $stmt = $dbh->prepare(
    "select doc_id, doc_category, doc_filename, doc_width, doc_height from tbldocument ".
    "where doc_type in ('jpg','jpeg','gif','png','bmp') ".
    "and doc_status<2 and doc_id>=$start and doc_id<$end");
  $stmt->execute();

  while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
    list($doc_id, $doc_cat, $doc_file, $doc_w, $doc_h) = array_values($row);
    if ($doc_id==780218 || $doc_id==890108) continue;
    $upload = "/srv/www/tvtl/web/uploads";
    $file   = "$upload/resources/$doc_cat/$doc_file";
    $thumb  = "$upload/thumbnails/$doc_cat/thumbnails/$doc_file.jpg";
    $thumb2 = "$upload/thumbnails/$doc_cat/thumbnails2/$doc_file.jpg";
    recreateThumb($doc_id, 150, 100, $file, $thumb);
    if ($doc_w > 300 || $doc_h > 300)
      recreateThumb($doc_id, 300, 300, $file, $thumb2);
  }
}
echo "\nFinish convert $count files\n\n";
