@*--<?php
class Chunk 
{
    public $UPLOAD_PATH;

    private $_lastChunk = null;
    private $_chunkFolder = '';
    private $_lockFile = '';
    private $_isLast = false;

    public function __construct() 
    {
        $this->UPLOAD_PATH = dirname(__FILE__) . '/';
        $this->_chunkFolder = $this->UPLOAD_PATH . 'default';
    }

    public function save($info) 
    {
        $validationResult = $this->validate($info);
        if ('' !== $validationResult)
            exit('error:' . $validationResult);

        $this->_lastChunk = $info;
        $this->_chunkFolder = $this->UPLOAD_PATH . $info['id'];
        $this->_lockFile = $this->_chunkFolder . '/lock';

        if (!is_dir($this->_chunkFolder)) {
            mkdir($this->_chunkFolder, 0777, true);
        }

        $f = fopen($this->_lockFile, 'c');

        if (flock($f, LOCK_EX)) {
            $chunks = array_diff(scandir($this->_chunkFolder), array('.', '..', 'lock'));

            if ((int) $this->_lastChunk['total'] === count($chunks) + 1) {
                $this->_isLast = true;
            }
            file_put_contents($this->_chunkFolder . '/' . (int) $info['current'], $info['content']);

            flock($f, LOCK_UN);
        } else {
            exit(json_encode(array('response' => 'error:Couldn\'t lock the file')));
        }
    }

    public function last() 
    {
        return $this->_isLast;
    }

    public function complete() 
    {
        $content = '';
        for ($i = 1, $count = (int) $this->_lastChunk['total']; $i <= $count; $i++) {
            if (!file_exists($this->_chunkFolder . "/$i"))
                exit(json_encode(array('response' => 'error:Missing chunk #' . $i . ' : ' . implode(' / ', scandir($this->_chunkFolder)))));
            $content .= file_get_contents($this->_chunkFolder . "/$i");
        }
        Helper::removeDir($this->_chunkFolder);
        return $content;
    }

    public function validate($info) 
    {
        $errors = array();
        if (!isset($info['id']) || !$info['id'])
            $errors[] = 'Invalid id';
        if (!isset($info['total']) || (int) $info['total'] < 1)
            $errors[] = 'Invalid chunks total';
        if (!isset($info['current']) || (int) $info['current'] < 1)
            $errors[] = 'Invalid current chunk number';
        if (!isset($info['content']) || !strlen($info['content']))
            $errors[] = 'Invalid chunk content';
        if (count($errors) < 1)
            return '';
        else
            return  implode(', ', $errors);
    }
}--*@