Failed Conditions
Pull Request — master (#4274)
by Owen
13:07
created

Drawing::getPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4
5
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
6
use ZipArchive;
7
8
class Drawing extends BaseDrawing
9
{
10
    const IMAGE_TYPES_CONVERTION_MAP = [
11
        IMAGETYPE_GIF => IMAGETYPE_PNG,
12
        IMAGETYPE_JPEG => IMAGETYPE_JPEG,
13
        IMAGETYPE_PNG => IMAGETYPE_PNG,
14
        IMAGETYPE_BMP => IMAGETYPE_PNG,
15
    ];
16
17
    /**
18
     * Path.
19
     */
20
    private string $path;
21
22
    /**
23
     * Whether or not we are dealing with a URL.
24
     */
25
    private bool $isUrl;
26
27
    /**
28
     * Create a new Drawing.
29
     */
30 193
    public function __construct()
31
    {
32
        // Initialise values
33 193
        $this->path = '';
34 193
        $this->isUrl = false;
35
36
        // Initialize parent
37 193
        parent::__construct();
38
    }
39
40
    /**
41
     * Get Filename.
42
     */
43 1
    public function getFilename(): string
44
    {
45 1
        return basename($this->path);
46
    }
47
48
    /**
49
     * Get indexed filename (using image index).
50
     */
51 45
    public function getIndexedFilename(): string
52
    {
53 45
        return md5($this->path) . '.' . $this->getExtension();
54
    }
55
56
    /**
57
     * Get Extension.
58
     */
59 45
    public function getExtension(): string
60
    {
61 45
        $exploded = explode('.', basename($this->path));
62
63 45
        return $exploded[count($exploded) - 1];
64
    }
65
66
    /**
67
     * Get full filepath to store drawing in zip archive.
68
     */
69 3
    public function getMediaFilename(): string
70
    {
71 3
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
72 1
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
73
        }
74
75 3
        return sprintf('image%d%s', $this->getImageIndex(), $this->getImageFileExtensionForSave());
76
    }
77
78
    /**
79
     * Get Path.
80
     */
81 116
    public function getPath(): string
82
    {
83 116
        return $this->path;
84
    }
85
86
    /**
87
     * Set Path.
88
     *
89
     * @param string $path File path
90
     * @param bool $verifyFile Verify file
91
     * @param ?ZipArchive $zip Zip archive instance
92
     *
93
     * @return $this
94
     */
95 103
    public function setPath(string $path, bool $verifyFile = true, ?ZipArchive $zip = null): static
96
    {
97 103
        $this->isUrl = false;
98 103
        if (preg_match('~^data:image/[a-z]+;base64,~', $path) === 1) {
99 4
            $this->path = $path;
100
101 4
            return $this;
102
        }
103
104 101
        $this->path = '';
105
        // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979
106 101
        if (filter_var($path, FILTER_VALIDATE_URL)) {
107 2
            if (!preg_match('/^(http|https|file|ftp|s3):/', $path)) {
108 2
                throw new PhpSpreadsheetException('Invalid protocol for linked drawing');
109
            }
110
            // Implicit that it is a URL, rather store info than running check above on value in other places.
111
            $this->isUrl = true;
112
            $ctx = null;
113
            $imageContents = false;
114
            if (str_starts_with($path, 'https:') && function_exists('curl_init')) {
115
                $curlparam = curl_init($path);
116
                if ($curlparam !== false) {
117
                    curl_setopt($curlparam, CURLOPT_RETURNTRANSFER, 1);
118
                    curl_setopt($curlparam, CURLOPT_TIMEOUT, 30);
119
                    curl_setopt($curlparam, CURLOPT_SSL_VERIFYPEER, false);
120
                    $imageContents = curl_exec($curlparam);
121
                    curl_close($curlparam);
122
                }
123
            } else {
124
                // https://github.com/php/php-src/issues/16023
125
                if (str_starts_with($path, 'https:')) {
126
                    $ctx = stream_context_create(['ssl' => ['crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT]]);
127
                }
128
                $imageContents = @file_get_contents($path, false, $ctx);
129
            }
130
            if ($imageContents !== false) {
131
                $filePath = tempnam(sys_get_temp_dir(), 'Drawing');
132
                if ($filePath) {
133
                    $put = @file_put_contents($filePath, $imageContents);
134
                    if ($put !== false) {
135
                        if ($this->isImage($filePath)) {
136
                            $this->path = $path;
137
                            $this->setSizesAndType($filePath);
138
                        }
139
                        unlink($filePath);
140
                    }
141
                }
142
            }
143 99
        } elseif ($zip instanceof ZipArchive) {
144 62
            $zipPath = explode('#', $path)[1];
145 62
            $locate = @$zip->locateName($zipPath);
146 62
            if ($locate !== false) {
147 62
                if ($this->isImage($path)) {
148 62
                    $this->path = $path;
149 62
                    $this->setSizesAndType($path);
150
                }
151
            }
152
        } else {
153 51
            $exists = @file_exists($path);
154 51
            if ($exists !== false && $this->isImage($path)) {
155 49
                $this->path = $path;
156 49
                $this->setSizesAndType($path);
157
            }
158
        }
159 99
        if ($this->path === '' && $verifyFile) {
160 1
            throw new PhpSpreadsheetException("File $path not found!");
161
        }
162
163 98
        if ($this->worksheet !== null) {
164 2
            if ($this->path !== '') {
165 2
                $this->worksheet->getCell($this->coordinates);
166
            }
167
        }
168
169 98
        return $this;
170
    }
171
172 97
    private function isImage(string $path): bool
173
    {
174 97
        $mime = (string) @mime_content_type($path);
175 97
        $retVal = false;
176 97
        if (str_starts_with($mime, 'image/')) {
177 96
            $retVal = true;
178 3
        } elseif ($mime === 'application/octet-stream') {
179 2
            $extension = pathinfo($path, PATHINFO_EXTENSION);
180 2
            $retVal = in_array($extension, ['bin', 'emf'], true);
181
        }
182
183 97
        return $retVal;
184
    }
185
186
    /**
187
     * Get isURL.
188
     */
189 43
    public function getIsURL(): bool
190
    {
191 43
        return $this->isUrl;
192
    }
193
194
    /**
195
     * Set isURL.
196
     *
197
     * @return $this
198
     */
199
    public function setIsURL(bool $isUrl): self
200
    {
201
        $this->isUrl = $isUrl;
202
203
        return $this;
204
    }
205
206
    /**
207
     * Get hash code.
208
     *
209
     * @return string Hash code
210
     */
211 43
    public function getHashCode(): string
212
    {
213 43
        return md5(
214 43
            $this->path
215 43
            . parent::getHashCode()
216 43
            . __CLASS__
217 43
        );
218
    }
219
220
    /**
221
     * Get Image Type for Save.
222
     */
223 1
    public function getImageTypeForSave(): int
224
    {
225 1
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
226 1
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
227
        }
228
229 1
        return self::IMAGE_TYPES_CONVERTION_MAP[$this->type];
230
    }
231
232
    /**
233
     * Get Image file extention for Save.
234
     */
235 3
    public function getImageFileExtensionForSave(bool $includeDot = true): string
236
    {
237 3
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
238 1
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
239
        }
240
241 3
        $result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot);
242
243 3
        return "$result";
244
    }
245
246
    /**
247
     * Get Image mime type.
248
     */
249 3
    public function getImageMimeType(): string
250
    {
251 3
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
252 1
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
253
        }
254
255 3
        return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]);
256
    }
257
}
258