1: | <?php
|
2: | |
3: | |
4: | |
5: | |
6: | |
7: | |
8: | |
9: | |
10: |
|
11: | namespace Opencart\System\Library;
|
12: | |
13: | |
14: | |
15: | |
16: |
|
17: | class Response {
|
18: | |
19: | |
20: |
|
21: | private array $headers = [];
|
22: | |
23: | |
24: |
|
25: | private int $level = 0;
|
26: | |
27: | |
28: |
|
29: | private string $output = '';
|
30: |
|
31: | |
32: | |
33: | |
34: | |
35: |
|
36: | public function addHeader(string $header): void {
|
37: | $this->headers[] = $header;
|
38: | }
|
39: |
|
40: | |
41: | |
42: | |
43: | |
44: |
|
45: | public function getHeaders(): array {
|
46: | return $this->headers;
|
47: | }
|
48: |
|
49: | |
50: | |
51: | |
52: | |
53: | |
54: | |
55: | |
56: |
|
57: | public function redirect(string $url, int $status = 302): void {
|
58: | header('Location: ' . str_replace(['&', "\n", "\r"], ['&', '', ''], $url), true, $status);
|
59: | exit();
|
60: | }
|
61: |
|
62: | |
63: | |
64: | |
65: | |
66: | |
67: | |
68: |
|
69: | public function setCompression(int $level): void {
|
70: | $this->level = $level;
|
71: | }
|
72: |
|
73: | |
74: | |
75: | |
76: | |
77: | |
78: | |
79: |
|
80: | public function setOutput(string $output): void {
|
81: | $this->output = $output;
|
82: | }
|
83: |
|
84: | |
85: | |
86: | |
87: | |
88: |
|
89: | public function getOutput(): string {
|
90: | return $this->output;
|
91: | }
|
92: |
|
93: | |
94: | |
95: | |
96: | |
97: | |
98: | |
99: | |
100: |
|
101: | private function compress(string $data, int $level = 0): string {
|
102: | if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false)) {
|
103: | $encoding = 'gzip';
|
104: | }
|
105: |
|
106: | if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false)) {
|
107: | $encoding = 'x-gzip';
|
108: | }
|
109: |
|
110: | if (!isset($encoding) || ($level < -1 || $level > 9)) {
|
111: | return $data;
|
112: | }
|
113: |
|
114: | if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
|
115: | return $data;
|
116: | }
|
117: |
|
118: | if (headers_sent()) {
|
119: | return $data;
|
120: | }
|
121: |
|
122: | if (connection_status()) {
|
123: | return $data;
|
124: | }
|
125: |
|
126: | $this->addHeader('Content-Encoding: ' . $encoding);
|
127: |
|
128: | return gzencode($data, $level);
|
129: | }
|
130: |
|
131: | |
132: | |
133: | |
134: | |
135: | |
136: | |
137: |
|
138: | public function output(): void {
|
139: | if ($this->output) {
|
140: | $output = $this->level ? $this->compress($this->output, $this->level) : $this->output;
|
141: |
|
142: | if (!headers_sent()) {
|
143: | foreach ($this->headers as $header) {
|
144: | header($header, true);
|
145: | }
|
146: | }
|
147: |
|
148: | echo $output;
|
149: | }
|
150: | }
|
151: | }
|
152: | |