<?php

include dirname(__FILE__) . '/session.php';
include dirname(__FILE__) . '/dbconfig.php';
include dirname(__FILE__) . '/utils.php';

function check() {
check_session();

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET CHARACTER SET 'utf8'");
$dbh = new PDO(DB_DSN, DB_USER, DB_PASSWORD, $options);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "SELECT ftp.* FROM userdata as u INNER JOIN ftp ON ftp.id=u.id AND ftp.del_flg='0' WHERE u.id=? AND u.del_flg='0'";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($_SESSION['usr_id']));

$account = $stmt->fetch(PDO::FETCH_ASSOC);

$top = $account['dir'];
if (empty($top)) {
  $top = '/var/www/html';
}

$data = file_get_contents('php://input');
if (empty($data)) {
  exit(0);
}

$params = json_decode($data,true);

$dir = $params['dir'];
$list = $params['list'];
$tz = 'UTC';
if (isset($_SESSION['tzoff'])) {
  $of = intval($_SESSION['tzoff']);
  $sign = '+';
  if ($of < 0) {
    $sign = '-';
    $of   = -$of;
  }
  $hour = intval($of/60);
  $min  = $of-$hour*60;
  $tz = sprintf('GMT%s%02d:%02d',$sign,$hour,$min);
}
$name = trim("GRM_B_" . `TZ='$tz' date +'%Y%m%d%H%M%S'`);

if (empty($dir)) {
  $dir = '/';
}
$wd = $top  .$dir;
$files  = array();
foreach($list as $item) {
  if ($item != "..") {
    $folder = '';
    if (isset($item['folder'])) {
        $folder = $item['folder'];
        if ($folder === '/') {
            $folder = '';
        }
    }
    if (file_exists($wd . '/' . $folder . $item['name'])) {
      $files[]  = "./" . $folder . $item['name'];
    }
  }
}
$lock_inodes = array();
$lock_files  = array();
$cmd = "cd $wd; find '" . join("' '",$files) . '\' -printf "%i %p\n"';
$p = popen($cmd, "r");
while(($line=fgets($p)) !== false) {
  if (preg_match('/^([0-9]+) (.*)$/',$line,$m)){
    $lock_inodes[] = $m[1];
    $lock_files[]  = str_replace($top, '', realpath("$wd/" . $m[2]));
  }
}
pclose($p);

$top = rtrim($top, '/') . '/';
with_lock($top, $lock_inodes, $lock_files, '0', function() use($dbh, $name,$top,$wd,$tz,$files,$lock_inodes, $lock_files) {
  $pass  = bin2hex(openssl_random_pseudo_bytes(8));

  $params = json_encode(array(
    'name'   => $name . '.zip',
#    'cmd'    => "cd '$dir'; cat $temp | TZ='$tz' zip -r -J -@ - ",
    'top'    => $top,
    'path'   => $wd,
    'tz'     => $tz,
    'files'  => $files,
    'pass'   => $pass,
    'lock'   => array('inodes' => $lock_inodes, 'files' => $lock_files)
  ));

   $sql  = "INSERT INTO download (params) VALUES (?)";
   $stmt = $dbh->prepare($sql);
   $stmt->execute(array($params));
   $stmt = $dbh->prepare("SELECT LAST_INSERT_ID() as id");
   $stmt->execute();
   $row = $stmt->fetch(PDO::FETCH_ASSOC);
   $id  = $row['id'];

   setcookie('GRMONEDL', $pass, 0, '/');

   echo json_encode(array('url' => '/cgi-bin/downloadZip.cgi/' . $id . '/' . $name . '.zip'));
}, function() {
  echo json_encode(array('error' => _('アップロード中のファイルが含まれるためダウンロードできません。')));
});
}

wrap('check');
