<?php

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

function upload() {
check_session();

$locale = getCurrentLang();

$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 u.member_id,ftp.*,cap.capacity FROM userdata as u INNER JOIN ftp ON ftp.id=u.id AND ftp.del_flg='0' INNER JOIN capacity_master as cap on cap.id=u.capacity 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';
}
if (!preg_match('"/$"', $top)) {
  $top .= '/';
}
$member_id = $account['member_id'];

$dir = '';

if (isset($_POST['dir'])) {
  $dir = $_POST['dir'];
}
$req = array( 'top' => $top, 'dir' => $dir, 'locale' => $locale );

$sql = "SELECT u.*, cap.gb as capacity_gb FROM userdata as u inner join capacity_master as cap on cap.id=u.capacity WHERE u.member_id=?";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($member_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);

$req['file_number'] = $result['file'];
$req['use_data'] = $result['use_data'];
$req['use_data_disp'] = convUseData($result['use_data']);
$req['cap_per'] = calcCapPercent($result);
$req['lim'] = $account['capacity'];

$currentDir = realpath($req['top'] . $req['dir']);
$currentDir = str_replace(realpath($req['top']),'',$currentDir);

$_SESSION['dir'] = $currentDir;

$files = array();
$error = array();
$size  = $req['use_data'];
foreach($_FILES as $key => $file) {
    if (is_uploaded_file($file['tmp_name'])){
        if (filesize($file['tmp_name']) == $file['size']) {
 	    $files[] = $file;
	    $size += $file['size'];
	} else {
	    $error[] = $file['name'];
	}
    } else {
      $error[] = $file['name'];
    }
}
if (empty($files)) {
    $result = array(
        'error' => _('empty upload')
    );
} else if ($size >= $req['lim']) {
    $result = array(
        'error' => _('limit over')
    );
}else{
    $req['files'] = $files;
    $req['error'] = $error;

    $reqs = bin2hex(json_encode($req));

    $fp = popen("LANG=ja_JP.utf-8 /var/www/html/bin/putfiles.sh $reqs", "r");
    $out = stream_get_contents($fp);
    pclose($fp);
    $result = json_decode($out,true);
    if ($result['error']) {
      $result['error'] = _('upload failed: ').$result['error'];
    }
    include dirname(__FILE__) . '/update_info.php';
}
echo json_encode($result);
}

header('Content-Type: application/json');
wrap('upload');
