Example #1
0
 public function testSizeReturnsStreamSize()
 {
     $stream = Stream::make('Lorem ipsum dolor sit amet');
     $resource = $stream->getResource();
     $stat = fstat($resource);
     $this->assertEquals($stat['size'], $stream->getSize());
 }
function multipartUpload($client, $bucket, $keyprefix)
{
    //初始化分开上传,获取uploadid
    $args = array("Bucket" => $bucket, "Key" => $keyprefix . "EOFile");
    $uploadid = $client->initMultipartUpload($args);
    $uploadid = $uploadid["UploadId"];
    //获取到uploadid
    //开始上传
    $file = "D://IMG.jpg";
    //要上传的文件
    $partsize = 1024 * 100;
    $resource = fopen($file, "r");
    $stat = fstat($resource);
    $total = $stat["size"];
    //获取文件的总大小
    fclose($resource);
    $count = (int) ($total / $partsize + 1);
    //计算文件需要分几块上传
    for ($i = 0; $i < $count; $i++) {
        //依次上传每一块
        echo "upload" . $i . "\r\n";
        $args = array("Bucket" => $bucket, "Key" => $keyprefix . "EOFile", "LastPart" => $i === $count - 1, "Options" => array("partNumber" => $i + 1, "uploadId" => $uploadid), "ObjectMeta" => array("Content-Length" => min($partsize, $total - $partsize * $i)), "Content" => array("content" => $file, "seek_position" => $partsize * $i));
        $etag = $client->uploadPart($args);
        $etag = $etag["ETag"];
    }
    $parts = $client->listParts(array("Bucket" => $bucket, "Key" => $keyprefix . "EOFile", "Options" => array("uploadId" => $uploadid)));
    //结束上传
    $args = array("Bucket" => $bucket, "Key" => $keyprefix . "EOFile", "Options" => array("uploadId" => $uploadid), "Parts" => $parts["Parts"]);
    $result = $client->completeMultipartUpload($args);
    rangeGetAndCheckMd5($client, $bucket, $keyprefix . "EOFile", "D://testdown/down", base64_encode(md5_file("D://IMG.jpg")));
}
Example #3
0
 protected function parse()
 {
     $streams = array();
     if (!$this->readHeader()) {
         throw new Exception('Unable to read header');
     }
     /* directories are aligned on 128 bytes */
     $stats = fstat($this->fd);
     for ($pos = 512 + $this->dir_start * $this->block_size; $pos < $stats[7]; $pos += 128) {
         fseek($this->fd, $pos);
         $name = fread($this->fd, 64);
         $name_length = $this->readUnsignedShort();
         $name = utf8_encode(str_replace("", '', substr($name, 0, $name_length - 2)));
         $type = $this->readByte();
         $color = $this->readByte();
         $left_sib = $this->readUnsignedLong();
         $right_sib = $this->readUnsignedLong();
         $child = $this->readUnsignedLong();
         fseek($this->fd, 36, SEEK_CUR);
         $stream_start = $this->readUnsignedLong();
         $stream_size = $this->readUnsignedLong();
         switch ($type) {
             case self::STGTY_STREAM:
                 debug('Found stream ' . $name . ' starting at sector ' . sprintf('0x%X', $stream_start) . ' of size ' . $stream_size);
                 $streams[] = new OLEStream($name, $this, $this->fd, $stream_start, $stream_size);
                 break;
             case self::STGTY_ROOT:
                 debug('Found root ' . $name);
                 break;
         }
     }
     $this->streams = $streams;
 }
Example #4
0
 /**
  * {@inheritdoc}
  *
  * @return int|null Returns the size in bytes if known, or null if unknown.
  */
 public function getSize()
 {
     if (null === $this->stream) {
         return null;
     }
     return fstat($this->stream)['size'];
 }
Example #5
0
function eraseLastLineBreak($fileName)
{
    $file = fopen($fileName, 'r+') or die("can't open file");
    $stat = fstat($file);
    ftruncate($file, $stat['size'] - 2);
    fclose($file);
}
Example #6
0
 /**
  * @brief Logs admin page.
  *
  * @return string
  */
 function get()
 {
     $log_choices = array(LOGGER_NORMAL => 'Normal', LOGGER_TRACE => 'Trace', LOGGER_DEBUG => 'Debug', LOGGER_DATA => 'Data', LOGGER_ALL => 'All');
     $t = get_markup_template('admin_logs.tpl');
     $f = get_config('system', 'logfile');
     $data = '';
     if (!file_exists($f)) {
         $data = t("Error trying to open <strong>{$f}</strong> log file.\r\n<br/>Check to see if file {$f} exist and is \n\treadable.");
     } else {
         $fp = fopen($f, 'r');
         if (!$fp) {
             $data = t("Couldn't open <strong>{$f}</strong> log file.\r\n<br/>Check to see if file {$f} is readable.");
         } else {
             $fstat = fstat($fp);
             $size = $fstat['size'];
             if ($size != 0) {
                 if ($size > 5000000 || $size < 0) {
                     $size = 5000000;
                 }
                 $seek = fseek($fp, 0 - $size, SEEK_END);
                 if ($seek === 0) {
                     $data = escape_tags(fread($fp, $size));
                     while (!feof($fp)) {
                         $data .= escape_tags(fread($fp, 4096));
                     }
                 }
             }
             fclose($fp);
         }
     }
     return replace_macros($t, array('$title' => t('Administration'), '$page' => t('Logs'), '$submit' => t('Submit'), '$clear' => t('Clear'), '$data' => $data, '$baseurl' => z_root(), '$logname' => get_config('system', 'logfile'), '$debugging' => array('debugging', t("Debugging"), get_config('system', 'debugging'), ""), '$logfile' => array('logfile', t("Log file"), get_config('system', 'logfile'), t("Must be writable by web server. Relative to your top-level webserver directory.")), '$loglevel' => array('loglevel', t("Log level"), get_config('system', 'loglevel'), "", $log_choices), '$form_security_token' => get_form_security_token('admin_logs')));
 }
Example #7
0
 public function open($filename, $mode = "w", $permissions = 0777)
 {
     $created = false;
     if ($this->resource !== false) {
         return false;
     }
     if (file_exists($filename) === false) {
         if ($mode == "r" || $mode == "r+") {
             return false;
         } else {
             $created = true;
             $directory = dirname($filename);
             if (is_dir($directory) === false) {
                 mkdir($directory, $permissions, true);
                 chmod($directory, $permissions);
             }
         }
     }
     $this->resource = fopen($filename, $mode);
     if ($this->resource !== false) {
         if ($created === true) {
             chmod($filename, $permissions);
         }
         $this->stats = fstat($this->resource);
     }
     return true;
 }
Example #8
0
 public function testGetSize()
 {
     $resource = fopen(__FILE__, 'r');
     $expected = fstat($resource);
     $stream = new Stream($resource);
     $this->assertEquals($expected['size'], $stream->getSize());
 }
Example #9
0
function create_source_zip()
{
    // get the version
    $v_res = $GLOBALS['db']->query('select `version` from `version` limit 1')->fetch();
    $version = $v_res['version'];
    if (empty($version)) {
        $version = '';
    }
    $zip_filename = _DIR_ROOT . '/source/latest' . $version . '.zip';
    define('_SOURCE_ZIP_FILE', $zip_filename);
    if (file_exists($zip_filename)) {
        if (($fp = @fopen($zip_filename, 'r')) !== false) {
            $stats = fstat($fp);
            fclose($fp);
            // check if the source was created in the last hour
            if (time() - $stats['mtime'] <= 3600) {
                return;
            }
        }
        rename($zip_filename, _DIR_ROOT . '/source/latest' . time() . '.zip');
    }
    // Create the latest source of the application
    // in a ZIP archive
    $z = new ZipArchive();
    $z->open($zip_filename, ZipArchive::CREATE);
    add_directory_to_zip($z, _DIR_ROOT);
    // define a constant with the path to the file
    define('_SOURCE_ZIP_FILE', $zip_filename);
}
Example #10
0
 function cacheAge($cacheName)
 {
     $fp = fopen($this->cacheFolder . $cacheName, 'r');
     $fstat = fstat($fp);
     fclose($fp);
     return time() - $fstat['mtime'];
 }
Example #11
0
 protected function changed()
 {
     clearstatcache();
     $fstat = fstat($this->fh);
     $this->currentSize = $fstat['size'];
     return $this->size != $this->currentSize;
 }
 function url_stat($path, $flags)
 {
     if (isset($this->filehandle)) {
         return fstat($this->filehandle);
     }
     return null;
 }
Example #13
0
 function getFileSize()
 {
     if (false === ($stat = fstat($this->resource))) {
         throw new phpMorphy_Exception('Can`t invoke fstat for ' . $this->file_name . ' file');
     }
     return $stat['size'];
 }
Example #14
0
 public function __construct($file)
 {
     $this->file = $file;
     $this->handle = fopen($this->file, self::MODE);
     $stats = fstat($this->handle);
     $this->size = $stats['size'];
 }
Example #15
0
 /**
  * {@inheritdoc}
  */
 public function isDirect()
 {
     if ($this->isDirect === null) {
         $this->isDirect = 020000 === (fstat(STDOUT)['mode'] & 0170000);
     }
     return $this->isDirect;
 }
 public function testStat()
 {
     $this->assertEquals(0, fstat($this->resource)['size']);
     fwrite($this->resource, 'foo');
     fflush($this->resource);
     $this->assertGreaterThan(0, fstat($this->resource)['size']);
 }
Example #17
0
 static function stat($path)
 {
     $fp = fopen($path, "r");
     $fstat = fstat($fp);
     fclose($fp);
     return _hx_anonymous(array("gid" => $fstat['gid'], "uid" => $fstat['uid'], "atime" => Date::fromTime($fstat['atime'] * 1000), "mtime" => Date::fromTime($fstat['mtime'] * 1000), "ctime" => Date::fromTime($fstat['ctime'] * 1000), "dev" => $fstat['dev'], "ino" => $fstat['ino'], "nlink" => $fstat['nlink'], "rdev" => $fstat['rdev'], "size" => $fstat['size'], "mode" => $fstat['mode']));
 }
Example #18
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     $this->stderrIsNotStdout = fstat(\STDERR)['dev'] != fstat(\STDOUT)['dev'];
     $this->stderrSupportsColors = Console::streamSupportsAnsiColors(\STDERR);
     $this->stdoutSupportsColors = Console::streamSupportsAnsiColors(\STDOUT);
 }
Example #19
0
 public function dump($var)
 {
     $result = array();
     $stream_vars = stream_get_meta_data($var);
     $fstat = fstat($var);
     $real_path = realpath($stream_vars['uri']);
     $result['file'] = $real_path;
     $result['mode'] = $fstat['mode'];
     $result['size'] = $this->_formatSize($fstat['size']);
     $permissions = array('read');
     if (is_writable($real_path)) {
         $permissions[] = 'write';
     }
     if (is_executable($real_path)) {
         $permissions[] = 'execute';
     }
     if (is_link($real_path)) {
         $permissions[] = 'link';
     }
     if (is_dir($real_path)) {
         $permissions[] = 'directory';
     }
     $result['permissions'] = implode(', ', $permissions);
     return $result;
 }
Example #20
0
function get_poison_emails($seed, $count)
{
    global $globals;
    $fd = fopen($globals->poison->file, 'r');
    $size = fstat($fd);
    $size = $size['size'];
    $seed = crc32($seed . date('m-Y')) % $size;
    if ($seed < 0) {
        $seed = $size + $seed;
    }
    fseek($fd, $seed);
    fgets($fd);
    $emails = array();
    $i = 0;
    while (!feof($fd) && $i < $count) {
        $line = trim(fgets($fd));
        if (strlen($line) > 0) {
            $emails[] = $line;
            ++$seed;
        }
        ++$i;
    }
    fclose($fd);
    return $emails;
}
Example #21
0
 public function testStat()
 {
     $fh = fopen(self::$shareUrl . '/LICENSE', 'r');
     $stat = fstat($fh);
     static::assertStat($stat);
     static::assertSame(1066, $stat['size']);
 }
 public function run($queueItemId, $lastFseekPosition = 0)
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     /** @var DeferredQueue $item */
     $item = DeferredQueue::loadModel($queueItemId, false, false, 0, new NotFoundHttpException());
     if ($item->status === DeferredQueue::STATUS_SCHEDULED || $item->status === DeferredQueue::STATUS_DISABLED) {
         return new ReportingTaskResponse(['status' => $item->status]);
     } else {
         if (empty($item->output_file)) {
             return new ReportingTaskResponse(['error' => true, 'errorMessage' => Yii::t('deferred-tasks', 'Field output_file is empty for queue item.')]);
         }
         if (file_exists($item->output_file) && is_readable($item->output_file)) {
             $fp = fopen($item->output_file, 'r');
             $stat = fstat($fp);
             $fseekStatus = fseek($fp, $lastFseekPosition);
             if ($fseekStatus !== 0) {
                 fclose($fp);
                 return new ReportingTaskResponse(['error' => true, 'errorMessage' => Yii::t('deferred-tasks', 'Unable to fseek file.'), 'lastFseekPosition' => $lastFseekPosition, 'newOutput' => '', 'status' => $item->status, 'nextQueue' => $item->next_task_id]);
             }
             $bytesToRead = $stat['size'] - $lastFseekPosition;
             if ($bytesToRead > 0) {
                 $data = fread($fp, $bytesToRead);
             } else {
                 $data = '';
             }
             $lastFseekPosition += $bytesToRead;
             fclose($fp);
             return new ReportingTaskResponse(['status' => $item->status, 'nextQueue' => $item->next_task_id, 'error' => false, 'newOutput' => $data, 'lastFseekPosition' => $lastFseekPosition, 'taskStatusCode' => $item->exit_code]);
         } else {
             return new ReportingTaskResponse(['error' => true, 'errorMessage' => Yii::t('deferred-tasks', 'Error accessing output file.'), 'lastFseekPosition' => $lastFseekPosition, 'newOutput' => '', 'status' => $item->status, 'nextQueue' => $item->next_task_id]);
         }
     }
 }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public function getSize()
 {
     if (!is_resource($this->resource)) {
         return null;
     }
     return fstat($this->resource)['size'];
 }
 function tail($callback)
 {
     if ($fp = fopen($this->tailfile, "rb")) {
         fseek($fp, 0, SEEK_END);
         $fs = fstat($fp);
         $ino = $fs['ino'];
         while ($this->publish_count < $this->max_lines_before_quit || $this->max_lines_before_quit == 0) {
             do {
                 do {
                     $ino = $this->rotate($ino);
                     if ($ino == FALSE) {
                         return FALSE;
                     }
                     $c = fgetc($fp);
                     $line .= $c;
                 } while ($c != "\n" && $c != "\r" && $c);
                 if ($c === FALSE) {
                     sleep(1);
                 }
             } while ($c != "\n" && $c != "\r");
             $this->publish_count++;
             call_user_func($callback, $line);
             $line = '';
             $c = '';
         }
         fclose($fp);
     } else {
         echo "Can't open file\n";
     }
 }
Example #25
0
 /**
  * Calculates length of the request body, adds proper headers
  *
  * @param    array   associative array of request headers, this method will
  *                   add proper 'Content-Length' and 'Content-Type' headers
  *                   to this array (or remove them if not needed)
  */
 protected function calculateRequestLength(&$headers)
 {
     $this->requestBody = $this->request->getBody();
     if (is_string($this->requestBody)) {
         $this->contentLength = strlen($this->requestBody);
     } elseif (is_resource($this->requestBody)) {
         $stat = fstat($this->requestBody);
         $this->contentLength = $stat['size'];
         rewind($this->requestBody);
     } else {
         $this->contentLength = $this->requestBody->getLength();
         $headers['content-type'] = 'multipart/form-data; boundary=' . $this->requestBody->getBoundary();
         $this->requestBody->rewind();
     }
     if (in_array($this->request->getMethod(), self::$bodyDisallowed) || 0 == $this->contentLength) {
         // No body: send a Content-Length header nonetheless (request #12900),
         // but do that only for methods that require a body (bug #14740)
         if (in_array($this->request->getMethod(), self::$bodyRequired)) {
             $headers['content-length'] = 0;
         } else {
             unset($headers['content-length']);
             // if the method doesn't require a body and doesn't have a
             // body, don't send a Content-Type header. (request #16799)
             unset($headers['content-type']);
         }
     } else {
         if (empty($headers['content-type'])) {
             $headers['content-type'] = 'application/x-www-form-urlencoded';
         }
         $headers['content-length'] = $this->contentLength;
     }
 }
Example #26
0
 /**
  * ZIPs files (from an array) into a zip file and return the data associated with the
  * created ZIP.
  *
  * @param string $filename ZIP fullpath and name (we want to create)
  * @param array $bagelems Array of files in a format like the one produced by Filfiles() class (we need the path and filename props).
  */
 public static function zipfiles($filename = './tempname.zip', $bagelems = array())
 {
     $fsp = preg_split('/\\//', $filename);
     $filenamebase = $fsp[count($fsp) - 1];
     $toret = array('log' => array(), 'filefullpath' => $filename, 'filename' => $filenamebase, 'zipinfo' => array());
     $zip = new ZipArchive();
     if (count($bagelems) > 0) {
         if ($zip->open($filename, ZIPARCHIVE::CREATE) !== true) {
             $toret['log'][] = "cannot open {$filename}";
         } else {
             foreach ($bagelems as $me) {
                 $zip->addFile($me['path'] . '/' . $me['filename'], $me['filename']);
             }
             $toret['zipinfo']["numfiles"] = $zip->numFiles;
             $toret['zipinfo']["status"] = $zip->status;
         }
     } else {
         $toret['log'][] = 'Nothing in the file array';
     }
     $zip->close();
     $fp = fopen($filename, "r");
     $toret['fstat'] = array_slice(fstat($fp), 13);
     fclose($fp);
     return $toret;
 }
Example #27
0
 /**
  * Creates a new Buffer given a resource, a path or URL,
  * If the first argument is a string (a path or URL) the
  * second argument specifies the mode to use to open it.
  *
  * @param string|resource $resource
  * @param string $mode
  */
 public function __construct($resource = null, $mode = null)
 {
     parent::__construct($resource, $mode);
     $this->readPosition = 0;
     $stat = fstat($this->resource);
     $this->writePosition = $stat['size'];
 }
 public static function compileTo($outputFile)
 {
     if (!count(self::$loadedFiles)) {
         return;
     }
     $fp = fopen($outputFile, "a+");
     if (flock($fp, LOCK_EX)) {
         if ($filesize = filesize($outputFile)) {
             fseek($fp, 0);
             $currentFile = fread($fp, $filesize);
         } else {
             $currentFile = '';
         }
         if (!$currentFile) {
             $appendSource = "<?php\n";
             $existingClasses = array();
         } else {
             $appendSource = '';
             $existingClasses = self::getClassesFromSource($currentFile);
         }
         for ($i = 0; $i < count(self::$loadedFiles); $i++) {
             $filename = self::$loadedFiles[$i];
             if (self::$excludeRegexp && preg_match(self::$excludeRegexp, $filename)) {
                 continue;
             }
             $f = @fopen($filename, "r", true);
             $fstat = fstat($f);
             $file = fread($f, $fstat['size']);
             fclose($f);
             $classes = self::getClassesFromSource($file);
             if (!count(array_intersect($existingClasses, $classes))) {
                 if (strpos($file, '__FILE__') === false) {
                     Lms_Debug::debug("Complile autoload {$filename}");
                     $endFile = substr($file, -2) == '?>' ? -2 : null;
                     $appendSource .= $endFile === null ? substr($file, 5) : substr($file, 5, -2);
                 } else {
                     //Потенциально ненадежно, но работает
                     $filePath = self::realPath($filename);
                     if ($filePath) {
                         Lms_Debug::warn("Complile autoload with __FILE__ constant {$filename}");
                         $file = str_replace('__FILE__', "'{$filePath}'", $file);
                         $endFile = substr($file, -2) == '?>' ? -2 : null;
                         $appendSource .= $endFile === null ? substr($file, 5) : substr($file, 5, -2);
                     }
                 }
             } else {
                 Lms_Debug::debug("Conflict detect on file {$filename}. Complile autoload terminated.");
                 $appendSource = '';
                 break;
             }
         }
         if ($appendSource) {
             fseek($fp, 0, SEEK_END);
             fwrite($fp, $appendSource);
         }
         flock($fp, LOCK_UN);
     }
     fclose($fp);
 }
Example #29
0
 public function switchAction($action, $httpVars, $filesVars)
 {
     if (!isset($this->actions[$action])) {
         return false;
     }
     $repository = ConfService::getRepository();
     if (!$repository->detectStreamWrapper(true)) {
         return false;
     }
     if (!isset($this->pluginConf)) {
         $this->pluginConf = array("GENERATE_THUMBNAIL" => false);
     }
     $streamData = $repository->streamData;
     $this->streamData = $streamData;
     $destStreamURL = $streamData["protocol"] . "://" . $repository->getId();
     if ($action == "preview_data_proxy") {
         $file = AJXP_Utils::decodeSecureMagic($httpVars["file"]);
         if (!file_exists($destStreamURL . $file)) {
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: 0");
             return;
         }
         if (isset($httpVars["get_thumb"]) && $this->getFilteredOption("GENERATE_THUMBNAIL", $repository->getId())) {
             $dimension = 200;
             if (isset($httpVars["dimension"]) && is_numeric($httpVars["dimension"])) {
                 $dimension = $httpVars["dimension"];
             }
             $this->currentDimension = $dimension;
             $cacheItem = AJXP_Cache::getItem("diaporama_" . $dimension, $destStreamURL . $file, array($this, "generateThumbnail"));
             $data = $cacheItem->getData();
             $cId = $cacheItem->getId();
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($cId)) . "; name=\"" . basename($cId) . "\"");
             header("Content-Length: " . strlen($data));
             header('Cache-Control: public');
             header("Pragma:");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
             header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
             print $data;
         } else {
             //$filesize = filesize($destStreamURL.$file);
             $node = new AJXP_Node($destStreamURL . $file);
             $fp = fopen($destStreamURL . $file, "r");
             $stat = fstat($fp);
             $filesize = $stat["size"];
             header("Content-Type: " . AJXP_Utils::getImageMimeType(basename($file)) . "; name=\"" . basename($file) . "\"");
             header("Content-Length: " . $filesize);
             header('Cache-Control: public');
             header("Pragma:");
             header("Last-Modified: " . gmdate("D, d M Y H:i:s", time() - 10000) . " GMT");
             header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5 * 24 * 3600) . " GMT");
             $class = $streamData["classname"];
             $stream = fopen("php://output", "a");
             call_user_func(array($streamData["classname"], "copyFileInStream"), $destStreamURL . $file, $stream);
             fflush($stream);
             fclose($stream);
             AJXP_Controller::applyHook("node.read", array($node));
         }
     }
 }
Example #30
0
File: File.php Project: khsk/ethnam
 /**
  *  ログ出力を開始する
  *
  *  @access public
  */
 function begin()
 {
     $this->fp = fopen($this->file, 'a');
     $st = fstat($this->fp);
     if (function_exists("posix_getuid") && posix_getuid() == $st[4]) {
         chmod($this->file, intval($this->mode, 8));
     }
 }