Example #1
0
 protected function createTransferAction(\SplFileInfo $file)
 {
     // Open the file for reading
     $filename = $file->getPathName();
     if (!($resource = fopen($filename, 'r'))) {
         // @codeCoverageIgnoreStart
         throw new RuntimeException("Could not open {$filename} for reading");
         // @codeCoverageIgnoreEnd
     }
     $key = $this->options['source_converter']->convert($filename);
     $body = EntityBody::factory($resource);
     // Determine how the ACL should be applied
     if ($acl = $this->options['acl']) {
         $aclType = is_string($this->options['acl']) ? 'ACL' : 'ACP';
     } else {
         $acl = 'private';
         $aclType = 'ACL';
     }
     // Use a multi-part upload if the file is larger than the cutoff size and is a regular file
     if ($body->getWrapper() == 'plainfile' && $file->getSize() >= $this->options['multipart_upload_size']) {
         $builder = UploadBuilder::newInstance()->setBucket($this->options['bucket'])->setKey($key)->setMinPartSize($this->options['multipart_upload_size'])->setOption($aclType, $acl)->setClient($this->options['client'])->setSource($body)->setConcurrency($this->options['concurrency']);
         $this->dispatch(self::BEFORE_MULTIPART_BUILD, array('builder' => $builder, 'file' => $file));
         return $builder->build();
     }
     return $this->options['client']->getCommand('PutObject', array('Bucket' => $this->options['bucket'], 'Key' => $key, 'Body' => $body, $aclType => $acl));
 }
Example #2
0
 /**
  * Test is files or directories passed as arguments are empty.
  * Only valid for regular files and directories.
  *
  * @param mixed $files String or array of strings of path to files and directories.
  *
  * @return boolean True if all arguments are empty. (Size 0 for files and no children for directories).
  */
 public function isEmpty($files)
 {
     if (!$files instanceof \Traversable) {
         $files = new \ArrayObject(is_array($files) ? $files : array($files));
     }
     foreach ($files as $file) {
         if (!$this->exists($file)) {
             throw new FileNotFoundException(null, 0, null, $file);
         }
         if (is_file($file)) {
             $file_info = new \SplFileInfo($file);
             if ($file_info->getSize() !== 0) {
                 return false;
             }
         } elseif (is_dir($file)) {
             $finder = new Finder();
             $finder->in($file);
             $it = $finder->getIterator();
             $it->rewind();
             if ($it->valid()) {
                 return false;
             }
         } else {
             throw new IOException(sprintf('File "%s" is not a directory or a regular file.', $file), 0, null, $file);
         }
     }
     return true;
 }
    /**
     * UnsortedEpisodesFilter::accept()
     *
     * @return
     */
    public function accept()
    {
        $file = new SplFileInfo( $this->getInnerIterator()->current() );

        if ( !$file->isFile() )
        {
            echo "Not a file<br />";
            return false;
        }


        if ( !preg_match( '/\.(mkv|avi)$/ ', $file->getBasename() ) )
        {
            echo "Not a video<br />";
            return false;
        }

        if ( $file->getSize() < ( 25 * 1024 * 1024 ) )
        {
            echo "Too small<br />";
            return false;
        }

        $subtitleFileNames = array( $file->getBasename() . '.srt', $file->getBasename() . '.ass' );
        foreach ( $subtitleFileNames as $subtitleFileName )
            if ( file_exists( $subtitleFileName ) )
                return false;
    }
Example #4
0
 /**
  * The "booting" method of the model.
  *
  * @return void
  */
 protected static function boot()
 {
     parent::boot();
     static::saving(function (\Eloquent $model) {
         // If a new download file is uploaded, could be create or edit...
         $dirty = $model->getDirty();
         if (array_key_exists('filename', $dirty)) {
             $file = new \SplFileInfo($model->getAbsolutePath());
             $model->filesize = $file->getSize();
             $model->extension = strtoupper($file->getExtension());
             // Now if editing only...
             if ($model->exists) {
                 $oldFilename = self::where($model->getKeyName(), '=', $model->id)->first()->pluck('filename');
                 $newFilename = $dirty['filename'];
                 // Delete the old file if the filename is different to the new one, and it therefore hasn't been replaced
                 if ($oldFilename != $newFilename) {
                     $model->deleteFile($oldFilename);
                 }
             }
         }
         // If a download is edited and the image is changed...
         if (array_key_exists('image', $dirty) && $model->exists) {
             $oldImageFilename = self::where($model->getKeyName(), '=', $model->id)->first()->pluck('image');
             $model->deleteImageFiles($oldImageFilename);
         }
     });
     static::deleted(function ($model) {
         $model->deleteFile();
         $model->deleteImageFiles();
     });
 }
 public function info()
 {
     if (!isset($this->info)) {
         $this->info = new StorageInfo(array('name' => $this->file->getFilename(), 'hash' => $this->isReadable() ? $this->getHash() : null, 'format' => $this->getFormat(), 'size' => $this->isReadable() ? $this->file->getSize() : 0, 'count' => $this->isReadable() ? count($this->reader()) : 0));
     }
     return $this->info;
 }
Example #6
0
 /**
  * @param \SplFileInfo $fileInfo
  * @param string       $downloadDirUrl
  */
 public function __construct(\SplFileInfo $fileInfo, $downloadDirUrl)
 {
     $this->size = $fileInfo->getSize();
     $this->fileName = $fileInfo->getBasename();
     $this->lastModified = \DateTime::createFromFormat("U", $fileInfo->getMTime());
     $this->url = "{$downloadDirUrl}/" . rawurlencode($this->fileName);
 }
Example #7
0
    public function __construct(SplFileInfo $fileinfo = null)
    {
        parent::__construct();
        if ($fileinfo) {
            $this->file_hash = md5($fileinfo->getRealPath());
            $fileSize = $fileinfo->getSize();
            // Looking for existing path
            $result = Db::getInstance()->getRow('
				SELECT *
				FROM `' . _DB_PREFIX_ . bqSQL(self::$definition['table']) . '`
				WHERE `file_hash` = \'' . pSQL($this->file_hash) . '\'');
            if (!$result) {
                $this->file_size = $fileSize;
                $this->file_info = $fileinfo;
            } else {
                $this->id = $result['id'];
                foreach ($result as $key => $value) {
                    if (array_key_exists($key, $this)) {
                        $this->{$key} = $value;
                    }
                }
                // Check file size
                if ($this->file_size != $fileSize) {
                    $this->file_size = $fileSize;
                    $this->file_info = $fileinfo;
                }
            }
        }
        return $this;
    }
Example #8
0
 /**
  * Returns file checksum
  *
  * @param string $file
  * @return string
  */
 public function calculate($file)
 {
     $file = new \SplFileInfo($file);
     if (!$file->isFile() && !$file->isReadable()) {
         throw new \InvalidArgumentException('Invalid argument supplied for checksum calculation, only existing files are allowed');
     }
     return sprintf('%s:%s', $file->getMTime(), $file->getSize());
 }
Example #9
0
 /**
  * @param string $filename
  * @return FileUpload
  */
 public static function fileUploadFromFile($filename)
 {
     if (!file_exists($filename)) {
         throw new FileNotExistsException("File '{$filename}' does not exists");
     }
     $file = new \SplFileInfo($filename);
     return new FileUpload(['name' => $file->getBasename(), 'type' => $file->getType(), 'size' => $file->getSize(), 'tmp_name' => $filename, 'error' => 0]);
 }
Example #10
0
 /**
  * Hash constructor.
  * creates a new hash set from a list of files
  *
  * @constructor
  * @access public
  * @param array $fileList
  */
 public function __construct(array $fileList)
 {
     $this->fileList = $fileList;
     foreach ($this->fileList as $filePath) {
         $file = new \SplFileInfo($filePath);
         // hash the file path, size and CTime using murmur
         $this->hashSet[$file->getRealPath()] = murmurhash3($file->getRealPath() . $file->getSize() . $file->getCTime());
     }
 }
Example #11
0
 public function __construct(SplFileInfo $fileInfo)
 {
     $this->perms = $fileInfo->getPerms();
     $this->size = $fileInfo->getSize();
     $this->is_dir = $fileInfo->isDir();
     $this->is_file = $fileInfo->isFile();
     $this->is_link = $fileInfo->isLink();
     if (($this->perms & 0xc000) === 0xc000) {
         $this->typename = 'File socket';
         $this->typeflag = 's';
     } elseif ($this->is_file) {
         if ($this->is_link) {
             $this->typename = 'File symlink';
             $this->typeflag = 'l';
         } else {
             $this->typename = 'File';
             $this->typeflag = '-';
         }
     } elseif (($this->perms & 0x6000) === 0x6000) {
         $this->typename = 'Block special file';
         $this->typeflag = 'b';
     } elseif ($this->is_dir) {
         if ($this->is_link) {
             $this->typename = 'Directory symlink';
             $this->typeflag = 'l';
         } else {
             $this->typename = 'Directory';
             $this->typeflag = 'd';
         }
     } elseif (($this->perms & 0x2000) === 0x2000) {
         $this->typename = 'Character special file';
         $this->typeflag = 'c';
     } elseif (($this->perms & 0x1000) === 0x1000) {
         $this->typename = 'FIFO pipe file';
         $this->typeflag = 'p';
     }
     parent::__construct('FsPath');
     $this->path = $fileInfo->getPathname();
     $this->realpath = realpath($this->path);
     if ($this->is_link && method_exists($fileInfo, 'getLinktarget')) {
         $this->linktarget = $fileInfo->getLinktarget();
     }
     $flags = array($this->typeflag);
     // User
     $flags[] = $this->perms & 0x100 ? 'r' : '-';
     $flags[] = $this->perms & 0x80 ? 'w' : '-';
     $flags[] = $this->perms & 0x40 ? $this->perms & 0x800 ? 's' : 'x' : ($this->perms & 0x800 ? 'S' : '-');
     // Group
     $flags[] = $this->perms & 0x20 ? 'r' : '-';
     $flags[] = $this->perms & 0x10 ? 'w' : '-';
     $flags[] = $this->perms & 0x8 ? $this->perms & 0x400 ? 's' : 'x' : ($this->perms & 0x400 ? 'S' : '-');
     // Other
     $flags[] = $this->perms & 0x4 ? 'r' : '-';
     $flags[] = $this->perms & 0x2 ? 'w' : '-';
     $flags[] = $this->perms & 0x1 ? $this->perms & 0x200 ? 't' : 'x' : ($this->perms & 0x200 ? 'T' : '-');
     $this->contents = implode($flags);
 }
Example #12
0
 /**
  * @param mixed $variable
  *
  * @return false|null
  */
 protected function _parse(&$variable)
 {
     /** @noinspection PhpUsageOfSilenceOperatorInspection */
     if (is_object($variable) || is_array($variable) || (string) $variable !== $variable || strlen($variable) > 2048 || preg_match('[[:?<>"*|]]', $variable) || !@is_readable($variable)) {
         return false;
     }
     try {
         $fileInfo = new \SplFileInfo($variable);
         $flags = array();
         $perms = $fileInfo->getPerms();
         if (($perms & 0xc000) === 0xc000) {
             $type = 'File socket';
             $flags[] = 's';
         } elseif (($perms & 0xa000) === 0xa000) {
             $type = 'File symlink';
             $flags[] = 'l';
         } elseif (($perms & 0x8000) === 0x8000) {
             $type = 'File';
             $flags[] = '-';
         } elseif (($perms & 0x6000) === 0x6000) {
             $type = 'Block special file';
             $flags[] = 'b';
         } elseif (($perms & 0x4000) === 0x4000) {
             $type = 'Directory';
             $flags[] = 'd';
         } elseif (($perms & 0x2000) === 0x2000) {
             $type = 'Character special file';
             $flags[] = 'c';
         } elseif (($perms & 0x1000) === 0x1000) {
             $type = 'FIFO pipe file';
             $flags[] = 'p';
         } else {
             $type = 'Unknown file';
             $flags[] = 'u';
         }
         // owner
         $flags[] = $perms & 0x100 ? 'r' : '-';
         $flags[] = $perms & 0x80 ? 'w' : '-';
         $flags[] = $perms & 0x40 ? $perms & 0x800 ? 's' : 'x' : ($perms & 0x800 ? 'S' : '-');
         // group
         $flags[] = $perms & 0x20 ? 'r' : '-';
         $flags[] = $perms & 0x10 ? 'w' : '-';
         $flags[] = $perms & 0x8 ? $perms & 0x400 ? 's' : 'x' : ($perms & 0x400 ? 'S' : '-');
         // world
         $flags[] = $perms & 0x4 ? 'r' : '-';
         $flags[] = $perms & 0x2 ? 'w' : '-';
         $flags[] = $perms & 0x1 ? $perms & 0x200 ? 't' : 'x' : ($perms & 0x200 ? 'T' : '-');
         $this->type = $type;
         $this->size = sprintf('%.2fK', $fileInfo->getSize() / 1024);
         $this->value = implode($flags);
     } catch (\Exception $e) {
         return false;
     }
 }
Example #13
0
/**
 * Get the size of a directory or a file
 *
 * @param SplFileInfo $file SplFileInfo instance
 *
 * @return int The calculated size
 */
function get_size(\SplFileInfo $file)
{
    $size = 0;
    try {
        if ($file->isFile()) {
            $size += $file->getSize();
        } else {
            foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($file->getRealpath())) as $f) {
                $size += $f->getSize();
            }
        }
    } catch (\RuntimeException $e) {
    }
    return $size;
}
Example #14
0
 /**
  * Reads a file
  *
  * @param string $key
  * @param bool $includeContent
  *
  * @return File|boolean
  */
 public function read($key, $includeContent = true)
 {
     if (!$this->exists($key) || !is_readable($key)) {
         return false;
     }
     $info = new \SplFileInfo($key);
     $file = new File();
     $file->size = $info->getSize();
     $file->name = $info->getFilename();
     if ($includeContent) {
         $file->content = file_get_contents($info->getRealPath());
     }
     $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
     $file->mime = finfo_file($fileInfo, $info->getRealPath());
     finfo_close($fileInfo);
     return $file;
 }
Example #15
0
 /**
  * Builds hashmap for given directory.
  *
  * @param string $directory  Directory for hashmap creation.
  * @param array  $exclusions List of excluded file names.
  *
  * @return array Hashmap.
  */
 public function build_dir_hashmap($directory, $exclusions = array())
 {
     $directory_iterator = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
     $recursive_iterator = new RecursiveIteratorIterator($directory_iterator);
     $files = new RegexIterator($recursive_iterator, '/^.+\\.(less|css|php)$/i', RegexIterator::GET_MATCH);
     $hashmap = array();
     foreach ($files as $file) {
         $file_info = new SplFileInfo($file[0]);
         $file_path = $file_info->getPathname();
         if (in_array($file_info->getFilename(), $exclusions)) {
             continue;
         }
         $key = str_replace(array($directory, '/'), array('', '\\'), $file_path);
         $hashmap[$key] = array('size' => $file_info->getSize(), 'sha1' => sha1_file($file_path));
     }
     ksort($hashmap);
     return $hashmap;
 }
 /**
  * @see EbayEnterprise_Catalog_Model_Error_IConfirmations::process()
  */
 public function process(Varien_Event_Observer $observer)
 {
     /** @var Varien_Event */
     $event = $observer->getEvent();
     /** @var array */
     $feedDetails = (array) $event->getFeedDetails();
     foreach ($feedDetails as $detail) {
         /** @var string */
         $fileName = $detail['error_file'];
         $this->loadFile($fileName);
         // If no in-progress error file exists for the feed detail, it was
         // either never created and nothing was written to it, or it was
         // already processed. Don't attempt to process it again, move on.
         if (!$this->fileStream->isFile()) {
             $this->logger->debug('Error confirmation file does not exist: {file_name}', $this->context->getMetaData(__CLASS__, ['file_name' => $fileName]));
             continue;
         }
         // If the file exists but nothing was ever written to it, was not
         // initialized and no errors written to it, no need to send the empty
         // error file so simply remove it and move on.
         if ($this->fileStream->getSize() === 0) {
             $this->removeFile($fileName);
             $this->logger->debug('Error confirmation file is empty: {file_name}', $this->context->getMetaData(__CLASS__, ['file_name' => $fileName]));
             continue;
         }
         // If the error file exists and has had data written to it, close
         // the file - append closing XML tag.
         $this->close();
         // Ensure that only valid files are sent - may have had bad data
         // written to the file or in some other way be invalid. ProductHub
         // will be unable to do anything with invalid files and may cause
         // issues for the system if it receives any.
         if ($this->isValidPayload($fileName)) {
             $this->coreFeed->mvToLocalDirectory($fileName);
             $this->logger->debug('Sending Error confirmation File: {file_name}', $this->context->getMetaData(__CLASS__, ['file_name' => $fileName]));
         } else {
             $this->removeFile($fileName);
             $this->logger->debug('Error confirmation File: {file_name} has invalid XML', $this->context->getMetaData(__CLASS__, ['file_name' => $fileName]));
         }
     }
     return $this;
 }
 /**
  * Get the total filesize for a given file or directory
  *
  * If $file is a file then just return the result of `filesize()`.
  * If $file is a directory then schedule a recursive filesize scan.
  *
  * @param SplFileInfo $file			The file or directory you want to know the size of
  * @param bool $skip_excluded_files	Skip excluded files when calculating a directories total size
  * @return int 						The total of the file or directory
  */
 public function filesize(SplFileInfo $file, $skip_excluded_files = false)
 {
     // Skip missing or unreadable files
     if (!file_exists($file->getPathname()) || !@realpath($file->getPathname()) || !$file->isReadable()) {
         return false;
     }
     // If it's a file then just pass back the filesize
     if ($file->isFile() && $file->isReadable()) {
         return $file->getSize();
     }
     // If it's a directory then pull it from the cached filesize array
     if ($file->isDir()) {
         // If we haven't calculated the site size yet then kick it off in a thread
         $directory_sizes = get_transient('hmbkp_directory_filesizes');
         if (!is_array($directory_sizes)) {
             if (!$this->is_site_size_being_calculated()) {
                 // Mark the filesize as being calculated
                 set_transient('hmbkp_directory_filesizes_running', true, HOUR_IN_SECONDS);
                 // Schedule a Backdrop task to trigger a recalculation
                 $task = new HM_Backdrop_Task(array($this, 'recursive_filesize_scanner'));
                 $task->schedule();
             }
             return;
         }
         $current_pathname = trailingslashit($file->getPathname());
         $root = trailingslashit($this->get_root());
         foreach ($directory_sizes as $path => $size) {
             // Remove any files that aren't part of the current tree
             if (false === strpos($path, $current_pathname)) {
                 unset($directory_sizes[$path]);
             }
         }
         if ($skip_excluded_files) {
             $excludes = $this->exclude_string('regex');
             foreach ($directory_sizes as $path => $size) {
                 // Skip excluded files if we have excludes
                 if ($excludes && preg_match('(' . $excludes . ')', str_ireplace($root, '', HM_Backup::conform_dir($path)))) {
                     unset($directory_sizes[$path]);
                 }
             }
         }
         // Directory size is now just a sum of all files across all sub directories
         return array_sum($directory_sizes);
     }
 }
Example #18
0
                //TODO not sure if this is needed!
                if ($key != 'files' && $key != 'dirs') {
                    $f2s = $key . '/' . $val;
                    if (substr($f2s, -3) == 'php') {
                        $output .= 'File: ' . $f2s . PHP_EOL;
                    }
                }
            }
        }
    } else {
        $info = new SplFileInfo($o2s);
        $perms = substr(sprintf('%o', $info->getPerms()), -4);
        $owner = $info->getOwner();
        $group = $info->getGroup();
        $type = $info->getType();
        $size = $info->getSize();
        $scanner = new Scanner($o2s, $eol, $htmlMode, $scannerOptions);
        $scanner->scanFile("all", $patternData, $stringData);
        if (count($scanner->found)) {
            foreach ($scanner->found as $l) {
                $found .= $l;
            }
        } else {
            $found = '';
        }
        //make human readable size
        $size = $scanner->size_readable($size);
    }
} else {
    $ainfo = "The file/folder {$bS}{$o2s}{$bE} does not exist";
}
Example #19
0
 public function testDecoratedMethods()
 {
     $decorated = $this->getMockBuilder('hanneskod\\classtools\\Tests\\MockSplFileInfo')->setConstructorArgs([''])->getMock();
     $decorated->expects($this->once())->method('getRelativePath');
     $decorated->expects($this->once())->method('getRelativePathname');
     $decorated->expects($this->once())->method('getContents');
     $decorated->expects($this->once())->method('getATime');
     $decorated->expects($this->once())->method('getBasename');
     $decorated->expects($this->once())->method('getCTime');
     $decorated->expects($this->once())->method('getExtension');
     $decorated->expects($this->once())->method('getFileInfo');
     $decorated->expects($this->once())->method('getFilename');
     $decorated->expects($this->once())->method('getGroup');
     $decorated->expects($this->once())->method('getInode');
     $decorated->expects($this->once())->method('getLinkTarget');
     $decorated->expects($this->once())->method('getMTime');
     $decorated->expects($this->once())->method('getOwner');
     $decorated->expects($this->once())->method('getPath');
     $decorated->expects($this->once())->method('getPathInfo');
     $decorated->expects($this->once())->method('getPathname');
     $decorated->expects($this->once())->method('getPerms');
     $decorated->expects($this->once())->method('getRealPath');
     $decorated->expects($this->once())->method('getSize');
     $decorated->expects($this->once())->method('getType');
     $decorated->expects($this->once())->method('isDir');
     $decorated->expects($this->once())->method('isExecutable');
     $decorated->expects($this->once())->method('isFile');
     $decorated->expects($this->once())->method('isLink');
     $decorated->expects($this->once())->method('isReadable');
     $decorated->expects($this->once())->method('isWritable');
     $decorated->expects($this->once())->method('openFile');
     $decorated->expects($this->once())->method('setFileClass');
     $decorated->expects($this->once())->method('setInfoClass');
     $decorated->expects($this->once())->method('__toString')->will($this->returnValue(''));
     $fileInfo = new SplFileInfo($decorated);
     $fileInfo->getRelativePath();
     $fileInfo->getRelativePathname();
     $fileInfo->getContents();
     $fileInfo->getATime();
     $fileInfo->getBasename();
     $fileInfo->getCTime();
     $fileInfo->getExtension();
     $fileInfo->getFileInfo();
     $fileInfo->getFilename();
     $fileInfo->getGroup();
     $fileInfo->getInode();
     $fileInfo->getLinkTarget();
     $fileInfo->getMTime();
     $fileInfo->getOwner();
     $fileInfo->getPath();
     $fileInfo->getPathInfo();
     $fileInfo->getPathname();
     $fileInfo->getPerms();
     $fileInfo->getRealPath();
     $fileInfo->getSize();
     $fileInfo->getType();
     $fileInfo->isDir();
     $fileInfo->isExecutable();
     $fileInfo->isFile();
     $fileInfo->isLink();
     $fileInfo->isReadable();
     $fileInfo->isWritable();
     $fileInfo->openFile();
     $fileInfo->setFileClass();
     $fileInfo->setInfoClass();
     (string) $fileInfo;
 }
Example #20
0
 public function getFileSize()
 {
     return $this->file->getSize();
 }
Example #21
0
 /**
  * Evaluates the given variable
  *
  * @param   mixed &$subject   Variable to query
  * @param   bool $specialStr  Should this be interpreted as a special string?
  * @return  mixed             Result (both HTML and text modes generate strings)
  */
 protected function evaluate(&$subject, $specialStr = false)
 {
     switch ($type = gettype($subject)) {
         // https://github.com/digitalnature/php-ref/issues/13
         case 'unknown type':
             return $this->fmt->text('unknown');
             // null value
         // null value
         case 'NULL':
             return $this->fmt->text('null');
             // integer/double/float
         // integer/double/float
         case 'integer':
         case 'double':
             return $this->fmt->text($type, $subject, $type);
             // boolean
         // boolean
         case 'boolean':
             $text = $subject ? 'true' : 'false';
             return $this->fmt->text($text, $text, $type);
             // arrays
         // arrays
         case 'array':
             // empty array?
             if (empty($subject)) {
                 $this->fmt->text('array');
                 return $this->fmt->emptyGroup();
             }
             if (isset($subject[static::MARKER_KEY])) {
                 unset($subject[static::MARKER_KEY]);
                 $this->fmt->text('array');
                 $this->fmt->emptyGroup('recursion');
                 return;
             }
             // first recursion level detection;
             // this is optional (used to print consistent recursion info)
             foreach ($subject as $key => &$value) {
                 if (!is_array($value)) {
                     continue;
                 }
                 // save current value in a temporary variable
                 $buffer = $value;
                 // assign new value
                 $value = $value !== 1 ? 1 : 2;
                 // if they're still equal, then we have a reference
                 if ($value === $subject) {
                     $value = $buffer;
                     $value[static::MARKER_KEY] = true;
                     $this->evaluate($value);
                     return;
                 }
                 // restoring original value
                 $value = $buffer;
             }
             $this->fmt->text('array');
             $count = count($subject);
             if (!$this->fmt->startGroup($count)) {
                 return;
             }
             $max = max(array_map('static::strLen', array_keys($subject)));
             $subject[static::MARKER_KEY] = true;
             foreach ($subject as $key => &$value) {
                 // ignore our temporary marker
                 if ($key === static::MARKER_KEY) {
                     continue;
                 }
                 if ($this->hasInstanceTimedOut()) {
                     break;
                 }
                 $keyInfo = gettype($key);
                 if ($keyInfo === 'string') {
                     $encoding = static::$env['mbStr'] ? mb_detect_encoding($key) : '';
                     $keyLen = $encoding && $encoding !== 'ASCII' ? static::strLen($key) . '; ' . $encoding : static::strLen($key);
                     $keyInfo = "{$keyInfo}({$keyLen})";
                 } else {
                     $keyLen = strlen($key);
                 }
                 $this->fmt->startRow();
                 $this->fmt->text('key', $key, "Key: {$keyInfo}");
                 $this->fmt->colDiv($max - $keyLen);
                 $this->fmt->sep('=>');
                 $this->fmt->colDiv();
                 $this->evaluate($value, $specialStr);
                 $this->fmt->endRow();
             }
             unset($subject[static::MARKER_KEY]);
             $this->fmt->endGroup();
             return;
             // resource
         // resource
         case 'resource':
             $meta = array();
             $resType = get_resource_type($subject);
             $this->fmt->text('resource', strval($subject));
             if (!static::$config['showResourceInfo']) {
                 return $this->fmt->emptyGroup($resType);
             }
             // @see: http://php.net/manual/en/resource.php
             // need to add more...
             switch ($resType) {
                 // curl extension resource
                 case 'curl':
                     $meta = curl_getinfo($subject);
                     break;
                 case 'FTP Buffer':
                     $meta = array('time_out' => ftp_get_option($subject, FTP_TIMEOUT_SEC), 'auto_seek' => ftp_get_option($subject, FTP_AUTOSEEK));
                     break;
                     // gd image extension resource
                 // gd image extension resource
                 case 'gd':
                     $meta = array('size' => sprintf('%d x %d', imagesx($subject), imagesy($subject)), 'true_color' => imageistruecolor($subject));
                     break;
                 case 'ldap link':
                     $constants = get_defined_constants();
                     array_walk($constants, function ($value, $key) use(&$constants) {
                         if (strpos($key, 'LDAP_OPT_') !== 0) {
                             unset($constants[$key]);
                         }
                     });
                     // this seems to fail on my setup :(
                     unset($constants['LDAP_OPT_NETWORK_TIMEOUT']);
                     foreach (array_slice($constants, 3) as $key => $value) {
                         if (ldap_get_option($subject, (int) $value, $ret)) {
                             $meta[strtolower(substr($key, 9))] = $ret;
                         }
                     }
                     break;
                     // mysql connection (mysql extension is deprecated from php 5.4/5.5)
                 // mysql connection (mysql extension is deprecated from php 5.4/5.5)
                 case 'mysql link':
                 case 'mysql link persistent':
                     $dbs = array();
                     $query = @mysql_list_dbs($subject);
                     while ($row = @mysql_fetch_array($query)) {
                         $dbs[] = $row['Database'];
                     }
                     $meta = array('host' => ltrim(@mysql_get_host_info($subject), 'MySQL host info: '), 'server_version' => @mysql_get_server_info($subject), 'protocol_version' => @mysql_get_proto_info($subject), 'databases' => $dbs);
                     break;
                     // mysql result
                 // mysql result
                 case 'mysql result':
                     while ($row = @mysql_fetch_object($subject)) {
                         $meta[] = (array) $row;
                         if ($this->hasInstanceTimedOut()) {
                             break;
                         }
                     }
                     break;
                     // stream resource (fopen, fsockopen, popen, opendir etc)
                 // stream resource (fopen, fsockopen, popen, opendir etc)
                 case 'stream':
                     $meta = stream_get_meta_data($subject);
                     break;
             }
             if (!$meta) {
                 return $this->fmt->emptyGroup($resType);
             }
             if (!$this->fmt->startGroup($resType)) {
                 return;
             }
             $max = max(array_map('static::strLen', array_keys($meta)));
             foreach ($meta as $key => $value) {
                 $this->fmt->startRow();
                 $this->fmt->text('resourceProp', ucwords(str_replace('_', ' ', $key)));
                 $this->fmt->colDiv($max - static::strLen($key));
                 $this->fmt->sep(':');
                 $this->fmt->colDiv();
                 $this->evaluate($value);
                 $this->fmt->endRow();
             }
             $this->fmt->endGroup();
             return;
             // string
         // string
         case 'string':
             $length = static::strLen($subject);
             $encoding = static::$env['mbStr'] ? mb_detect_encoding($subject) : false;
             $info = $encoding && $encoding !== 'ASCII' ? $length . '; ' . $encoding : $length;
             if ($specialStr) {
                 $this->fmt->sep('"');
                 $this->fmt->text(array('string', 'special'), $subject, "string({$info})");
                 $this->fmt->sep('"');
                 return;
             }
             $this->fmt->text('string', $subject, "string({$info})");
             // advanced checks only if there are 3 characteres or more
             if (static::$config['showStringMatches'] && $length > 2 && trim($subject) !== '') {
                 $isNumeric = is_numeric($subject);
                 // very simple check to determine if the string could match a file path
                 // @note: this part of the code is very expensive
                 $isFile = $length < 2048 && max(array_map('strlen', explode('/', str_replace('\\', '/', $subject)))) < 128 && !preg_match('/[^\\w\\.\\-\\/\\\\:]|\\..*\\.|\\.$|:(?!(?<=^[a-zA-Z]:)[\\/\\\\])/', $subject);
                 if ($isFile) {
                     try {
                         $file = new \SplFileInfo($subject);
                         $flags = array();
                         $perms = $file->getPerms();
                         if (($perms & 0xc000) === 0xc000) {
                             // socket
                             $flags[] = 's';
                         } elseif (($perms & 0xa000) === 0xa000) {
                             // symlink
                             $flags[] = 'l';
                         } elseif (($perms & 0x8000) === 0x8000) {
                             // regular
                             $flags[] = '-';
                         } elseif (($perms & 0x6000) === 0x6000) {
                             // block special
                             $flags[] = 'b';
                         } elseif (($perms & 0x4000) === 0x4000) {
                             // directory
                             $flags[] = 'd';
                         } elseif (($perms & 0x2000) === 0x2000) {
                             // character special
                             $flags[] = 'c';
                         } elseif (($perms & 0x1000) === 0x1000) {
                             // FIFO pipe
                             $flags[] = 'p';
                         } else {
                             // unknown
                             $flags[] = 'u';
                         }
                         // owner
                         $flags[] = $perms & 0x100 ? 'r' : '-';
                         $flags[] = $perms & 0x80 ? 'w' : '-';
                         $flags[] = $perms & 0x40 ? $perms & 0x800 ? 's' : 'x' : ($perms & 0x800 ? 'S' : '-');
                         // group
                         $flags[] = $perms & 0x20 ? 'r' : '-';
                         $flags[] = $perms & 0x10 ? 'w' : '-';
                         $flags[] = $perms & 0x8 ? $perms & 0x400 ? 's' : 'x' : ($perms & 0x400 ? 'S' : '-');
                         // world
                         $flags[] = $perms & 0x4 ? 'r' : '-';
                         $flags[] = $perms & 0x2 ? 'w' : '-';
                         $flags[] = $perms & 0x1 ? $perms & 0x200 ? 't' : 'x' : ($perms & 0x200 ? 'T' : '-');
                         $size = is_dir($subject) ? '' : sprintf(' %.2fK', $file->getSize() / 1024);
                         $this->fmt->startContain('file', true);
                         $this->fmt->text('file', implode('', $flags) . $size);
                         $this->fmt->endContain();
                     } catch (\Exception $e) {
                         $isFile = false;
                     }
                 }
                 // class/interface/function
                 if (!preg_match('/[^\\w+\\\\]/', $subject) && $length < 96) {
                     $isClass = class_exists($subject, false);
                     if ($isClass) {
                         $this->fmt->startContain('class', true);
                         $this->fromReflector(new \ReflectionClass($subject));
                         $this->fmt->endContain();
                     }
                     if (!$isClass && interface_exists($subject, false)) {
                         $this->fmt->startContain('interface', true);
                         $this->fromReflector(new \ReflectionClass($subject));
                         $this->fmt->endContain('interface');
                     }
                     if (function_exists($subject)) {
                         $this->fmt->startContain('function', true);
                         $this->fromReflector(new \ReflectionFunction($subject));
                         $this->fmt->endContain('function');
                     }
                 }
                 // skip serialization/json/date checks if the string appears to be numeric,
                 // or if it's shorter than 5 characters
                 if (!$isNumeric && $length > 4) {
                     // url
                     if (static::$config['showUrls'] && static::$env['curlActive'] && filter_var($subject, FILTER_VALIDATE_URL)) {
                         $ch = curl_init($subject);
                         curl_setopt($ch, CURLOPT_NOBODY, true);
                         curl_exec($ch);
                         $nfo = curl_getinfo($ch);
                         curl_close($ch);
                         if ($nfo['http_code']) {
                             $this->fmt->startContain('url', true);
                             $contentType = explode(';', $nfo['content_type']);
                             $this->fmt->text('url', sprintf('%s:%d %s %.2fms (%d)', !empty($nfo['primary_ip']) ? $nfo['primary_ip'] : null, !empty($nfo['primary_port']) ? $nfo['primary_port'] : null, $contentType[0], $nfo['total_time'], $nfo['http_code']));
                             $this->fmt->endContain();
                         }
                     }
                     // date
                     if ($length < 128 && static::$env['supportsDate'] && !preg_match('/[^A-Za-z0-9.:+\\s\\-\\/]/', $subject)) {
                         try {
                             $date = new \DateTime($subject);
                             $errors = \DateTime::getLastErrors();
                             if ($errors['warning_count'] < 1 && $errors['error_count'] < 1) {
                                 $now = new \Datetime('now');
                                 $nowUtc = new \Datetime('now', new \DateTimeZone('UTC'));
                                 $diff = $now->diff($date);
                                 $map = array('y' => 'yr', 'm' => 'mo', 'd' => 'da', 'h' => 'hr', 'i' => 'min', 's' => 'sec');
                                 $timeAgo = 'now';
                                 foreach ($map as $k => $label) {
                                     if ($diff->{$k} > 0) {
                                         $timeAgo = $diff->format("%R%{$k}{$label}");
                                         break;
                                     }
                                 }
                                 $tz = $date->getTimezone();
                                 $offs = round($tz->getOffset($nowUtc) / 3600);
                                 if ($offs > 0) {
                                     $offs = "+{$offs}";
                                 }
                                 $timeAgo .= (int) $offs !== 0 ? ' ' . sprintf('%s (UTC%s)', $tz->getName(), $offs) : ' UTC';
                                 $this->fmt->startContain('date', true);
                                 $this->fmt->text('date', $timeAgo);
                                 $this->fmt->endContain();
                             }
                         } catch (\Exception $e) {
                             // not a date
                         }
                     }
                     // attempt to detect if this is a serialized string
                     static $unserializing = 0;
                     $isSerialized = $unserializing < 3 && ($subject[$length - 1] === ';' || $subject[$length - 1] === '}') && in_array($subject[0], array('s', 'a', 'O'), true) && ($subject[0] === 's' && $subject[$length - 2] !== '"' || preg_match("/^{$subject[0]}:[0-9]+:/s", $subject)) && ($unserialized = @unserialize($subject)) !== false;
                     if ($isSerialized) {
                         $unserializing++;
                         $this->fmt->startContain('serialized', true);
                         $this->evaluate($unserialized);
                         $this->fmt->endContain();
                         $unserializing--;
                     }
                     // try to find out if it's a json-encoded string;
                     // only do this for json-encoded arrays or objects, because other types have too generic formats
                     static $decodingJson = 0;
                     $isJson = !$isSerialized && $decodingJson < 3 && in_array($subject[0], array('{', '['), true);
                     if ($isJson) {
                         $decodingJson++;
                         $json = json_decode($subject);
                         if ($isJson = json_last_error() === JSON_ERROR_NONE) {
                             $this->fmt->startContain('json', true);
                             $this->evaluate($json);
                             $this->fmt->endContain();
                         }
                         $decodingJson--;
                     }
                     // attempt to match a regex
                     if ($length < 768) {
                         try {
                             $components = $this->splitRegex($subject);
                             if ($components) {
                                 $regex = '';
                                 $this->fmt->startContain('regex', true);
                                 foreach ($components as $component) {
                                     $this->fmt->text('regex-' . key($component), reset($component));
                                 }
                                 $this->fmt->endContain();
                             }
                         } catch (\Exception $e) {
                             // not a regex
                         }
                     }
                 }
             }
             return;
     }
     // if we reached this point, $subject must be an object
     // track objects to detect recursion
     static $hashes = array();
     // hash ID of this object
     $hash = spl_object_hash($subject);
     $recursion = isset($hashes[$hash]);
     // sometimes incomplete objects may be created from string unserialization,
     // if the class to which the object belongs wasn't included until the unserialization stage...
     if ($subject instanceof \__PHP_Incomplete_Class) {
         $this->fmt->text('object');
         $this->fmt->emptyGroup('incomplete');
         return;
     }
     // check cache at this point
     if (!$recursion && $this->fmt->didCache($hash)) {
         static::$debug['cacheHits']++;
         return;
     }
     $reflector = new \ReflectionObject($subject);
     $this->fmt->startContain('class');
     $this->fromReflector($reflector);
     $this->fmt->text('object', ' object');
     $this->fmt->endContain();
     // already been here?
     if ($recursion) {
         return $this->fmt->emptyGroup('recursion');
     }
     $hashes[$hash] = 1;
     $flags = \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED;
     if (static::$config['showPrivateMembers']) {
         $flags |= \ReflectionProperty::IS_PRIVATE;
     }
     $props = $reflector->getProperties($flags);
     $methods = array();
     if (static::$config['showMethods']) {
         $flags = \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED;
         if (static::$config['showPrivateMembers']) {
             $flags |= \ReflectionMethod::IS_PRIVATE;
         }
         $methods = $reflector->getMethods($flags);
     }
     $constants = $reflector->getConstants();
     $interfaces = $reflector->getInterfaces();
     $traits = static::$env['is54'] ? $reflector->getTraits() : array();
     $parents = static::getParentClasses($reflector);
     // work-around for https://bugs.php.net/bug.php?id=49154
     // @see http://stackoverflow.com/questions/15672287/strange-behavior-of-reflectiongetproperties-with-numeric-keys
     if (!static::$env['is54']) {
         $props = array_values(array_filter($props, function ($prop) use($subject) {
             return !$prop->isPublic() || property_exists($subject, $prop->name);
         }));
     }
     // no data to display?
     if (!$props && !$methods && !$constants && !$interfaces && !$traits) {
         unset($hashes[$hash]);
         return $this->fmt->emptyGroup();
     }
     if (!$this->fmt->startGroup()) {
         return;
     }
     // show contents for iterators
     if (static::$config['showIteratorContents'] && $reflector->isIterateable()) {
         $itContents = iterator_to_array($subject);
         $this->fmt->sectionTitle(sprintf('Contents (%d)', count($itContents)));
         foreach ($itContents as $key => $value) {
             $keyInfo = gettype($key);
             if ($keyInfo === 'string') {
                 $encoding = static::$env['mbStr'] ? mb_detect_encoding($key) : '';
                 $length = $encoding && $encoding !== 'ASCII' ? static::strLen($key) . '; ' . $encoding : static::strLen($key);
                 $keyInfo = sprintf('%s(%s)', $keyInfo, $length);
             }
             $this->fmt->startRow();
             $this->fmt->text(array('key', 'iterator'), $key, sprintf('Iterator key: %s', $keyInfo));
             $this->fmt->colDiv();
             $this->fmt->sep('=>');
             $this->fmt->colDiv();
             $this->evaluate($value);
             //$this->evaluate($value instanceof \Traversable ? ((count($value) > 0) ? $value : (string)$value) : $value);
             $this->fmt->endRow();
         }
     }
     // display the interfaces this objects' class implements
     if ($interfaces) {
         $items = array();
         $this->fmt->sectionTitle('Implements');
         $this->fmt->startRow();
         $this->fmt->startContain('interfaces');
         $i = 0;
         $count = count($interfaces);
         foreach ($interfaces as $name => $interface) {
             $this->fromReflector($interface);
             if (++$i < $count) {
                 $this->fmt->sep(', ');
             }
         }
         $this->fmt->endContain();
         $this->fmt->endRow();
     }
     // traits this objects' class uses
     if ($traits) {
         $items = array();
         $this->fmt->sectionTitle('Uses');
         $this->fmt->startRow();
         $this->fmt->startContain('traits');
         $i = 0;
         $count = count($traits);
         foreach ($traits as $name => $trait) {
             $this->fromReflector($trait);
             if (++$i < $count) {
                 $this->fmt->sep(', ');
             }
         }
         $this->fmt->endContain();
         $this->fmt->endRow();
     }
     // class constants
     if ($constants) {
         $this->fmt->sectionTitle('Constants');
         $max = max(array_map('static::strLen', array_keys($constants)));
         foreach ($constants as $name => $value) {
             $meta = null;
             $type = array('const');
             foreach ($parents as $parent) {
                 if ($parent->hasConstant($name)) {
                     if ($parent !== $reflector) {
                         $type[] = 'inherited';
                         $meta = array('sub' => array(array('Prototype defined by', $parent->name)));
                     }
                     break;
                 }
             }
             $this->fmt->startRow();
             $this->fmt->sep('::');
             $this->fmt->colDiv();
             $this->fmt->startContain($type);
             $this->fmt->text('name', $name, $meta, $this->linkify($parent, $name));
             $this->fmt->endContain();
             $this->fmt->colDiv($max - static::strLen($name));
             $this->fmt->sep('=');
             $this->fmt->colDiv();
             $this->evaluate($value);
             $this->fmt->endRow();
         }
     }
     // object/class properties
     if ($props) {
         $this->fmt->sectionTitle('Properties');
         $max = 0;
         foreach ($props as $idx => $prop) {
             if (($propNameLen = static::strLen($prop->name)) > $max) {
                 $max = $propNameLen;
             }
         }
         foreach ($props as $idx => $prop) {
             if ($this->hasInstanceTimedOut()) {
                 break;
             }
             $bubbles = array();
             $sourceClass = $prop->getDeclaringClass();
             $inherited = $reflector->getShortName() !== $sourceClass->getShortName();
             $meta = $sourceClass->isInternal() ? null : static::parseComment($prop->getDocComment());
             if ($meta) {
                 if ($inherited) {
                     $meta['sub'] = array(array('Declared in', $sourceClass->getShortName()));
                 }
                 if (isset($meta['tags']['var'][0])) {
                     $meta['left'] = $meta['tags']['var'][0][0];
                 }
                 unset($meta['tags']);
             }
             if ($prop->isProtected() || $prop->isPrivate()) {
                 $prop->setAccessible(true);
             }
             $value = $prop->getValue($subject);
             $this->fmt->startRow();
             $this->fmt->sep($prop->isStatic() ? '::' : '->');
             $this->fmt->colDiv();
             $bubbles = array();
             if ($prop->isProtected()) {
                 $bubbles[] = array('P', 'Protected');
             }
             if ($prop->isPrivate()) {
                 $bubbles[] = array('!', 'Private');
             }
             $this->fmt->bubbles($bubbles);
             $type = array('prop');
             if ($inherited) {
                 $type[] = 'inherited';
             }
             if ($prop->isPrivate()) {
                 $type[] = 'private';
             }
             $this->fmt->colDiv(2 - count($bubbles));
             $this->fmt->startContain($type);
             $this->fmt->text('name', $prop->name, $meta, $this->linkify($prop));
             $this->fmt->endContain();
             $this->fmt->colDiv($max - static::strLen($prop->name));
             $this->fmt->sep('=');
             $this->fmt->colDiv();
             $this->evaluate($value);
             $this->fmt->endRow();
         }
     }
     // class methods
     if ($methods && !$this->hasInstanceTimedOut()) {
         $this->fmt->sectionTitle('Methods');
         foreach ($methods as $idx => $method) {
             $this->fmt->startRow();
             $this->fmt->sep($method->isStatic() ? '::' : '->');
             $this->fmt->colDiv();
             $bubbles = array();
             if ($method->isAbstract()) {
                 $bubbles[] = array('A', 'Abstract');
             }
             if ($method->isFinal()) {
                 $bubbles[] = array('F', 'Final');
             }
             if ($method->isProtected()) {
                 $bubbles[] = array('P', 'Protected');
             }
             if ($method->isPrivate()) {
                 $bubbles[] = array('!', 'Private');
             }
             $this->fmt->bubbles($bubbles);
             $this->fmt->colDiv(4 - count($bubbles));
             // is this method inherited?
             $inherited = $reflector->getShortName() !== $method->getDeclaringClass()->getShortName();
             $type = array('method');
             if ($inherited) {
                 $type[] = 'inherited';
             }
             if ($method->isPrivate()) {
                 $type[] = 'private';
             }
             $this->fmt->startContain($type);
             $name = $method->name;
             if ($method->returnsReference()) {
                 $name = "&{$name}";
             }
             $this->fromReflector($method, $name, $reflector);
             $paramCom = $method->isInternal() ? array() : static::parseComment($method->getDocComment(), 'tags');
             $paramCom = empty($paramCom['param']) ? array() : $paramCom['param'];
             $paramCount = $method->getNumberOfParameters();
             $this->fmt->sep('(');
             // process arguments
             foreach ($method->getParameters() as $idx => $parameter) {
                 $meta = null;
                 $paramName = "\${$parameter->name}";
                 $optional = $parameter->isOptional();
                 $variadic = static::$env['is56'] && $parameter->isVariadic();
                 if ($parameter->isPassedByReference()) {
                     $paramName = "&{$paramName}";
                 }
                 if ($variadic) {
                     $paramName = "...{$paramName}";
                 }
                 $type = array('param');
                 if ($optional) {
                     $type[] = 'optional';
                 }
                 $this->fmt->startContain($type);
                 // attempt to build meta
                 foreach ($paramCom as $tag) {
                     list($pcTypes, $pcName, $pcDescription) = $tag;
                     if ($pcName !== $paramName) {
                         continue;
                     }
                     $meta = array('title' => $pcDescription);
                     if ($pcTypes) {
                         $meta['left'] = $pcTypes;
                     }
                     break;
                 }
                 try {
                     $paramClass = $parameter->getClass();
                 } catch (\Exception $e) {
                     // @see https://bugs.php.net/bug.php?id=32177&edit=1
                 }
                 if (!empty($paramClass)) {
                     $this->fmt->startContain('hint');
                     $this->fromReflector($paramClass, $paramClass->name);
                     $this->fmt->endContain();
                     $this->fmt->sep(' ');
                 }
                 if ($parameter->isArray()) {
                     $this->fmt->text('hint', 'array');
                     $this->fmt->sep(' ');
                 }
                 $this->fmt->text('name', $paramName, $meta);
                 if ($optional) {
                     $paramValue = $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null;
                     $this->fmt->sep(' = ');
                     if (static::$env['is546'] && !$parameter->getDeclaringFunction()->isInternal() && $parameter->isDefaultValueConstant()) {
                         $this->fmt->text('constant', $parameter->getDefaultValueConstantName(), 'Constant');
                     } else {
                         $this->evaluate($paramValue, true);
                     }
                 }
                 $this->fmt->endContain();
                 if ($idx < $paramCount - 1) {
                     $this->fmt->sep(', ');
                 }
             }
             $this->fmt->sep(')');
             $this->fmt->endContain();
             $this->fmt->endRow();
         }
     }
     unset($hashes[$hash]);
     $this->fmt->endGroup();
     $this->fmt->cacheLock($hash);
 }
Example #22
0
 public function properties($path)
 {
     $path = $this->preparePath($path);
     $file = new \SplFileInfo($path);
     $data['Name'] = $file->getFileName();
     $data['Type'] = $file->getType();
     $data['Size'] = $file->getSize() . ' b';
     $data['Location'] = $this->fileSystem->makePathRelative(pathinfo($file->getRealPath(), PATHINFO_DIRNAME), $this->root);
     return $data;
 }
Example #23
0
 /**
  * Returns basic information about created file/object
  * @param string $entityName name of class
  * @param mixed $entityId id of entity
  * @return null|array basic information
  */
 public function spy($entityName, $entityId)
 {
     $file = sprintf('%s/%s/%s.json', $this->config->dir, $entityName, $entityId);
     if (file_exists($file)) {
         $file = new \SplFileInfo($file);
         $result = array();
         $result['last_modified_time'] = $file->getATime();
         $result['size'] = $file->getSize();
         return $result;
     } else {
         return null;
     }
 }
Example #24
0
</td>
            </tr>
            </tbody>
        </table>
    </section>

    <section>
        <a class="anchor" id="memory"></a>

        <h3>Memory Usage</h3>

        <div class="row">
            <div class="span4">
                <div class="well well-small">
                    <h4><?php 
echo bsize($file_info->getSize());
?>
</h4>

                    <p>Cache file in use size</p>
                </div>
            </div>
            <div class="span4">
                <div class="well well-small">
                    <h4><?php 
echo bsize(disk_free_space($file_info->getPath()));
?>
</h4>

                    <p>Cache directory free size</p>
                </div>
 /**
  * Indexes all sFiles that were found in crawl() method.
  */
 public function indexCrawledDocuments()
 {
     foreach ($this->aFiles as $sFile) {
         $oRepoFile = new SplFileInfo($sFile);
         if (!$oRepoFile->isFile()) {
             continue;
         }
         $sFileName = $oRepoFile->getFilename();
         $sDocType = $this->mimeDecoding($oRepoFile->getExtension());
         if (!$this->checkDocType($sDocType, $sFileName)) {
             continue;
         }
         if (!$this->oMainControl->bCommandLineMode) {
             set_time_limit($this->iTimeLimit);
         }
         if ($this->sizeExceedsMaxDocSize($oRepoFile->getSize(), $sFileName)) {
             continue;
         }
         $sRepoFileRealPath = $oRepoFile->getRealPath();
         $timestampImage = wfTimestamp(TS_ISO_8601, $oRepoFile->getMTime());
         if ($this->checkExistence($sRepoFileRealPath, 'external', $timestampImage, $sFileName)) {
             continue;
         }
         $text = $this->getFileText($sRepoFileRealPath, $sFileName);
         $doc = $this->makeRepoDocument($sDocType, utf8_encode($sFileName), $text, utf8_encode($sRepoFileRealPath), $timestampImage);
         $this->writeLog($sFileName);
         wfRunHooks('BSExtendedSearchBeforeAddExternalFile', array($this, $oRepoFile, &$doc));
         if ($doc) {
             // mode and ERROR_MSG_KEY are only passed for the case when addsFile fails
             $this->oMainControl->addDocument($doc, $this->mode, self::S_ERROR_MSG_KEY);
         }
     }
 }
Example #26
0
<?php

include __DIR__ . '/../../../test/sample_dir/fix_mtimes.inc';
$info = new SplFileInfo(__DIR__ . '/../../sample_dir');
if (!$info->isFile()) {
    echo $info->getRealPath();
}
$info = new SplFileInfo(__DIR__ . '/../../sample_dir/file');
var_dump($info->getbaseName());
var_dump($info->getbaseName('.cpp'));
$info->getCTime();
$info->getGroup();
$info->getInode();
$info->getMTime();
$info->getOwner();
$info->getPerms();
$info->getSize();
$info->getType();
$info->isDir();
$info->isFile();
$info->isLink();
$info->isReadable();
$info->isWritable();
Example #27
0
 /**
  * Fetch item metadata
  *
  * @param string $key
  * @return array
  */
 public function fetchMetadata($key)
 {
     $info = new \SplFileInfo("{$this->root}/{$key}");
     return array('size' => $info->getSize(), 'change_time' => $info->getCTime());
 }
Example #28
0
 /**
  * Converts a SplFileInfo to a Model
  *
  * @param \SplFileInfo $aFile
  *
  * @return Model
  */
 public static function fileToModel(\SplFileInfo $aFile)
 {
     $model = new \stdClass();
     $model->{'dir'} = $aFile->isDir();
     $model->{'extension'} = $aFile->getExtension();
     $model->{'filename'} = $aFile->getFilename();
     $model->{'path'} = str_replace('\\', '/', $aFile->getPathname());
     if ($aFile->isReadable()) {
         $model->{'last_modified'} = $aFile->getMTime();
         $model->{'size'} = $aFile->getSize();
         $model->{'type'} = $aFile->getType();
     }
     return $model;
 }
Example #29
0
 /**
  * Get the total filesize for a given file or directory
  *
  * If $file is a file then just return the result of `filesize()`.
  * If $file is a directory then recursively calculate the size.
  *
  * @param \SplFileInfo   $file The file or directory you want to know the size of
  *
  * @return int           The total filesize of the file or directory
  */
 public function filesize(\SplFileInfo $file)
 {
     // Skip missing or unreadable files
     if (!file_exists($file->getPathname()) || !$file->getRealpath() || !$file->isReadable()) {
         return 0;
     }
     // If it's a file then just pass back the filesize
     if ($file->isFile()) {
         return $file->getSize();
     }
     // If it's a directory then pull it from the cached filesize array
     if ($file->isDir()) {
         return $this->directory_filesize($file);
     }
 }
 /**
  * {@inheritDoc}
  */
 public function process(MediaInterface $media, VariantInterface $variant, \SplFileInfo $source = NULL)
 {
     $options = $variant->getOptions();
     $result = $source;
     list($originalWidth, $originalHeight) = getimagesize($source->getPathName());
     $width = $originalWidth;
     $height = $originalHeight;
     if (is_array($options) && !empty($options)) {
         if ($this->imagine == NULL) {
             throw new ProviderProcessException(sprintf('Cannot process image "%s": Imagine library not installed or misconfigured', $media), $this, $media, $variant);
         }
         $options = $this->processOptions($options, $variant->getName(), $media->getContext());
         $destFile = sprintf('%s%s-temp-%s.%s', $this->tempDir, date('Y-m-d-h-i-s'), $source->getBasename('.' . $source->getExtension()), $options['format']);
         /**
          * @var \Imagine\Image\ImageInterface $image
          */
         $image = $this->imagine->open($source);
         if ($options['enlarge'] === TRUE || $originalWidth >= $options['width'] && $originalHeight >= $options['height']) {
             $width = $options['width'];
             $height = $options['height'];
             if ($options['resize'] == 'proportional') {
                 //calculate missing dimension
                 if ($width === NULL) {
                     $width = round($originalWidth * $height / $originalHeight);
                 } elseif ($height === NULL) {
                     $height = round($width * $originalHeight / $originalWidth);
                 }
             }
             $box = new \Imagine\Image\Box($width, $height);
             if ($options['resize'] == 'proportional' || $options['resize'] == 'stretch') {
                 $image->resize($box);
             } elseif ($options['resize'] == 'crop') {
                 $image = $image->thumbnail($box, \Imagine\Image\ImageInterface::THUMBNAIL_OUTBOUND);
             }
         }
         $image->save($destFile, array('quality' => $options['quality']));
         $this->addTempFile($destFile);
         $result = new \SplFileInfo($destFile);
     }
     //set variant metadata
     $variant->setMetaValue('size', $result->getSize());
     $variant->setMetaValue('width', $width);
     $variant->setMetaValue('height', $height);
     return $result;
 }