1<?php
2/**
3 * Provides upload functionalities for the import plugins
4 */
5
6declare(strict_types=1);
7
8namespace PhpMyAdmin\Plugins\Import\Upload;
9
10use PhpMyAdmin\Import\Ajax;
11use PhpMyAdmin\Plugins\UploadInterface;
12use function array_key_exists;
13use function function_exists;
14use function trim;
15use function uploadprogress_get_info;
16
17/**
18 * Implementation for upload progress
19 */
20class UploadProgress implements UploadInterface
21{
22    /**
23     * Gets the specific upload ID Key
24     *
25     * @return string ID Key
26     */
27    public static function getIdKey()
28    {
29        return 'UPLOAD_IDENTIFIER';
30    }
31
32    /**
33     * Returns upload status.
34     *
35     * This is implementation for upload progress
36     *
37     * @param string $id upload id
38     *
39     * @return array|null
40     */
41    public static function getUploadStatus($id)
42    {
43        global $SESSION_KEY;
44
45        if (trim($id) == '') {
46            return null;
47        }
48
49        if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
50            $_SESSION[$SESSION_KEY][$id] = [
51                'id'       => $id,
52                'finished' => false,
53                'percent'  => 0,
54                'total'    => 0,
55                'complete' => 0,
56                'plugin'   => self::getIdKey(),
57            ];
58        }
59        $ret = $_SESSION[$SESSION_KEY][$id];
60
61        if (! Ajax::progressCheck() || $ret['finished']) {
62            return $ret;
63        }
64
65        $status = null;
66        // @see https://pecl.php.net/package/uploadprogress
67        if (function_exists('uploadprogress_get_info')) {
68            $status = uploadprogress_get_info($id);
69        }
70
71        if ($status) {
72            if ($status['bytes_uploaded'] == $status['bytes_total']) {
73                $ret['finished'] = true;
74            } else {
75                $ret['finished'] = false;
76            }
77            $ret['total'] = $status['bytes_total'];
78            $ret['complete'] = $status['bytes_uploaded'];
79
80            if ($ret['total'] > 0) {
81                $ret['percent'] = $ret['complete'] / $ret['total'] * 100;
82            }
83        } else {
84            $ret = [
85                'id'       => $id,
86                'finished' => true,
87                'percent'  => 100,
88                'total'    => $ret['total'],
89                'complete' => $ret['total'],
90                'plugin'   => self::getIdKey(),
91            ];
92        }
93
94        $_SESSION[$SESSION_KEY][$id] = $ret;
95
96        return $ret;
97    }
98}
99