Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
File.php
Go to the documentation of this file.
1 <?php
7 
12 class File extends AbstractIo
13 {
19  protected $_iwd;
20 
26  protected $_cwd;
27 
33  const GREP_FILES = 'files_only';
34 
40  const GREP_DIRS = 'dirs_only';
41 
49  protected $_allowCreateFolders = false;
50 
56  protected $_streamHandler;
57 
63  protected $_streamFileName;
64 
70  protected $_streamChmod;
71 
77  protected $_streamLocked = false;
78 
82  private $_streamException;
83 
89  public function __destruct()
90  {
91  if ($this->_streamHandler) {
92  $this->streamClose();
93  }
94  }
95 
102  public function streamLock($exclusive = true)
103  {
104  if (!$this->_streamHandler) {
105  return false;
106  }
107  $this->_streamLocked = true;
108  $lock = $exclusive ? LOCK_EX : LOCK_SH;
109  return flock($this->_streamHandler, $lock);
110  }
111 
117  public function streamUnlock()
118  {
119  if (!$this->_streamHandler || !$this->_streamLocked) {
120  return false;
121  }
122  $this->_streamLocked = false;
123  return flock($this->_streamHandler, LOCK_UN);
124  }
125 
132  public function streamRead($length = 1024)
133  {
134  if (!$this->_streamHandler) {
135  return false;
136  }
137  if (feof($this->_streamHandler)) {
138  return false;
139  }
140  return @fgets($this->_streamHandler, $length);
141  }
142 
150  public function streamReadCsv($delimiter = ',', $enclosure = '"')
151  {
152  if (!$this->_streamHandler) {
153  return false;
154  }
155  return @fgetcsv($this->_streamHandler, 0, $delimiter, $enclosure);
156  }
157 
164  public function streamWrite($str)
165  {
166  if (!$this->_streamHandler) {
167  return false;
168  }
169  return @fwrite($this->_streamHandler, $str);
170  }
171 
180  public function streamWriteCsv(array $row, $delimiter = ',', $enclosure = '"')
181  {
182  if (!$this->_streamHandler) {
183  return false;
184  }
191  foreach ($row as $key => $value) {
192  if (!is_string($value)) {
193  $value = (string)$value;
194  }
195  if (isset($value[0]) && in_array($value[0], ['=', '+', '-'])) {
196  $row[$key] = ' ' . $value;
197  }
198  }
199  return @fputcsv($this->_streamHandler, $row, $delimiter, $enclosure);
200  }
201 
208  public function streamClose()
209  {
210  if (!$this->_streamHandler) {
211  return false;
212  }
213 
214  if ($this->_streamLocked) {
215  $this->streamUnlock();
216  }
217  @fclose($this->_streamHandler);
218  $this->chmod($this->_streamFileName, $this->_streamChmod);
219  return true;
220  }
221 
229  public function streamStat($part = null, $default = null)
230  {
231  if (!$this->_streamHandler) {
232  return false;
233  }
234  $stat = @fstat($this->_streamHandler);
235  if ($part !== null) {
236  return $stat[$part] ?? $default;
237  }
238  return $stat;
239  }
240 
246  public function getStreamException()
247  {
248  return $this->_streamException;
249  }
250 
260  public function open(array $args = [])
261  {
262  if (!empty($args['path'])) {
263  if ($args['path']) {
264  if ($this->_allowCreateFolders) {
265  $this->_createDestinationFolder($args['path']);
266  }
267  }
268  }
269 
270  $this->_iwd = getcwd();
271  $this->cd(!empty($args['path']) ? $args['path'] : $this->_iwd);
272  return true;
273  }
274 
282  public function setAllowCreateFolders($flag)
283  {
284  $this->_allowCreateFolders = $flag;
285  return $this;
286  }
287 
293  public function close()
294  {
295  return true;
296  }
297 
306  public function mkdir($dir, $mode = 0777, $recursive = true)
307  {
308  $this->_cwd();
309  $result = @mkdir($dir, $mode, $recursive);
310  $this->_iwd();
311  return $result;
312  }
313 
321  public function rmdir($dir, $recursive = false)
322  {
323  $this->_cwd();
324  $result = self::rmdirRecursive($dir, $recursive);
325  $this->_iwd();
326  return $result;
327  }
328 
335  public static function rmdirRecursive($dir, $recursive = true)
336  {
337  if ($recursive) {
338  $result = self::_recursiveCallback($dir, ['unlink'], ['rmdir']);
339  } else {
340  $result = @rmdir($dir);
341  }
342  return $result;
343  }
344 
360  protected static function _recursiveCallback($dir, array $fileCallback, array $dirCallback = [])
361  {
362  if (empty($fileCallback) || !is_array($fileCallback) || !is_array($dirCallback)) {
363  throw new \InvalidArgumentException("file/dir callback is not specified");
364  }
365  if (empty($dirCallback)) {
366  $dirCallback = $fileCallback;
367  }
368  if (is_dir($dir)) {
369  foreach (scandir($dir, SCANDIR_SORT_NONE) as $item) {
370  if (!strcmp($item, '.') || !strcmp($item, '..')) {
371  continue;
372  }
373  self::_recursiveCallback($dir . '/' . $item, $fileCallback, $dirCallback);
374  }
375  $callback = $dirCallback[0];
376  if (!is_callable($callback)) {
377  throw new \InvalidArgumentException("'dirCallback' parameter is not callable");
378  }
379  $parameters = isset($dirCallback[1]) ? $dirCallback[1] : [];
380  } else {
381  $callback = $fileCallback[0];
382  if (!is_callable($callback)) {
383  throw new \InvalidArgumentException("'fileCallback' parameter is not callable");
384  }
385  $parameters = isset($fileCallback[1]) ? $fileCallback[1] : [];
386  }
387  array_unshift($parameters, $dir);
388  $result = @call_user_func_array($callback, $parameters);
389 
390  return $result;
391  }
392 
398  public function pwd()
399  {
400  return $this->_cwd;
401  }
402 
411  public function cd($dir)
412  {
413  if (is_dir($dir)) {
414  $this->_iwd();
415  $this->_cwd = realpath($dir);
416  return true;
417  } else {
418  throw new \Exception('Unable to list current working directory.');
419  }
420  }
421 
432  public function read($filename, $dest = null)
433  {
434  $this->_cwd();
435  if ($dest !== null) {
436  $result = @copy($filename, $dest);
437  } else {
438  $result = @file_get_contents($filename);
439  }
440  $this->_iwd();
441 
442  return $result;
443  }
444 
454  public function write($filename, $src, $mode = null)
455  {
456  if (is_string($src) && @is_readable($src)) {
457  $src = realpath($src);
458  $srcIsFile = true;
459  } elseif (is_string($src) || is_resource($src)) {
460  $srcIsFile = false;
461  } else {
462  return false;
463  }
464  $this->_cwd();
465 
466  if (file_exists($filename)) {
467  if (!is_writeable($filename)) {
468  printf('The file %s is not writable', $filename);
469  return false;
470  }
471  } else {
472  if (!is_writable(dirname($filename))) {
473  printf('The directory %s is not writable', dirname($filename));
474  return false;
475  }
476  }
477  if ($srcIsFile) {
478  $result = @copy($src, $filename);
479  } else {
480  $result = @file_put_contents($filename, $src);
481  }
482  if ($mode !== null && $result) {
483  @chmod($filename, $mode);
484  }
485  $this->_iwd();
486  return $result;
487  }
488 
496  public function fileExists($file, $onlyFile = true)
497  {
498  $this->_cwd();
499  $result = file_exists($file);
500  if ($result && $onlyFile) {
501  $result = is_file($file);
502  }
503  $this->_iwd();
504  return $result;
505  }
506 
513  public function isWriteable($path)
514  {
515  $this->_cwd();
516  $result = is_writeable($path);
517  $this->_iwd();
518  return $result;
519  }
520 
527  public function getDestinationFolder($filePath)
528  {
529  preg_match('/^(.*[!\/])/', $filePath, $matches);
530  if (isset($matches[0])) {
531  return $matches[0];
532  }
533  return false;
534  }
535 
542  public function createDestinationDir($path)
543  {
544  if (!$this->_allowCreateFolders) {
545  return false;
546  }
547  return $this->_createDestinationFolder($this->getCleanPath($path));
548  }
549 
558  public function checkAndCreateFolder($folder, $mode = 0777)
559  {
560  if (is_dir($folder)) {
561  return true;
562  }
563  if (!is_dir(dirname($folder))) {
564  $this->checkAndCreateFolder(dirname($folder), $mode);
565  }
566  if (!is_dir($folder) && !$this->mkdir($folder, $mode)) {
567  throw new \Exception("Unable to create directory '{$folder}'. Access forbidden.");
568  }
569  return true;
570  }
571 
578  private function _createDestinationFolder($destinationFolder)
579  {
580  return $this->checkAndCreateFolder($destinationFolder);
581  }
582 
590  public function rm($filename)
591  {
592  $this->_cwd();
593  $result = @unlink($filename);
594  $this->_iwd();
595  return $result;
596  }
597 
606  public function mv($src, $destination)
607  {
608  $this->_cwd();
609  $result = @rename($src, $destination);
610  $this->_iwd();
611  return $result;
612  }
613 
622  public function cp($src, $destination)
623  {
624  $this->_cwd();
625  $result = @copy($src, $destination);
626  $this->_iwd();
627  return $result;
628  }
629 
638  public function chmod($filename, $mode, $recursive = false)
639  {
640  $this->_cwd();
641  if ($recursive) {
642  $result = self::chmodRecursive($filename, $mode);
643  } else {
644  $result = @chmod($filename, $mode);
645  }
646  $this->_iwd();
647  return $result;
648  }
649 
658  public static function chmodRecursive($dir, $mode)
659  {
660  return self::_recursiveCallback($dir, ['chmod', [$mode]]);
661  }
662 
679  public function ls($grep = null)
680  {
681  $ignoredDirectories = ['.', '..'];
682 
683  if (is_dir($this->_cwd)) {
684  $dir = $this->_cwd;
685  } elseif (is_dir($this->_iwd)) {
686  $dir = $this->_iwd;
687  } else {
688  throw new \Exception('Unable to list current working directory.');
689  }
690 
691  $list = [];
692 
693  $dirHandler = opendir($dir);
694  if ($dirHandler) {
695  while (($entry = readdir($dirHandler)) !== false) {
696  $listItem = [];
697 
698  $fullPath = $dir . '/' . $entry;
699 
700  if ($grep == self::GREP_DIRS && !is_dir($fullPath)) {
701  continue;
702  } elseif ($grep == self::GREP_FILES && !is_file($fullPath)) {
703  continue;
704  } elseif (in_array($entry, $ignoredDirectories)) {
705  continue;
706  }
707 
708  $listItem['text'] = $entry;
709  $listItem['mod_date'] = date('Y-m-d H:i:s', filectime($fullPath));
710  $listItem['permissions'] = $this->_parsePermissions(fileperms($fullPath));
711  $listItem['owner'] = $this->_getFileOwner($fullPath);
712 
713  if (is_file($fullPath)) {
714  $pathInfo = pathinfo($fullPath);
715  $listItem['size'] = filesize($fullPath);
716  $listItem['leaf'] = true;
717  if (isset(
718  $pathInfo['extension']
719  ) && in_array(
720  strtolower($pathInfo['extension']),
721  ['jpg', 'jpeg', 'gif', 'bmp', 'png']
722  ) && $listItem['size'] > 0
723  ) {
724  $listItem['is_image'] = true;
725  $listItem['filetype'] = $pathInfo['extension'];
726  } elseif ($listItem['size'] == 0) {
727  $listItem['is_image'] = false;
728  $listItem['filetype'] = 'unknown';
729  } elseif (isset($pathInfo['extension'])) {
730  $listItem['is_image'] = false;
731  $listItem['filetype'] = $pathInfo['extension'];
732  } else {
733  $listItem['is_image'] = false;
734  $listItem['filetype'] = 'unknown';
735  }
736  } else {
737  $listItem['leaf'] = false;
738  $listItem['id'] = $fullPath;
739  }
740 
741  $list[] = $listItem;
742  }
743  closedir($dirHandler);
744  } else {
745  throw new \Exception('Unable to list current working directory. Access forbidden.');
746  }
747 
748  return $list;
749  }
750 
756  protected function _cwd()
757  {
758  if ($this->_cwd) {
759  chdir($this->_cwd);
760  }
761  }
762 
768  protected function _iwd()
769  {
770  if ($this->_iwd) {
771  chdir($this->_iwd);
772  }
773  }
774 
784  protected function _parsePermissions($mode)
785  {
786  if ($mode & 0x1000) {
787  $type = 'p'; /* FIFO pipe */
788  } elseif ($mode & 0x2000) {
789  $type = 'c'; /* Character special */
790  } elseif ($mode & 0x4000) {
791  $type = 'd'; /* \Directory */
792  } elseif ($mode & 0x6000) {
793  $type = 'b'; /* Block special */
794  } elseif ($mode & 0x8000) {
795  $type = '-'; /* Regular */
796  } elseif ($mode & 0xA000) {
797  $type = 'l'; /* Symbolic Link */
798  } elseif ($mode & 0xC000) {
799  $type = 's'; /* Socket */
800  } else {
801  $type = 'u'; /* UNKNOWN */
802  }
803 
804  /* Determine permissions */
805  $owner['read'] = $mode & 00400 ? 'r' : '-';
806  $owner['write'] = $mode & 00200 ? 'w' : '-';
807  $owner['execute'] = $mode & 00100 ? 'x' : '-';
808  $group['read'] = $mode & 00040 ? 'r' : '-';
809  $group['write'] = $mode & 00020 ? 'w' : '-';
810  $group['execute'] = $mode & 00010 ? 'x' : '-';
811  $world['read'] = $mode & 00004 ? 'r' : '-';
812  $world['write'] = $mode & 00002 ? 'w' : '-';
813  $world['execute'] = $mode & 00001 ? 'x' : '-';
814 
815  /* Adjust for SUID, SGID and sticky bit */
816  if ($mode & 0x800) {
817  $owner["execute"] = $owner['execute'] == 'x' ? 's' : 'S';
818  }
819  if ($mode & 0x400) {
820  $group["execute"] = $group['execute'] == 'x' ? 's' : 'S';
821  }
822  if ($mode & 0x200) {
823  $world["execute"] = $world['execute'] == 'x' ? 't' : 'T';
824  }
825 
826  $s = sprintf('%1s', $type);
827  $s .= sprintf('%1s%1s%1s', $owner['read'], $owner['write'], $owner['execute']);
828  $s .= sprintf('%1s%1s%1s', $group['read'], $group['write'], $group['execute']);
829  $s .= sprintf('%1s%1s%1s', $world['read'], $world['write'], $world['execute']);
830  return trim($s);
831  }
832 
839  protected function _getFileOwner($filename)
840  {
841  if (!function_exists('posix_getpwuid')) {
842  return 'n/a';
843  }
844 
845  $owner = posix_getpwuid(fileowner($filename));
846  $groupInfo = posix_getgrnam(filegroup($filename));
847 
848  return $owner['name'] . ' / ' . $groupInfo;
849  }
850 
856  public function dirsep()
857  {
858  return '/';
859  }
860 
867  public function dirname($file)
868  {
869  return $this->getCleanPath(dirname($file));
870  }
871 
879  public function getDirectoriesList($path, $flag = GLOB_ONLYDIR)
880  {
881  return glob($this->getCleanPath($path) . '*', $flag);
882  }
883 
890  public function getPathInfo($path)
891  {
892  return pathinfo($path);
893  }
894 }
fileExists($file, $onlyFile=true)
Definition: File.php:496
streamStat($part=null, $default=null)
Definition: File.php:229
read($filename, $dest=null)
Definition: File.php:432
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$group
Definition: sections.phtml:16
static _recursiveCallback($dir, array $fileCallback, array $dirCallback=[])
Definition: File.php:360
checkAndCreateFolder($folder, $mode=0777)
Definition: File.php:558
$type
Definition: item.phtml:13
chmod($filename, $mode, $recursive=false)
Definition: File.php:638
getDirectoriesList($path, $flag=GLOB_ONLYDIR)
Definition: File.php:879
$value
Definition: gender.phtml:16
streamReadCsv($delimiter=',', $enclosure='"')
Definition: File.php:150
if($exist=($block->getProductCollection() && $block->getProductCollection() ->getSize())) $mode
Definition: grid.phtml:15
cp($src, $destination)
Definition: File.php:622
rmdir($dir, $recursive=false)
Definition: File.php:321
mkdir($dir, $mode=0777, $recursive=true)
Definition: File.php:306
is_writable($path)
Definition: io.php:25
mv($src, $destination)
Definition: File.php:606
write($filename, $src, $mode=null)
Definition: File.php:454
static chmodRecursive($dir, $mode)
Definition: File.php:658
static rmdirRecursive($dir, $recursive=true)
Definition: File.php:335