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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
| <?php
/**
* class Upload
* Version 1.0.0 (30/06/22)
* Author moimp
* Based on https://github.com/grunk/Pry/blob/fa3104194aeec40c416e53f742f1ad4575561f13/Pry/File/Upload.php#L206
* Documentation on https://github.com/grunk/Pry/tree/master/doc
namespace Upload;
require_once('FileTools.php');
require_once('StringTools.php');
use FileTools\FileTools;
use StringTools\StringTools;
/**
* Class to upload multiple files.
* Optional use of finfo or mimemagic (see https://rubygems.org/gems/mimemagic?locale=fr)
*/
class Upload
{
const MIME_CHECK_BROWSER = 1;
const MIME_CHECK_FINFO = 2;
const MIME_CHECK_MIMETYPE = 3;
const MIME_CHECK_NONE = 4;
const REQUIRE_ALL = 1;
const REQUIRE_YES = 2;
const REQUIRE_NO = 3;
const WMODE_OVERWRITE = 1;
const WMODE_COPY = 2;
const WMODE_CANCEL = 3;
/*
/**
* Max filesize in bytes
* @var int
*/
private $maxFileSize;
/**
* Targetpath for uploaded files
* @var string
*/
private $uploadDir;
/**
* Path to magicmime file
* @var string
*/
private $magicFile;
/**
* Mime: check type
* @var int
*/
private $mimetypeCheck;
/**
* Writemode for uploading files
* @var int
*/
private $writeMode;
/**
* Secure mode or not
* @var boolean
*/
private $secureMode;
/**
* File required or not
* @var int
*/
private $required;
/**
* Allowed extensions
* @var array
*/
private $extensions;
/**
* Allowed mimetypes
* @var array
*/
private $mimeTypes;
/**
* Fieldnames for files to upload
* @var string
*/
private $fieldName;
/**
* Filename
* @var string
*/
private $fileName;
/**
* Filename cleaned or not
* @var boolean
*/
private $cleanName;
/**
* Préfix for filename
* @var string
*/
private $prefix;
/**
* Suffix for filename
* @var <string
*/
private $suffix;
/**
* Uploaded files summaries
* @var array
*/
private $uploadedFileSummaries;
/**
* Found errors
* @var mixed
*/
private $errors;
/** Temporary name
* @var string
*/
private $fileNameTmp;
private $_taille = 0;
private $_nom = '';
private $_temp = '';
private $_mime = '';
private $_image = false;
private $_error = '';
private $_ext = '';
/**
* Constructor
* @param string $dir Target path for files
* @param string $fieldName Uploading fieldnames
* @param int [$mimetypeCheck] Mode to check type (browser)
*/
public function __construct(string $dir, string $fieldName, int $mimetypeCheck = 1)
{
$this->maxFileSize = str_replace('M', '', ini_get('upload_max_filesize')) * 1024 * 1024;
$this->uploadDir = $this->checkPath($dir);
$this->magicFile = '';
$this->mimetypeCheck= intval($mimetypeCheck);
$this->writeMode = self::WMODE_OVERWRITE;
$this->required = self::REQUIRE_NO;
$this->extensions = array('jpg', 'png', 'gif');
$this->mimeTypes = array('image/gif', 'image/jpeg', 'image/png', 'text/plain', 'application/pdf');
$this->fieldName = $fieldName;
$this->fileName = '';
$this->fileNameTmp = '';
$this->prefix = '';
$this->suffix = '';
$this->uploadedFileSummaries= array();
$this->secureMode = false;
$this->cleanName = false;
$this->errors = array();
}
/**
* Trigger fileuploads
* @return array
*/
public function upload()
{
if (!isset($_FILES[$this->fieldName]['tmp_name']))
throw new \UnexpectedValueException('Error: No filedata');
$nbFile = count($_FILES[$this->fieldName]['tmp_name']);
for ($i = 0; $i < $nbFile; $i++) {
$this->fileNameTmp = '';
$this->_taille = $_FILES[$this->fieldName]['size'][$i];
$this->_nom = $_FILES[$this->fieldName]['name'][$i];
$this->_temp = $_FILES[$this->fieldName]['tmp_name'][$i];
$this->_mime = $_FILES[$this->fieldName]['type'][$i];
$this->_image = false; // added by moimp
if (!empty($this->_nom))
$this->_ext = FileTools::getExtension($this->_nom);
$this->_error = $_FILES[$this->fieldName]['error'][$i];
if ($this->_error == UPLOAD_ERR_OK and is_uploaded_file($_FILES[$this->fieldName]['tmp_name'][$i]))
{
if ($this->mimetypeCheck == self::MIME_CHECK_FINFO)
{
$finfo = new \finfo(FILEINFO_MIME, $this->magicFile);
$this->_mime = $finfo->file(realpath($this->_temp));
// Can return mimetypes as "text/plain; charset=utf-8"
$posSemiCol = strpos($this->_mime, ';');
if ($posSemiCol !== false)
$this->_mime = substr($this->_mime, 0, $posSemiCol);
}
elseif ($this->mimetypeCheck == self::MIME_CHECK_MIMETYPE)
$this->_mime = mime_content_type(realpath($this->_temp));
elseif ($this->mimetypeCheck == self::MIME_CHECK_NONE)
$this->_mime = false;
if ($this->checkSize())
{
if ($this->checkExtension())
{
if ($this->checkMime())
{
// following code added by moimp
$this->getImgData();
if ($this->_image === 'err')
{
$this->errors[$i] = "The uploaded file is not an image.";
}
// end of added code
$this->buildName();
if ( ! $this->write() )
{
$this->errors[$i] = "Cannot write on harddisk. ";
}
}
else
{
$this->errors[$i] = "This filetype is not allowed. ";
}
}
else
{
$this->errors[$i] = "This file extension is not allowed. ";
}
}
else
{
$this->errors[$i] = "Filesize exceeds the allowed size. ";
}
}
else
{
if ($this->required == self::REQUIRE_ALL or $this->required == self::REQUIRE_YES and $i == 0)
$this->errors[$i] = "Error by uploading. Too big filesize or no required file? ";
}
}
return $this->getError();
}
/**
* Define max filesize.
* Allows (int) or string as 500K, 2M
* @param mixed $size
* @return Upload
*/
public function setMaxFileSize(string $size)
{
$this->maxFileSize = FileTools::getByteSize($size);
return $this;
}
/**
* Define path for magicmime files
* @param string $dir
* @return Upload
*/
/*
public function setMagicFile($path)
{
$this->magicFile = $path;
return $this;
}
*/
/**
* Define writemode
* @param int $mode (one of constants WMODE_OVERWRITE, WMODE_COPY, WMODE_CANCEL)
* @return Upload
*/
public function setWriteMode($mode)
{
$this->writeMode = intval($mode);
return $this;
}
/**
* Define if files are required or not
* @param int $mode
* @return Upload
*/
public function setRequired($mode)
{
$this->required = intval($mode);
return $this;
}
/**
* Define a (string) or multiple (array) of allowed extensions
* @param mixed $newExt
* @return Upload
*/
public function setAllowedExtensions($newExt)
{
if (is_array($newExt))
foreach ($newExt as $value)
$this->extensions[] = $value;
else
$this->extensions[] = $newExt;
return $this;
}
/**
* Return allowed extensions
* @return array
*/
public function getExtensions()
{
return $this->extensions;
}
/**
* Remove an extension
* @param string $extToRemove
* @return Upload
*/
public function removeExtension(string $extToRemove)
{
$key = array_search($extToRemove, $this->extensions);
if ($key)
unset($this->extensions[$key]);
return $this;
}
/**
* Remove all extensions
* @return Upload
*/
public function flushAllowedExtensions()
{
$this->extensions = array();
return $this;
}
/**
* Define a (string) or multiple (array) of allowed mimetypes
* @param mixed $newMime
* @return Upload
*/
public function setAllowedMime($newMime)
{
if (is_array($newMime))
foreach ($newMime as $value)
$this->mimeTypes[] = $value;
else
$this->mimeTypes[] = $newMime;
return $this;
}
/**
* Return allowed mimetypes
* @return array
*/
public function getMime()
{
return $this->mimeTypes;
}
/**
* Remove a mimetype
* @param string $mimeToRemove
* @return Upload
*/
public function removeMime(string $mimeToRemove)
{
$key = array_search($mimeToRemove, $this->mimeTypes);
if ($key)
unset($this->mimeTypes[$key]);
return $this;
}
/**
* Remove all mimetypes
* @return Upload
*/
public function flushAllowedMime()
{
$this->mimeTypes = array();
return $this;
}
/**
* Define filename after uploaded
* @param string $name
* @return Upload
*/
public function setFileName(string $name)
{
$this->fileName = trim($name);
return $this;
}
/**
* Define préfix of filename
* @param string $prefix
* @return Upload
*/
public function setPrefix(string $prefix)
{
$this->prefix = trim($prefix);
return $this;
}
/**
* Define suffix of filename
* @param string $suffix
* @return Upload
* Note: impact basename
*/
public function setSuffix(string $suffix)
{
$this->suffix = trim($suffix);
return $this;
}
/**
* Define securemode where application files or dangerous files are not allowed
* @param boolean $mode
* @return Upload
*/
public function setSecureMode(bool $mode)
{
$this->secureMode = $mode;
return $this;
}
/**
* Enable or disabled cleaning of filename
* @param boolean $bool
* @return Upload
*/
public function cleanName(bool $bool)
{
$this->cleanName = $bool;
return $this;
}
/**
* Return an array of all errors
* @return mixed
*/
public function getError()
{
if (!empty($this->errors))
return $this->errors;
else
return false;
}
/**
* Return an array of all sent files
* @return array
*/
public function getSummaries()
{
return $this->uploadedFileSummaries;
}
/**
* Get imagedata
* @return wether imagedata or boolean if uploaded file is not an image
* Function added by moimp
*/
private function getImgData()
{
if (strpos($this->_mime, 'image/') !== false)
{
$this->_image = getimagesize(realpath($this->_temp));
if ( !(
is_int($this->_image[0]) &&
is_int($this->_image[1]) &&
is_int($this->_image[2]) &&
is_int($this->_image['bits']) &&
strpos($this->_image['mime'], 'image/') !== false
)
)
{
$this->_image = 'err';
}
}
else
{
$this->_image = false;
}
}
/**
* Check if a path is correct
* @param string $path
* @return boolean
*/
private function checkPath(string $path)
{
$path = trim($path);
$path = rtrim($path, '/\\').'/'; // line added by moimp to allowed pathes ended wether with or whithout '/' or '\'
if (!is_dir($path))
throw new \InvalidArgumentException($path . ' is not a valid path');
if (!is_writable($path))
throw new \RuntimeException($path . ' is not open in write mode');
return $path;
}
/**
* Write file on harddisk on the wished place
* @return boolean
*/
private function write()
{
if ($this->writeMode == self::WMODE_OVERWRITE)
{
if ($this->exist())
unlink($this->uploadDir . $this->fileNameTmp);
$uploaded = move_uploaded_file($this->_temp, $this->uploadDir . $this->fileNameTmp);
}
elseif ($this->writeMode == self::WMODE_COPY)
{
if ($this->exist())
$this->fileName = 'Copy_' . $this->fileNameTmp;
$uploaded = move_uploaded_file($this->_temp, $this->uploadDir . $this->fileNameTmp);
}
else
{
if (!$this->exist())
$uploaded = move_uploaded_file($this->_temp, $this->uploadDir . $this->fileNameTmp);
else
$uploaded = false;
}
if ($uploaded)
{
$this->uploadedFileSummaries[] = array(
'nom' => $this->fileNameTmp,
'nom_base' => $this->_nom,
'ext' => $this->_ext,
'mime' => $this->_mime,
'path' => $this->uploadDir,
'octet' => $this->_taille,
'size' => number_format($this->_taille / 1024, 2, '.', ''),
'image' => $this->_image // added by moimp
);
return true;
}
return false;
}
/**
* Check filesize
* @return boolean
*/
private function checkSize()
{
if ($this->maxFileSize > $this->_taille)
return true;
return false;
}
/**
* Check the filename extension
* @return boolean
*/
private function checkExtension()
{
if (in_array($this->_ext, $this->extensions))
return true;
return false;
}
/**
* Check mimetype of the file
* @return boolean
*/
private function checkMime()
{
if ($this->mimetypeCheck != self::MIME_CHECK_NONE)
{
if ($this->secureMode) {
if (!in_array($this->_mime, $this->mimeTypes) || strpos($this->_mime, 'application') || preg_match("/.php$|.php3$|.php5$|.inc$|.js$|.exe$/i", $this->_ext))
return false;
} else {
if (!in_array($this->_mime, $this->mimeTypes))
return false;
}
}
return true;
}
/**
* Build filename
* @return void
*/
private function buildName()
{
if ($this->fileName == '')
$this->fileNameTmp = substr($this->_nom, 0, strrpos($this->_nom, '.'));
else
$this->fileNameTmp = $this->fileName;
if ($this->cleanName)
$this->fileNameTmp = StringTools::clean($this->fileNameTmp);
$this->fileNameTmp = $this->prefix . $this->fileNameTmp . $this->suffix . '.' . $this->_ext;
}
/**
* Check if file exists
* @access private
* @return boolean
*/
private function exist()
{
if (file_exists($this->uploadDir . $this->fileNameTmp))
return true;
return false;
}
} |
Partager