-
Notifications
You must be signed in to change notification settings - Fork 3
/
File.php
383 lines (340 loc) · 10.7 KB
/
File.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<?php
/**
* Upload
*
* @author Josh Lockhart <[email protected]>
* @copyright 2012 Josh Lockhart
* @link http://www.joshlockhart.com
* @version 1.0.0
*
* MIT LICENSE
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Upload;
/**
* File
*
* This class provides the implementation for an uploaded file. It exposes
* common attributes for the uploaded file (e.g. name, extension, media type)
* and allows you to attach validations to the file that must pass for the
* upload to succeed.
*
* @author Josh Lockhart <[email protected]>
* @since 1.0.0
* @package Upload
*/
class File extends \SplFileInfo
{
/********************************************************************************
* Static Properties
*******************************************************************************/
/**
* Upload error code messages
* @var array
*/
protected static $errorCodeMessages = array(
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk',
8 => 'A PHP extension stopped the file upload'
);
/**
* Lookup hash to convert file units to bytes
* @var array
*/
protected static $units = array(
'b' => 1,
'k' => 1024,
'm' => 1048576,
'g' => 1073741824
);
/********************************************************************************
* Instance Properties
*******************************************************************************/
/**
* Storage delegate
* @var \Upload\Storage\Base
*/
protected $storage;
/**
* Validations
* @var array[\Upload\Validation\Base]
*/
protected $validations;
/**
* Validation errors
* @var array
*/
protected $errors;
/**
* Original file name provided by client (for internal use only)
* @var string
*/
protected $originalName;
/**
* File name (without extension)
* @var string
*/
protected $name;
/**
* File extension (without leading dot)
* @var string
*/
protected $extension;
/**
* File mimetype (e.g. "image/png")
* @var string
*/
protected $mimetype;
/**
* Upload error code (for internal use only)
* @var int
* @link http://www.php.net/manual/en/features.file-upload.errors.php
*/
protected $errorCode;
/**
* Constructor
* @param string $key The file's key in $_FILES superglobal
* @param \Upload\Storage\Base $storage The method with which to store file
* @throws \Upload\Exception\UploadException If file uploads are disabled in the php.ini file
* @throws \InvalidArgumentException If $_FILES key does not exist
*/
public function __construct($key, \Upload\Storage\Base $storage)
{
if (!isset($_FILES[$key])) {
throw new \InvalidArgumentException('Fehler beim Dateiupload. Die erwartete Datei kam nicht am Server an, oder ist falsch benannt. Erwartet: '.htmlentities($key));
}
if ($_FILES[$key]['error'] !== UPLOAD_ERR_OK)
throw new \InvalidArgumentException('Fehler beim Dateiupload. Nummer: '.$_FILES[$key]['error'].' - siehe http://www.php.net/manual/de/features.file-upload.errors.php');
$this->storage = $storage;
$this->validations = array();
$this->errors = array();
$this->originalName = $_FILES[$key]['name'];
$this->errorCode = $_FILES[$key]['error'];
parent::__construct($_FILES[$key]['tmp_name']);
}
/**
* Get name
* @return string
*/
public function getName()
{
if (!isset($this->name)) {
$this->name = pathinfo($this->originalName, PATHINFO_FILENAME);
}
return $this->name;
}
/**
* Set name (without extension)
* @param string $name
* @return \Upload\File Self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get file name with extension
* @return string
*/
public function getNameWithExtension()
{
return sprintf('%s.%s', $this->getName(), $this->getExtension());
}
/**
* Get file extension (without leading dot)
* @return string
*/
public function getExtension()
{
if (!isset($this->extension)) {
$this->extension = strtolower(pathinfo($this->originalName, PATHINFO_EXTENSION));
}
return $this->extension;
}
/**
* Get mimetype
* @return string
*/
public function getMimetype()
{
if (!isset($this->mimeType)) {
$finfo = \finfo_open(FILEINFO_MIME);
$mimetype = \finfo_file($finfo, $this->getPathname());
$mimetypeParts = preg_split('/\s*[;,]\s*/', $mimetype);
$this->mimetype = strtolower($mimetypeParts[0]);
unset($finfo);
}
return $this->mimetype;
}
/**
* Get md5
* @return string
*/
public function getMd5()
{
return md5_file($this->getPathname());
}
/**
* Get image dimensions
* @return array formatted array of dimensions
*/
public function getDimensions()
{
list($width, $height) = getimagesize($this->getPathname());
return array(
'width' => $width,
'height' => $height
);
}
/********************************************************************************
* Validate
*******************************************************************************/
/**
* Add file validations
* @param \Upload\Validation\Base|array[\Upload\Validation\Base] $validations
*/
public function addValidations($validations)
{
if (!is_array($validations)) {
$validations = array($validations);
}
foreach ($validations as $validation) {
if ($validation instanceof \Upload\Validation\Base) {
$this->validations[] = $validation;
}
}
}
/**
* Get file validations
* @return array[\Upload\Validation\Base]
*/
public function getValidations()
{
return $this->validations;
}
/**
* Validate file
* @return bool True if valid, false if invalid
*/
public function validate()
{
// Validate is uploaded OK
if ($this->isOk() === false) {
$this->errors[] = self::$errorCodeMessages[$this->errorCode];
}
// Validate is uploaded file
if ($this->isUploadedFile() === false) {
$this->errors[] = 'The uploaded file was not sent with a POST request';
}
// User validations
foreach ($this->validations as $validation) {
if ($validation->validate($this) === false) {
$this->errors[] = $validation->getMessage();
}
}
return empty($this->errors);
}
/**
* Get file validation errors
* @return array[String]
*/
public function getErrors()
{
return $this->errors;
}
/**
* Add file validation error
* @param string
* @return \Upload\File Self
*/
public function addError($error)
{
$this->errors[] = $error;
return $this;
}
/********************************************************************************
* Upload
*******************************************************************************/
/**
* Upload file (delegated to storage object)
* @param string $newName Give the file it a new name
* @return bool
* @throws \Upload\Exception\UploadException If file does not validate
*/
public function upload($newName = null)
{
if ($this->validate() === false) {
throw new \Upload\Exception\UploadException('File validation failed');
}
// Update the name, leaving out the extension
if (is_string($newName)) {
$this->name = pathinfo($newName, PATHINFO_FILENAME);
}
return $this->storage->upload($this, $newName);
}
/********************************************************************************
* Helpers
*******************************************************************************/
/**
* Is this file uploaded with a POST request?
*
* This is a separate method so that it can be stubbed in unit tests to avoid
* the hard dependency on the `is_uploaded_file` function.
*
* @return bool
*/
public function isUploadedFile()
{
return is_uploaded_file($this->getPathname());
}
/**
* Is this file OK?
*
* This method inspects the upload error code to see if the upload was
* successful or if it failed for a variety of reasons.
*
* @link http://www.php.net/manual/en/features.file-upload.errors.php
* @return bool
*/
public function isOk()
{
return ($this->errorCode === UPLOAD_ERR_OK);
}
/**
* Convert human readable file size (e.g. "10K" or "3M") into bytes
* @param string $input
* @return int
*/
public static function humanReadableToBytes($input)
{
$number = (int)$input;
$unit = strtolower(substr($input, -1));
if (isset(self::$units[$unit])) {
$number = $number * self::$units[$unit];
}
return $number;
}
}