/** * Invokes system_retrieve_file() in several scenarios. */ function testFileRetrieving() { // Test 404 handling by trying to fetch a randomly named file. drupal_mkdir($sourcedir = 'public://' . $this->randomMachineName()); $filename = 'Файл для тестирования ' . $this->randomMachineName(); $url = file_create_url($sourcedir . '/' . $filename); $retrieved_file = system_retrieve_file($url); $this->assertFalse($retrieved_file, 'Non-existent file not fetched.'); // Actually create that file, download it via HTTP and test the returned path. file_put_contents($sourcedir . '/' . $filename, 'testing'); $retrieved_file = system_retrieve_file($url); // URLs could not contains characters outside the ASCII set so $filename // has to be encoded. $encoded_filename = rawurlencode($filename); $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).'); $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).'); $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).'); file_unmanaged_delete($retrieved_file); // Test downloading file to a different location. drupal_mkdir($targetdir = 'temporary://' . $this->randomMachineName()); $retrieved_file = system_retrieve_file($url, $targetdir); $this->assertEqual($retrieved_file, "{$targetdir}/{$encoded_filename}", 'Sane path for downloaded file returned (temporary:// scheme).'); $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).'); $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).'); file_unmanaged_delete($retrieved_file); file_unmanaged_delete_recursive($sourcedir); file_unmanaged_delete_recursive($targetdir); }
private function openImage($file) { // *** Get extension $extension = strtolower(strrchr($file, '.')); $file_size = @filesize($file) / 1024 / 1024; // magic number convert bytes to mb $image_size_limit = 0.5; // sorry for the magic numbering... can't get a good read on how to programatically fix this. // if we're about to try to load a massive image... // don't if ($file_size >= $image_size_limit || $file_size == 0) { return false; } switch ($extension) { case '.jpg': case '.jpeg': $img = imagecreatefromjpeg($file); break; case '.gif': $img = @imagecreatefromgif($file); break; case '.png': $img = @imagecreatefrompng($file); break; default: $img = false; break; } return $img; }
/** * Return JS configuration of the htmlArea plugins registered by the extension * * @return string JS configuration for registered plugins */ public function buildJavascriptConfiguration() { $schema = array('types' => array(), 'properties' => array()); // Parse configured schemas if (is_array($this->configuration['thisConfig']['schema.']) && is_array($this->configuration['thisConfig']['schema.']['sources.'])) { foreach ($this->configuration['thisConfig']['schema.']['sources.'] as $source) { $fileName = trim($source); $absolutePath = GeneralUtility::getFileAbsFileName($fileName); // Fallback to default schema file if configured file does not exists or is of zero size if (!$fileName || !file_exists($absolutePath) || !filesize($absolutePath)) { $fileName = 'EXT:' . $this->extensionKey . '/Resources/Public/Rdf/MicrodataSchema/SchemaOrgAll.rdf'; } $fileName = $this->getFullFileName($fileName); $rdf = file_get_contents($fileName); if ($rdf) { $this->parseSchema($rdf, $schema); } } } uasort($schema['types'], array($this, 'compareLabels')); uasort($schema['properties'], array($this, 'compareLabels')); // Insert no type and no property entries $languageService = $this->getLanguageService(); $noSchema = $languageService->sL('LLL:EXT:rtehtmlarea/Resources/Private/Language/Plugins/MicrodataSchema/locallang.xlf:No type'); $noProperty = $languageService->sL('LLL:EXT:rtehtmlarea/Resources/Private/Language/Plugins/MicrodataSchema/locallang.xlf:No property'); array_unshift($schema['types'], array('name' => 'none', 'label' => $noSchema)); array_unshift($schema['properties'], array('name' => 'none', 'label' => $noProperty)); // Store json encoded array in temporary file return 'RTEarea[editornumber].schemaUrl = "' . $this->writeTemporaryFile('schema_' . $this->configuration['language'], 'js', json_encode($schema)) . '";'; }
function fsize($file) { // filesize will only return the lower 32 bits of // the file's size! Make it unsigned. $fmod = filesize($file); if ($fmod < 0) { $fmod += 2.0 * (PHP_INT_MAX + 1); } // find the upper 32 bits $i = 0; $myfile = fopen($file, "r"); // feof has undefined behaviour for big files. // after we hit the eof with fseek, // fread may not be able to detect the eof, // but it also can't read bytes, so use it as an // indicator. while (strlen(fread($myfile, 1)) === 1) { fseek($myfile, PHP_INT_MAX, SEEK_CUR); $i++; } fclose($myfile); // $i is a multiplier for PHP_INT_MAX byte blocks. // return to the last multiple of 4, as filesize has modulo of 4 GB (lower 32 bits) if ($i % 2 == 1) { $i--; } // add the lower 32 bit to our PHP_INT_MAX multiplier return (double) $i * (PHP_INT_MAX + 1) + $fmod; }
public function dwld() { $this->min(); if (is_numeric($this->getParam("id"))) { $this->download->newDownload(); if ($this->download->getIsLocal()) { $url = OWEB_DIR_DATA . "/downloads/" . $this->download->getUrl(); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($url) . '";'); readfile($url); } else { $url = OWEB_DIR_DATA . "/downloads/" . $this->download->getUrl(); header("Content-Disposition: attachment; filename=" . basename($url)); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($url)); flush(); // this doesn't really matter. $fp = fopen($url, "r"); while (!feof($fp)) { echo fread($fp, 65536); flush(); // this is essential for large downloads } fclose($fp); } } else { throw new \Model\downloads\exception\DownloadCantBeFind("No Download ID given"); } }
function fa_cache_avatar($avatar, $id_or_email, $size, $default, $alt) { $avatar = str_replace(array("www.gravatar.com", "0.gravatar.com", "1.gravatar.com", "2.gravatar.com"), "cn.gravatar.com", $avatar); $tmp = strpos($avatar, 'http'); $url = get_avatar_url($id_or_email, $size); $url = str_replace(array("www.gravatar.com", "0.gravatar.com", "1.gravatar.com", "2.gravatar.com"), "cn.gravatar.com", $url); $avatar2x = get_avatar_url($id_or_email, $size * 2); $avatar2x = str_replace(array("www.gravatar.com", "0.gravatar.com", "1.gravatar.com", "2.gravatar.com"), "cn.gravatar.com", $avatar2x); $g = substr($avatar, $tmp, strpos($avatar, "'", $tmp) - $tmp); $tmp = strpos($g, 'avatar/') + 7; $f = substr($g, $tmp, strpos($g, "?", $tmp) - $tmp); $w = home_url(); $e = ABSPATH . 'avatar/' . $size . '*' . $f . '.jpg'; $e2x = ABSPATH . 'avatar/' . $size * 2 . '*' . $f . '.jpg'; $t = 1209600; if ((!is_file($e) || time() - filemtime($e) > $t) && (!is_file($e2x) || time() - filemtime($e2x) > $t)) { copy(htmlspecialchars_decode($g), $e); copy(htmlspecialchars_decode($avatar2x), $e2x); } else { $avatar = $w . '/avatar/' . $size . '*' . $f . '.jpg'; $avatar2x = $w . '/avatar/' . $size * 2 . '*' . $f . '.jpg'; if (filesize($e) < 1000) { copy($w . '/avatar/default.jpg', $e); } if (filesize($e2x) < 1000) { copy($w . '/avatar/default.jpg', $e2x); } $avatar = "<img alt='{$alt}' src='{$avatar}' srcset='{$avatar2x}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />"; } return $avatar; }
/** * The main function in the class * * @return string HTML content */ function cacheFiles() { $content = ''; // CURRENT: $content .= '<strong>1: The current cache files:</strong>' . Tx_Extdeveval_Compatibility::viewArray(t3lib_extMgm::currentCacheFiles()); // REMOVING? if (t3lib_div::_GP('REMOVE_temp_CACHED')) { $number = $this->removeCacheFiles(); $content .= '<hr /><p><strong>2: Tried to remove ' . $number . ' cache files.</strong></p>'; } if (t3lib_div::_GP('REMOVE_temp_CACHED_ALL')) { $content .= '<hr /><p><strong>2: Removing ALL "temp_CACHED_*" files:</strong></p>' . $this->removeALLtempCachedFiles(); } $files = t3lib_div::getFilesInDir(PATH_typo3conf, 'php'); $tRows = array(); foreach ($files as $f) { $tRows[] = '<tr> <td>' . htmlspecialchars($f) . '</td> <td>' . t3lib_div::formatSize(filesize(PATH_typo3conf . $f)) . '</td> </tr>'; } $content .= '<br /><strong>3: PHP files (now) in "' . PATH_typo3conf . '":</strong><br /> <table border="1">' . implode('', $tRows) . '</table> <input type="submit" name="REMOVE_temp_CACHED" value="REMOVE current temp_CACHED files" /> <input type="submit" name="REMOVE_temp_CACHED_ALL" value="REMOVE ALL temp_CACHED_* files" /> <input type="submit" name="_" value="Refresh" /> '; return $content; }
function getDirectorySize($path) { $totalsize = 0; $totalcount = 0; $dircount = 0; if ($handle = opendir($path)) { while (false !== ($file = readdir($handle))) { $nextpath = $path . '/' . $file; if ($file != '.' && $file != '..' && !is_link($nextpath)) { if (is_dir($nextpath)) { $dircount++; $result = getDirectorySize($nextpath); $totalsize += $result['size']; $totalcount += $result['count']; $dircount += $result['dircount']; } elseif (is_file($nextpath)) { $totalsize += filesize($nextpath); $totalcount++; } } } } closedir($handle); $total['size'] = $totalsize; $total['count'] = $totalcount; $total['dircount'] = $dircount; return $total; }
public function display($cachable = false, $urlparams = false) { JRequest::setVar('view', JRequest::getCmd('view', 'Orphans')); if (isset($_POST['_orphanaction']) && $_POST['_orphanaction'] == "zipIt") { $file = tempnam("tmp", "zip"); $zip = new ZipArchive(); $zip->open($file, ZipArchive::OVERWRITE); foreach ($_POST['tozip'] as $_file) { $zip->addFile(JPATH_ROOT . "/" . $_file, $_file); } $zip->close(); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($file)); header('Content-Disposition: attachment; filename="orphans.zip"'); readfile($file); unlink($file); die; } else { if (isset($_POST['_orphanaction']) && $_POST['_orphanaction'] == "delete" && isset($_POST['_confirmAction'])) { foreach ($_POST['tozip'] as $_file) { unlink(JPATH_ROOT . "/" . $_file); } } } // call parent behavior parent::display($cachable); }
public function size() : int { if ($this->fileCount === 0) { return 0; } return filesize($this->pathToZip); }
public function getDocuments($name) { if (!file_exists($this->_getFilePathName($name))) { return array(); } $fp = fopen($this->_getFilePathName($name), 'r'); $filesize = filesize($this->_getFilePathName($name)); if ($filesize % MULTIINDEX_DOCUMENTBYTESIZE != 0) { throw new Exception('Filesize not correct index is corrupt!'); } $ret = array(); $count = 0; for ($i = 0; $i < $filesize / MULTIINDEX_DOCUMENTBYTESIZE; $i++) { $bindata1 = fread($fp, MULTIINDEX_DOCUMENTINTEGERBYTESIZE); $bindata2 = fread($fp, MULTIINDEX_DOCUMENTINTEGERBYTESIZE); $bindata3 = fread($fp, MULTIINDEX_DOCUMENTINTEGERBYTESIZE); $data1 = unpack('i', $bindata1); $data2 = unpack('i', $bindata2); $data3 = unpack('i', $bindata3); $ret[] = array($data1[1], $data2[1], $data3[1]); $count++; if ($count == MULTIINDEX_DOCUMENTRETURN) { break; } } fclose($fp); return $ret; }
/** * Uploads file to FTP server. * @return void */ public function writeFile($local, $remote, callable $progress = NULL) { $size = max(filesize($local), 1); $retry = self::RETRIES; upload: $blocks = 0; do { if ($progress) { $progress(min($blocks * self::BLOCK_SIZE / $size, 100)); } try { $ret = $blocks === 0 ? $this->ftp('nb_put', $remote, $local, FTP_BINARY) : $this->ftp('nb_continue'); } catch (FtpException $e) { @ftp_close($this->connection); // intentionally @ $this->connect(); if (--$retry) { goto upload; } throw new FtpException("Cannot upload file {$local}, number of retries exceeded. Error: {$e->getMessage()}"); } $blocks++; } while ($ret === FTP_MOREDATA); if ($progress) { $progress(100); } }
/** * 遍历目录内容 * @param string $dirName 目录名 * @param string $exts 扩展名 * @param int $son 是否显示子目录 * @param array $list * @return array */ static function tree($dirName=null, $exts = '', $son = 0, $list = array()) { if(is_null($dirName))$dirName='.'; $dirPath = self::dirPath($dirName); static $id = 0; if (is_array($exts)) $exts = implode("|", $exts); foreach (glob($dirPath . '*') as $v) { $id++; if (is_dir($v) || !$exts || preg_match("/\.($exts)/i", $v)) { $list [$id] ['name'] = basename($v); $list [$id] ['path'] = str_replace("\\", "/", realpath($v)); $list [$id] ['type'] = filetype($v); $list [$id] ['filemtime'] = filemtime($v); $list [$id] ['fileatime'] = fileatime($v); $list [$id] ['size'] = filesize($v); $list [$id] ['iswrite'] = is_writeable($v) ? 1 : 0; $list [$id] ['isread'] = is_readable($v) ? 1 : 0; } if ($son) { if (is_dir($v)) { $list = self::tree($v, $exts, $son = 1, $list); } } } return $list; }
public static function download($fullPath) { if ($fd = fopen($fullPath, 'r')) { $fsize = filesize($fullPath); $path_parts = pathinfo($fullPath); $ext = strtolower($path_parts['extension']); switch ($ext) { case 'pdf': header('Content-type: application/pdf'); // add here more headers for diff. extensions header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"'); // use 'attachment' to force a download break; default: header('Content-type: application/octet-stream'); header('Content-Disposition: filename="' . $path_parts['basename'] . '"'); break; } header("Content-length: {$fsize}"); header('Cache-control: private'); //use this to open files directly while (!feof($fd)) { $buffer = fread($fd, 2048); echo $buffer; } } fclose($fd); }
function final_extract_install() { global $CONFIG, $lang_plugin_final_extract, $lang_plugin_final_extract_config, $thisplugin; require 'plugins/final_extract/configuration.php'; require 'include/sql_parse.php'; if (!isset($CONFIG['fex_enable'])) { $query = "INSERT INTO " . $CONFIG['TABLE_CONFIG'] . " VALUES ('fex_enable', '1');"; cpg_db_query($query); // create table $db_schema = $thisplugin->fullpath . '/schema.sql'; $sql_query = fread(fopen($db_schema, 'r'), filesize($db_schema)); $sql_query = preg_replace('/CPG_/', $CONFIG['TABLE_PREFIX'], $sql_query); $sql_query = remove_remarks($sql_query); $sql_query = split_sql_file($sql_query, ';'); foreach ($sql_query as $q) { cpg_db_query($q); } // Put default setting $db_schema = $thisplugin->fullpath . '/basic.sql'; $sql_query = fread(fopen($db_schema, 'r'), filesize($db_schema)); $sql_query = preg_replace('/CPG_/', $CONFIG['TABLE_PREFIX'], $sql_query); $sql_query = remove_remarks($sql_query); $sql_query = split_sql_file($sql_query, ';'); foreach ($sql_query as $q) { cpg_db_query($q); } } return true; }
public function createUploadFile() { $filename = tempnam($this->uploadDir, 'zfc'); file_put_contents($filename, sprintf('File created by %s', __CLASS__)); $file = ['name' => 'test.txt', 'type' => 'text/plain', 'tmp_name' => $filename, 'size' => filesize($filename), 'error' => UPLOAD_ERR_OK]; return $file; }
/** * Processes the given task. * * @param TaskInterface $task * @throws \InvalidArgumentException */ public function processTask(TaskInterface $task) { if (!$this->canProcessTask($task)) { throw new \InvalidArgumentException('Cannot process task of type "' . $task->getType() . '.' . $task->getName() . '"', 1350570621); } $helper = $this->getHelperByTaskName($task->getName()); try { $result = $helper->process($task); if ($result === NULL) { $task->setExecuted(TRUE); $task->getTargetFile()->setUsesOriginalFile(); } elseif (file_exists($result['filePath'])) { $task->setExecuted(TRUE); $graphicalFunctions = $this->getGraphicalFunctionsObject(); $imageDimensions = $graphicalFunctions->getImageDimensions($result['filePath']); $task->getTargetFile()->setName($task->getTargetFileName()); $task->getTargetFile()->updateProperties(array('width' => $imageDimensions[0], 'height' => $imageDimensions[1], 'size' => filesize($result['filePath']))); $task->getTargetFile()->updateWithLocalFile($result['filePath']); } else { // Seems we have no valid processing result $task->setExecuted(FALSE); } } catch (\Exception $e) { $task->setExecuted(FALSE); } }
public function __constructor($hostsFile, $hostsConfigFile = DEFAULT_CONFIG_FILE) { $this->hostsFile = $hostsFile; if (file_exists($hostsConfigFile) && filesize($hostsConfigFile)) { $this->hostsConfigFile = $hostsConfigFile; } }
/** * Task to run pending migrations * * @return null */ protected function _execute(array $params) { $migrations = new MigrationManager(); Database::$default = $params['db']; $this->db = Database::instance(); $db_config = Kohana::$config->load('database')->{$params['db']}; if (!ORM::factory('Migration')->is_installed()) { /** * Get platform from database config */ $platform = strtolower($db_config['type']); if ('mysqli' == $platform) { $platform = 'mysql'; } /** * Get SQL from file for selected platform */ $file = realpath(substr(__DIR__, 0, strlen(__DIR__) - strlen('classes/Task/Db')) . 'sql/' . $platform . '.sql'); $handle = fopen($file, 'rb'); $sql_create = fread($handle, filesize($file)); $this->db->query(0, $sql_create); $msg = Minion_CLI::color("-----------------------------\n", 'green'); $msg .= Minion_CLI::color("| Migration table create!!! |\n", 'green'); $msg .= Minion_CLI::color("-----------------------------\n", 'green'); Minion_CLI::write($msg); } $migrations->migrate($params['db'], $params['step']); }
protected function downFile($path, $file_name) { header("Content-type:text/html;charset=utf-8"); // echo $path,$file_name; //中文兼容 $file_name = iconv("utf-8", "gb2312", $file_name); //获取网站根目录,这里可以换成你的下载目录 $file_sub_path = $path; $file_path = $file_sub_path . $file_name; //判断文件是否存在 if (!file_exists($file_path)) { echo '文件不存在'; return; } $fp = fopen($file_path, "r"); $file_size = filesize($file_path); //下载文件所需的header申明 Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length:" . $file_size); Header("Content-Disposition: attachment; filename=" . $file_name); $buffer = 1024; $file_count = 0; //返回数据到浏览器 while (!feof($fp) && $file_count < $file_size) { $file_con = fread($fp, $buffer); $file_count += $buffer; echo $file_con; } fclose($fp); }
public static function readRoutes($url, $params = array()) { if (isset(self::$routes)) { } else { $filename = $_SERVER["DOCUMENT_ROOT"] . "/Init/routing.prop"; $f = fopen($filename, "r"); $r = fread($f, filesize($filename)); $prop = explode("\n", $r); #print_r($prop); for ($i = 0; $i < count($prop); $i++) { if (substr($prop[$i], 0, 4) != " ") { continue; } $params = array(); $row = true; while ($row) { $row = self::readRoutingRow($prop[$i++]); if ($row) { $params[$row[0]] = $row[1]; } } $i--; if (self::checkMe($url, $params)) { break; } } } }
function form_save() { if (isset($_POST["save_component_import"])) { if (trim($_POST["import_text"] != "")) { /* textbox input */ $xml_data = $_POST["import_text"]; } elseif ($_FILES["import_file"]["tmp_name"] != "none" && $_FILES["import_file"]["tmp_name"] != "") { /* file upload */ $fp = fopen($_FILES["import_file"]["tmp_name"], "r"); $xml_data = fread($fp, filesize($_FILES["import_file"]["tmp_name"])); fclose($fp); } else { header("Location: templates_import.php"); exit; } if ($_POST["import_rra"] == "1") { $import_custom_rra_settings = false; } else { $import_custom_rra_settings = true; } /* obtain debug information if it's set */ $debug_data = import_xml_data($xml_data, $import_custom_rra_settings); if (sizeof($debug_data) > 0) { $_SESSION["import_debug_info"] = $debug_data; } header("Location: templates_import.php"); } }
public static function echoFileContent($filename) { $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); echo $contents; }
public function uploadFile($key, $file) { $handle = fopen($file, 'r'); $value = $this->ossClient->putObject(array('Bucket' => $this->bucket, 'Key' => $key, 'Content' => $handle, 'ContentLength' => filesize($file))); fclose($handle); return $value; }
function index() { if ($this->input->post('PHPSESSID')) { session_id($this->input->post('PHPSESSID')); } else { return FALSE; } if (is_uploaded_file($_FILES['Filedata']['tmp_name'])) { $config['allowed_types'] = $this->input->post('upload_ext'); $config['upload_path'] = DATA_PATH . '/temp'; $config['max_size'] = $this->input->post('upload_size'); $config['encrypt_name'] = TRUE; $this->load->library('upload', $config); if ($this->upload->do_upload('Filedata')) { $data = $this->upload->data(); $file = '/temp/' . $data['file_name']; $filedir = $this->config->item('base_url') . DATA_DIR . $file; $filepath = DATA_PATH . $file; if (strpos('.jpg.gif.png', strtolower($data['file_ext'])) !== FALSE) { $info = array('imageurl' => $filedir, 'filename' => $data['orig_name'], 'filesize' => filesize($filepath), 'imagealign' => 'L', 'thumburl' => $filedir); } else { $info = array('attachurl' => $filedir, 'filemime' => $data['file_type'], 'filename' => $data['orig_name'], 'filesize' => filesize($filepath)); } echo json_encode($info); } else { echo $this->upload->display_errors('', ''); } } else { return FALSE; } }
/** * Return an CT file for download */ function churchcore__filedownload() { global $files_dir; include_once CHURCHCORE . "/churchcore_db.php"; $mime_types = getMimeTypes(); $file = db_query("select * from {cc_file} f where f.id=:id and filename=:filename", array(":id" => $_GET["id"], ":filename" => $_GET["filename"]))->fetch(); $filename = "{$files_dir}/files/{$file->domain_type}/{$file->domain_id}/{$file->filename}"; $handle = fopen($filename, "rb"); if ($handle == false) { echo "Die Datei konnte nicht gefunden werden!"; } else { $contents = fread($handle, filesize($filename)); fclose($handle); if (isset($mime_types[substr(strrchr($filename, '.'), 1)])) { drupal_add_http_header('Content-Type', $mime_types[substr(strrchr($filename, '.'), 1)], false); } else { drupal_add_http_header('Content-Type', 'application/unknown', false); } if (isset($_GET["type"]) && $_GET["type"] == "download") { drupal_add_http_header('Content-Disposition', 'attachment;filename="' . $file->bezeichnung . '"', false); } else { drupal_add_http_header('Content-Disposition', 'inline;filename="' . $file->bezeichnung . '"', false); } drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', false); drupal_add_http_header('Cache-Control', 'private', true); $content = drupal_get_header(); echo $contents; } }
/** * @param $file_name * @return array * @throws ApplicationException */ public static function generate($file_name) { set_time_limit(0); $temp_file = TempFileProvider::generate("peaks", ".raw"); $command = sprintf("%s -v quiet -i %s -ac 1 -f u8 -ar 11025 -acodec pcm_u8 %s", self::$ffmpeg_cmd, escapeshellarg($file_name), escapeshellarg($temp_file)); shell_exec($command); if (!file_exists($temp_file)) { throw new ApplicationException("Waveform could not be generated!"); } $chunk_size = ceil(filesize($temp_file) / self::PEAKS_RESOLUTION); $peaks = withOpenedFile($temp_file, "r", function ($fh) use(&$chunk_size) { while ($data = fread($fh, $chunk_size)) { $peak = 0; $array = str_split($data); foreach ($array as $item) { $code = ord($item); if ($code > $peak) { $peak = $code; } if ($code == 255) { break; } } (yield $peak - 127); } }); TempFileProvider::delete($temp_file); return $peaks; }
function GetFoldersAndFiles($resourceType, $currentFolder) { // Map the virtual path to the local server path. $sServerDir = ServerMapFolder($resourceType, $currentFolder); // Initialize the output buffers for "Folders" and "Files". $sFolders = '<Folders>'; $sFiles = '<Files>'; $oCurrentFolder = opendir($sServerDir); while ($sFile = readdir($oCurrentFolder)) { if ($sFile != '.' && $sFile != '..') { if (is_dir($sServerDir . $sFile)) { $sFolders .= '<Folder name="' . ConvertToXmlAttribute($sFile) . '" />'; } else { $iFileSize = filesize($sServerDir . $sFile); if ($iFileSize > 0) { $iFileSize = round($iFileSize / 1024); if ($iFileSize < 1) { $iFileSize = 1; } } $sFiles .= '<File name="' . ConvertToXmlAttribute($sFile) . '" size="' . $iFileSize . '" />'; } } } echo $sFolders; // Close the "Folders" node. echo '</Folders>'; echo $sFiles; // Close the "Files" node. echo '</Files>'; }
public function testGetImage() { $client = static::makeClient(true); $file = __DIR__ . "/Fixtures/files/uploadtest.png"; $originalFilename = 'uploadtest.png'; $mimeType = "image/png"; $image = new UploadedFile($file, $originalFilename, $mimeType, filesize($file)); $client->request('POST', '/api/temp_images/upload', array(), array('userfile' => $image)); $response = json_decode($client->getResponse()->getContent()); $property = "@id"; $imageId = $response->image->{$property}; $uri = $imageId . "/getImage"; $client->request('GET', $uri); $this->assertEquals("image/png", $client->getResponse()->headers->get("Content-Type")); $imageSize = getimagesizefromstring($client->getResponse()->getContent()); $this->assertEquals(51, $imageSize[0]); $this->assertEquals(23, $imageSize[1]); $iriConverter = $this->getContainer()->get("api.iri_converter"); $image = $iriConverter->getItemFromIri($imageId); /** * @var $image TempImage */ $this->getContainer()->get("partkeepr_image_service")->delete($image); $client->request('GET', $uri); $this->assertEquals(404, $client->getResponse()->getStatusCode()); }
/** * upload a file to hdfs * * example : var_dump(json_decode(hdfs_put('/tmp/xh', '/tmp/php_test', true))); * * @param string $localfile 本地文件 * @param string $remotefile hdfs中的文件位置 * @param boolean $overwrite 是否覆盖文件 * @return string 返回的错误信息 */ function hdfs_put($localfile, $remotefile, $overwrite = false) { $url = SERVICE_URL . "/webhdfs/v1{$remotefile}?op=CREATE&user.name=hadoop"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_PUT, 1); curl_setopt($ch, CURLOPT_HEADER, true); $resp = curl_exec($ch); curl_close($ch); $pos = strpos($resp, 'Location:'); $resp = strstr(substr($resp, $pos + 9), "\n", true); $datanode = trim($resp); if ($overwrite) { $datanode = str_replace('overwrite=false', 'overwrite=true', $datanode); } $f = fopen($localfile, 'rb'); $file_size = filesize($localfile); $ch = curl_init($datanode); curl_setopt($ch, CURLOPT_PUT, 1); //curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_INFILESIZE, $file_size); curl_setopt($ch, CURLOPT_INFILE, $f); $resp = curl_exec($ch); curl_close($ch); fclose($f); return $resp; }