summaryrefslogtreecommitdiff
path: root/PHP_DW.php
blob: d1190820398bf94a1a89752fc0524338ffab5f20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php

class PHP_DW {
    private $dw_dir = 'downloads';
    private $cnt_dir = '.count';

    function __construct($dw_dir = false, $cnt_dir = false) {

        if ($dw_dir) {
            $this->dw_dir = $dw_dir;
        }

        if ($cnt_dir) {
            $this->cnt_dir = $cnt_dir;
        }
    }

    private function __get_full_path($path) {
        if (basename($path) !== $path) {
            return null;
        }

        return $this->dw_dir . '/' . $path;
    }

    private function __incr_count($filename) {
        $fh = @fopen($this->cnt_dir . '/' . $filename . '.cnt', "a+");

        if (is_resource($fh) and flock($fh, LOCK_EX)) {
            rewind($fh);

            $count = fgets($fh);

            if ($count === false)
                $count = 0;

            $count++;

            ftruncate($fh, 0);
            fwrite($fh, $count);

            flock($fh, LOCK_UN);

            fclose($fh);
        }
    }

    public function download($filename) {
        $path = $this->__get_full_path($filename) or die('invalid file');

        $ret = @readfile($path);
        if ($ret) {
            header('Content-Description: File Transfer');
            header('Content-Disposition: attachment; filename=' . $filename);
            header('Content-Length: '. filesize($path));
            header('Cache-Control: must-revalidate');

            $this->__incr_count($filename);
        } else {
            die('no such file or directory');
        }
    }

    public function get_count($filename) {
        if (!$this->__get_full_path($filename))
            return 0;

        $fh = @fopen($this->cnt_dir . '/' . $filename . '.cnt', "r");

        if (!is_resource($fh))
            return 0;

        $count = fgets($fh) or '0';

        fclose($fh);

        return $count;
    }

    public function get_count_dir() {
        return $this->cnt_dir;
    }

    public function get_download_dir() {
        return $this->dw_dir;
    }
}
?>