/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, ['file' => 'required']); $file = $request->file('file'); $original_file_name = $file->getClientOriginalName(); $file_name = pathinfo($original_file_name, PATHINFO_FILENAME); $extension = \File::extension($original_file_name); $actual_name = $file_name . '.' . $extension; $apk = new \ApkParser\Parser($file); $manifest = $apk->getManifest(); $labelResourceId = $apk->getManifest()->getApplication()->getLabel(); $appLabel = $apk->getResources($labelResourceId); $package_name = $manifest->getPackageName(); if (Apk::packageExist($package_name)) { Session::flash('flash_class', 'alert-danger'); Session::flash('flash_message', 'Apk namespace already exist.'); return redirect()->route("apk.create"); } Apk::create(array('app_name' => $appLabel[0], 'pkgname' => $package_name, 'version' => $manifest->getVersionCode(), 'version_name' => $manifest->getVersionName(), 'md5' => md5_file($file), 'filename' => $actual_name, 'filesize' => str_format_filesize(\File::size($file)), 'token' => md5(uniqid(mt_rand(), true)))); $folderpath = base_path() . '/storage/apk/' . $manifest->getPackageName(); if (!\File::exists($folderpath)) { \File::makeDirectory($folderpath); } $file_path = $request->file('file')->move($folderpath, $actual_name); return redirect()->route("apk.index"); }
/** * Start a big file download on Laravel Framework 4.0 / 4.1 * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel * @param string $path Path to the big file * @param string $name Name of the file (used in Content-disposition header) * @param array $headers Some extra headers */ public function sendFile($path, $name = null, array $headers = array()) { if (is_null($name)) { $name = basename($path); } $file = new \Symfony\Component\HttpFoundation\File\File($path); $mime = $file->getMimeType(); // Prepare the headers $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers); $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers); // If there's a session we should save it now if (\Config::get('session.driver') !== '') { \Session::save(); } session_write_close(); if (ob_get_length()) { ob_end_clean(); } $response->sendHeaders(); // Read the file if ($file = fopen($path, 'rb')) { while (!feof($file) and connection_status() == 0) { print fread($file, 1024 * 8); flush(); } fclose($file); } // Finish off, like Laravel would \Event::fire('laravel.done', array($response)); $response->send(); }
function main() { if (empty($this->args)) { return $this->err('Usage: ./cake fixturize <table>'); } if ($this->args[0] == '?') { return $this->out('Usage: ./cake fixturize <table> [-force] [-reindex]'); } $options = array('force' => false, 'reindex' => false); foreach ($this->params as $key => $val) { foreach ($options as $name => $option) { if (isset($this->params[$name]) || isset($this->params['-' . $name]) || isset($this->params[$name[0]])) { $options[$name] = true; } } } foreach ($this->args as $table) { $name = Inflector::classify($table); $Model = new AppModel(array('name' => $name, 'table' => $table)); $file = sprintf('%stests/fixtures/%s_fixture.php', APP, Inflector::underscore($name)); $File = new File($file); if ($File->exists() && !$options['force']) { $this->err(sprintf('File %s already exists, use --force option.', $file)); continue; } $records = $Model->find('all'); $out = array(); $out[] = '<?php'; $out[] = ''; $out[] = sprintf('class %sFixture extends CakeTestFixture {', $name); $out[] = sprintf(' var $name = \'%s\';', $name); $out[] = ' var $records = array('; $File->write(join("\n", $out)); foreach ($records as $record) { $out = array(); $out[] = ' array('; if ($options['reindex']) { foreach (array('old_id', 'vendor_id') as $field) { if ($Model->hasField($field)) { $record[$name][$field] = $record[$name]['id']; break; } } $record[$name]['id'] = String::uuid(); } foreach ($record[$name] as $field => $val) { $out[] = sprintf(' \'%s\' => \'%s\',', addcslashes($field, "'"), addcslashes($val, "'")); } $out[] = ' ),'; $File->write(join("\n", $out)); } $out = array(); $out[] = ' );'; $out[] = '}'; $out[] = ''; $out[] = '?>'; $File->write(join("\n", $out)); $this->out(sprintf('-> Create %sFixture with %d records (%d bytes) in "%s"', $name, count($records), $File->size(), $file)); } }
/** * beforeSave callback * * @param array $options * @return boolean true on success */ public function beforeSave($options = array()) { if (!empty($this->data[$this->alias]['file']['tmp_name'])) { $File = new File($this->data[$this->alias]['file']['tmp_name']); $this->data[$this->alias]['filesize'] = $File->size(); $this->data[$this->alias]['mime_type'] = $File->mime(); } if (!empty($this->data[$this->alias]['file']['name'])) { $this->data[$this->alias]['extension'] = $this->fileExtension($this->data[$this->alias]['file']['name']); $this->data[$this->alias]['filename'] = $this->data[$this->alias]['file']['name']; } if (empty($this->data[$this->alias]['adapter'])) { $this->data[$this->alias]['adapter'] = 'S3Storage'; } // Start Auto Creator & Modifier Id Saving $exists = $this->exists(); $user = class_exists('CakeSession') ? CakeSession::read('Auth.User') : null; if (!$exists && $this->hasField('creator_id') && empty($this->data[$this->alias]['creator_id'])) { $this->data[$this->alias]['creator_id'] = $user['id']; } if ($this->hasField('modifier_id') && empty($this->data[$this->alias]['modifier_id'])) { $this->data[$this->alias]['modifier_id'] = $user['id']; } // End Auto Creator & Modifier Id Saving $Event = new CakeEvent('FileStorage.beforeSave', $this, array('record' => $this->data, 'storage' => $this->getStorageAdapter($this->data[$this->alias]['adapter']))); $this->getEventManager()->dispatch($Event); if ($Event->isStopped()) { return false; } return true; }
public function postUpload() { $agente = Agente::find(1); if (Input::hasFile('file')) { $file = Input::file('file'); $name = $file->getClientOriginalName(); $extension = $file->getClientOriginalExtension(); $size = File::size($file); //dd($extension); $data = array('nombre' => $name, 'extension' => $extension, 'size' => $size); $rules = array('extension' => 'required|mimes:jpeg'); $messages = array('required' => 'El campo :attribute es obligatorio.', 'min' => 'El campo :attribute no puede tener menos de :min carácteres.', 'email' => 'El campo :attribute debe ser un email válido.', 'max' => 'El campo :attribute no puede tener más de :max carácteres.', 'unique' => 'La factura ingresada ya está agregada en la base de datos.', 'confirmed' => 'Los passwords no coinciden.', 'mimes' => 'El campo :attribute debe ser un archivo de tipo :values.'); $validation = Validator::make($rules, $messages); if ($validation->fails()) { return Redirect::route('logo-post')->withInput()->withErrors($validation); } else { if ($extension != 'jpg') { return Redirect::route('logo-post')->with('global', 'Es necesario que la imagen sea de extension .jpg.'); } else { $path = public_path() . '/assets/img/'; $newName = 'logo'; $subir = $file->move($path, $newName . '.' . $extension); return Redirect::route('agente.index')->with('create', 'El logo ha sido actualizado correctamente!'); } } } else { return Redirect::route('logo-post')->with('global', 'Es necesario que selecciones una imagen.'); } }
function replace($path) { $F = new File($path); $md5 = $F->md5(); $this->path = appPATH . 'qg/file/' . $md5; $F->copy($this->path); $this->setVs(array('name' => $F->basename(), 'mime' => $F->mime(), 'text' => $F->getText(), 'md5' => $F->md5(), 'size' => $F->size())); }
protected final function setFiles($key, $req) { $file = new File($req["name"]); $file->tmp(isset($req["tmp_name"]) ? $req["tmp_name"] : ""); $file->size(isset($req["size"]) ? $req["size"] : ""); $file->error($req["error"]); $this->files[$key] = $file; }
public function admin_index() { $logDir = LOGS; $Folder = new Folder($logDir, false); $logfiles = $Folder->find('.*.log(\\.[0-9])?', true); $files = array(); foreach ($logfiles as $logfile) { $F = new File($logDir . $logfile); $file = array('name' => $logfile, 'dir' => $logDir, 'size' => $F->size(), 'last_modified' => $F->lastChange(), 'last_access' => $F->lastAccess()); array_push($files, $file); } $this->set(compact('files')); }
/** * Save the file to the fileable type and id */ public function save() { $file = $this->makeFileRecord(); // move the file and add the size to the file model $this->file->move($file->getSystemPath(), $file->filename); if (\File::exists($file->getSystemPath() . $file->filename)) { $file->filesize = \File::size($file->getSystemPath() . $file->filename); } if ($this->thumbnail->isPhoto($file->getSystemPath() . $file->filename)) { $this->thumbnail->make($file); } $file->save(); }
/** * Finished Benchmarks and log texts will be added to the logfile. * * Each benchmark is one row in the file. After calling this function successfully, the finished * benchmarks array and the log data array are empty. It is not recommended to use this function * directly. If an error occurs while writing the file a NonFatalException will be thrown. * * @throws NonFatalException */ public function saveFile() { $benchmarks = array(); //add new line if file is not empty $text = $this->file->size() != 0 ? "\r\n" : ''; $benchmarks = $this->getBenchmarkStringArray(); $text .= implode("\r\n", array_merge($this->logs, $benchmarks)); if ($this->file->write($text, true) === false) { throw NonFatalException('Could not write to log file.'); } else { $this->clear(); } }
/** * Finished Benchmarks and log texts will be added to the logfile. * * Each benchmark is one row in the file. * After calling this function successfully, the finished benchmarks array and the log data array are empty. * It is not recommended to use this function directly. * If an error occurs while writing the file a warning will be thrown. */ public function saveFile() { $benchmarks = array(); //add new line if file is not empty $text = iif($this->file->size() != 0 && $this->file->size() != false, "\r\n"); $benchmarks = $this->getBenchmarkStringArray(); $text .= implode("\r\n", array_merge($this->logs, $benchmarks)); if ($this->file->write($text, true) === false) { Core::throwError('Could not write log file in method Debug::saveFile().'); } else { $this->clear(); } }
function readFolder($folderName = null) { $folder = new Folder($folderName); $images = $folder->read(true, array('.', '..', 'Thumbs.db'), false); //pr($folder->tree($folderName)); $images = $images[1]; // We are only interested in files // Get more infos about the images $retVal = array(); foreach ($images as $the_image) { $the_image = new File($the_image); $retVal[] = array_merge($the_image->info(), array('size' => $the_image->size(), 'last_changed' => $the_image->lastChange())); } return $retVal; }
/** * Reads a cache file and unserializes the data. * * @param string Cache name * @return Cached data or null on failure */ public function load($name) { $file = new File($this->path.$name.'.ser'); if ($file->exists() == true && $file->size() > 0) { $data = $file->read(); if ($data !== false) { $data = unserialize($data); if (isset($data['expires']) && ($data['expires'] == 0 || $data['expires'] > time())) { return $data['data']; } else { $this->delete(); } } } return null; }
public function indx() { //Getting all post data if (Request::ajax()) { $data = Input::all(); $fileTblObj = new fileHandler(); $key = "uploaded_file"; if (Input::file($key)->isValid()) { $destinationPath = 'app/uploads/111/222/3'; // upload path $extension = Input::file($key)->getClientOriginalExtension(); // getting image extension $name = Input::file($key)->getClientOriginalName(); $curFilesize = Input::file($key)->getClientSize(); $mime = Input::file($key)->getMimeType(); // dd($mime); //$fileName = $name; // renameing image //$exstFileSize = Input::file($destinationPath, $fileName); if (!File::exists($destinationPath . "/boq-" . $name)) { //creating details for saving inthe file_handler Table $fileTblObj->user_id = $userid; $fileTblObj->eventName = $event; $fileTblObj->fileName = "boq-" . $name; $fileTblObj->formPage = 3; $fileTblObj->filePath = $destinationPath . "/"; $fileTblObj->mime = $mime; $ans->answer_text = 'Yes'; Input::file($key)->move($destinationPath, "boq-" . $name); // uploading file to given path //Input::file($key)->move($boqPath, $boqname); // uploading file to given path //Save filedetails $fileTblObj->save(); Session::flash('success', 'Upload successfully'); } else { if (File::size($destinationPath . "/" . $name) != $curFilesize) { $fileDtls = $fileTblObj->where('uid', $userid)->where('fileName', $name)->where('formPage', 3)->first(); Input::file($key)->move($destinationPath, $name); $ans->answer_text = 'Yes'; $ans->save(); $fileTblObj->where('id', $fileDtls->id)->update(array('updated_at' => date("Y-m-d h:m:s", time()))); } } //return Redirect::to('upload'); } die; } }
public function finish() { if ($this->isCache) { return null; } if ($this->handle) { ob_end_flush(); fclose($this->handle); } if (App::hasError()) { return null; } if (File::size($this->cacheTmp) > 0) { copy($this->cacheTmp, $this->cacheName); file_put_contents($this->cacheName . '.1', $this->lastModified); } }
public static function download($path, $name = null, $headers = array()) { if (!file_exists($path)) { return Response::code(404); } if (is_null($name)) { $name = basename($path); } $ext = File::extension($name); if ($ext == "") { $ext = File::extension($path); } $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => File::mime(File::extension($path)), 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => File::size($path), 'Content-Disposition' => 'attachment; filename="' . str_replace('"', '\\"', $name) . '"'), $headers); foreach ($headers as $k => $v) { header($k . ": " . $v); } readfile($path); }
public function editAction() { $this->view->setVar('Lang', $this->inc->getLang('web/web_news')); $id = $this->request->getPost('id'); $Edit = WebNews::findFirst(array('id=' . $id)); $this->view->setVar('Edit', $Edit); // Upload $upload = ''; if (!empty($Edit->upload)) { $File = new File(); $arr = array_filter(explode(',', $Edit->upload)); foreach ($arr as $val) { $upload[] = array('path' => $this->path, 'name' => $val, 'size' => $File->formatBytes($File->size($this->root . $this->path . $val))); } } $this->view->setVar('Upload', $upload); $this->view->pick("web/news/edit"); }
/** * Put a local file in an S3 bucket * * @return void * @author Rob Mcvey **/ public function put($localPath, $remoteDir = null) { // Base filename $file = basename($localPath); // File remote/local files $this->checkLocalPath($localPath); $this->checkFile($file); $this->checkRemoteDir($remoteDir); // Signature $stringToSign = $this->stringToSign('put'); // Build the HTTP request $request = array('method' => 'PUT', 'uri' => array('scheme' => 'https', 'host' => $this->bucket . '.' . $this->endpoint, 'path' => $this->file), 'header' => array('Accept' => '*/*', 'User-Agent' => 'CakePHP', 'Date' => $this->date, 'Authorization' => 'AWS ' . $this->accessKey . ':' . $this->signature($stringToSign), 'Content-MD5' => $this->contentMd5, 'Content-Type' => $this->contentType, 'Content-Length' => $this->File->size()), 'body' => $this->File->read()); // Any addional Amazon headers to add? $request = $this->addAmazonHeadersToRequest($request); // Make the HTTP request $response = $this->handleRequest($request); // Handle response errors if any $this->handleResponse($response); }
function file_size($size) { $dim = ''; if (!is_numeric($size)) { $size = \File::size($size); } if ($size) { $size = $size / 1024; $dim = ' KB'; } if ($size > 1000) { $size = $size / 1024; $dim = ' MB'; } if ($size > 1000) { $size = $size / 1024; $dim = ' GB'; } return number_format($size, 2) . $dim; }
/** * beforeRender callback function * * @param Controller $controller * @return array contents for panel */ public function beforeRender(Controller $controller) { $data = array(); $dir = new Folder(LOGS); $files = $dir->find(); foreach ($files as $log) { $file = new File(LOGS . $log); $name = $file->name(); $data[$name] = array(); if (!$file->readable()) { $data[$name]['content'] = __('This log file is unreadable.'); continue; } $data[$name]['lastChange'] = date('Y-m-d H:i:s', $file->lastChange()); if ($file->size() > $this->readBytes) { $file->offset(-$this->readBytes, SEEK_END); } $data[$name]['content'] = $file->read($this->readBytes); } return $data; }
/** * @return array */ public static function all() { $log = []; $log_levels = self::getLogLevels(); $pattern = '/\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\].*/'; if (!self::$file) { $log_file = self::getFiles(); if (!count($log_file)) { return []; } self::$file = $log_file[0]; } if (\File::size(self::$file) > self::MAX_FILE_SIZE) { return null; } $file = \File::get(self::$file); preg_match_all($pattern, $file, $headings); if (!is_array($headings)) { return $log; } $log_data = preg_split($pattern, $file); if ($log_data[0] < 1) { array_shift($log_data); } foreach ($headings as $h) { for ($i = 0, $j = count($h); $i < $j; $i++) { foreach ($log_levels as $level_key => $level_value) { if (strpos(strtolower($h[$i]), '.' . $level_value)) { preg_match('/^\\[(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2})\\].*?\\.' . $level_key . ': (.*?)( in .*?:[0-9]+)?$/', $h[$i], $current); if (!isset($current[2])) { continue; } $log[] = ['level' => $level_value, 'level_class' => self::$levels_classes[$level_value], 'level_img' => self::$levels_imgs[$level_value], 'date' => $current[1], 'text' => $current[2], 'in_file' => isset($current[3]) ? $current[3] : null, 'stack' => preg_replace("/^\n*/", '', $log_data[$i])]; } } } } return array_reverse($log); }
/** * @param $userId * @param $fileUniName * @param $oriFileName * @param $tmpFileUrl * @param $chunk * @param $chunks * @param string $uploadTo * @return AmaotoFile|\Illuminate\Database\Eloquent\Model|mixed|null|static * @throws NeedMoreDataException */ public static function uploadFile($userId, $fileUniName, $oriFileName, $tmpFileUrl, $chunk, $chunks, $uploadTo = 'upload') { $fileMergePath = self::getUploadToPath($uploadTo) . '/' . $fileUniName . '.merge'; if ($chunk === 0) { File::put($fileMergePath, File::get($tmpFileUrl)); } else { File::append($fileMergePath, File::get($tmpFileUrl)); } if (!$chunks || $chunk == $chunks - 1) { //文件已上传完整 //计算哈希值 $fileMd5 = md5_file($fileMergePath); $fileFinalUrl = self::getUploadToPath($uploadTo) . '/' . $fileMd5 . '.' . File::extension($oriFileName); //判断文件是否存在 if (file_exists($fileFinalUrl)) { File::delete($fileMergePath); } else { File::move($fileMergePath, $fileFinalUrl); } if (AmaotoFile::whereMd5($fileMd5)->count() == 0) { $thatFile = new AmaotoFile(); $thatFile->md5 = $fileMd5; $thatFile->name = $oriFileName; $thatFile->size = File::size($fileFinalUrl); $thatFile->url = str_replace(public_path(), '', $fileFinalUrl); $thatFile->user_id = $userId; $thatFile->updateTypeByGetId3(); $thatFile->save(); return $thatFile; } else { $thatFile = AmaotoFile::whereMd5($fileMd5)->first(); return $thatFile; } } throw new NeedMoreDataException('文件未接收完整,请求继续发送数据'); }
/** * testAppend method * * @return void */ public function testAppend() { if (!($tmpFile = $this->_getTmpFile())) { return false; } if (file_exists($tmpFile)) { unlink($tmpFile); } $TmpFile = new File($tmpFile); $this->assertFalse(file_exists($tmpFile)); $fragments = array('CakePHP\'s', ' test suite', ' was here ...'); $data = null; $size = 0; foreach ($fragments as $fragment) { $r = $TmpFile->append($fragment); $this->assertTrue($r); $this->assertTrue(file_exists($tmpFile)); $data = $data . $fragment; $this->assertEquals($data, file_get_contents($tmpFile)); $newSize = $TmpFile->size(); $this->assertTrue($newSize > $size); $size = $newSize; $TmpFile->close(); } $TmpFile->append(''); $this->assertEquals($data, file_get_contents($tmpFile)); $TmpFile->close(); }
/** * add_attachment method * * @return void */ public function uploadAttachment($fileP, $realFileName, $malware, $eventId = null, $category = null, $extraPath = '', $fullFileName = '', $dist, $fromGFI = false) { // Check if there were problems with the file upload // only keep the last part of the filename, this should prevent directory attacks $filename = basename($fileP); $tmpfile = new File($fileP); // save the file-info in the database $this->create(); $this->data['Attribute']['event_id'] = $eventId; $this->data['Attribute']['distribution'] = $dist; if ($malware) { $md5 = !$tmpfile->size() ? md5_file($fileP) : $tmpfile->md5(); $this->data['Attribute']['category'] = $category ? $category : "Payload delivery"; $this->data['Attribute']['type'] = "malware-sample"; $this->data['Attribute']['value'] = $fullFileName ? $fullFileName . '|' . $md5 : $filename . '|' . $md5; // TODO gives problems with bigger files $this->data['Attribute']['to_ids'] = 1; // LATER let user choose to send this to IDS if ($fromGFI) { $this->data['Attribute']['comment'] = 'GFI import'; } } else { $this->data['Attribute']['category'] = $category ? $category : "Artifacts dropped"; $this->data['Attribute']['type'] = "attachment"; $this->data['Attribute']['value'] = $fullFileName ? $fullFileName : $realFileName; $this->data['Attribute']['to_ids'] = 0; if ($fromGFI) { $this->data['Attribute']['comment'] = 'GFI import'; } } //??? if ($this->save($this->data)) { // attribute saved correctly in the db } else { // do some? } // no errors in file upload, entry already in db, now move the file where needed and zip it if required. // no sanitization is required on the filename, path or type as we save // create directory structure // ??? $rootDir = APP . "files" . DS . $eventId; $dir = new Folder($rootDir, true); // move the file to the correct location $destpath = $rootDir . DS . $this->getId(); // id of the new attribute in the database $file = new File($destpath); $zipfile = new File($destpath . '.zip'); $fileInZip = new File($rootDir . DS . $extraPath . $filename); // FIXME do sanitization of the filename // zip and password protect the malware files if ($malware) { // TODO check if CakePHP has no easy/safe wrapper to execute commands $execRetval = ''; $execOutput = array(); exec("zip -j -P infected " . $zipfile->path . ' \'' . addslashes($fileInZip->path) . '\'', $execOutput, $execRetval); if ($execRetval != 0) { // not EXIT_SUCCESS // do some? } $fileInZip->delete(); // delete the original not-zipped-file rename($zipfile->path, $file->path); // rename the .zip to .nothing } else { $fileAttach = new File($fileP); rename($fileAttach->path, $file->path); } }
/** * Retrieve (cached) metadata of a file * * @param Model $Model * @param string $file An absolute path to a file * @param integer $level level of amount of info to add, `0` disable, `1` for basic, `2` for detailed info * @return mixed Array with results or false if file is not readable */ function metadata(&$Model, $file, $level = 1) { if ($level < 1) { return array(); } extract($this->settings[$Model->alias]); $File = new File($file); if (!$File->readable()) { return false; } $checksum = $File->md5(true); if (isset($this->__cached[$Model->alias][$checksum])) { $data = $this->__cached[$Model->alias][$checksum]; } if ($level > 0 && !isset($data[1])) { $data[1] = array('size' => $File->size(), 'mime_type' => Mime_Type::guessType($File->pwd()), 'checksum' => $checksum); } if ($level > 1 && !isset($data[2])) { $data[2] = array(); try { $Info = Media_Info::factory(array('source' => $File->pwd())); foreach ($Info->all() as $key => $value) { $data[2][Inflector::underscore($key)] = $value; } } catch (Exception $E) { } } for ($i = $level, $result = array(); $i > 0; $i--) { $result = array_merge($result, $data[$i]); } $this->__cached[$Model->alias][$checksum] = $data; return $result; }
/** * Apply a file range to a file and set the end offset. * * If an invalid range is requested a 416 Status code will be used * in the response. * * @param File $file The file to set a range on. * @param string $httpRange The range to use. * @return void */ protected function _fileRange($file, $httpRange) { list(, $range) = explode('=', $httpRange); list($start, $end) = explode('-', $range); $fileSize = $file->size(); $lastByte = $fileSize - 1; if ($start === '') { $start = $fileSize - $end; $end = $lastByte; } if ($end === '') { $end = $lastByte; } if ($start > $end || $end > $lastByte || $start > $lastByte) { $this->statusCode(416); $this->header(array('Content-Range' => 'bytes 0-' . $lastByte . '/' . $fileSize)); return; } $this->header(array('Content-Length' => $end - $start + 1, 'Content-Range' => 'bytes ' . $start . '-' . $end . '/' . $fileSize)); $this->statusCode(206); $this->_fileRange = array($start, $end); }
public function grabFiles() { $validItems = $this->getFileRules(); App::uses('Folder', 'Utility'); App::uses('File', 'Utility'); $result = array(); foreach ($validItems as $k => &$item) { $dir = new Folder($item['path']); $files = $dir->find($item['regex'], true); foreach ($files as $file) { $f = new File($item['path'] . DS . $file); $validItems[$k]['files'][] = array('filename' => $file, 'filesize' => $f->size(), 'read' => $f->readable(), 'write' => $f->writable(), 'execute' => $f->executable()); } } return $validItems; }
/** * Setup for display or download the given file * * @param string $path Path to file * @param array $options Options * ### Options keys * - name: Alternate download name * - download: If `true` sets download header and forces file to be downloaded rather than displayed in browser * @return void * @throws NotFoundException */ public function file($path, $options = array()) { $options += array('name' => null, 'download' => null); if (!is_file($path)) { $path = APP . $path; } $file = new File($path); if (!$file->exists() || !$file->readable()) { if (Configure::read('debug')) { throw new NotFoundException(__d('cake_dev', 'The requested file %s was not found or not readable', $path)); } throw new NotFoundException(__d('cake', 'The requested file was not found')); } $extension = strtolower($file->ext()); $download = $options['download']; if ((!$extension || $this->type($extension) === false) && is_null($download)) { $download = true; } $fileSize = $file->size(); if ($download) { $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) { $contentType = 'application/octetstream'; } elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/force-download'; } if (!empty($contentType)) { $this->type($contentType); } if (is_null($options['name'])) { $name = $file->name; } else { $name = $options['name']; } $this->download($name); $this->header('Accept-Ranges', 'bytes'); $httpRange = env('HTTP_RANGE'); if (isset($httpRange)) { list(, $range) = explode('=', $httpRange); $size = $fileSize - 1; $length = $fileSize - $range; $this->header(array('Content-Length' => $length, 'Content-Range' => 'bytes ' . $range . $size . '/' . $fileSize)); $this->statusCode(206); $file->open('rb', true); $file->offset($range); } else { $this->header('Content-Length', $fileSize); } } else { $this->header('Content-Length', $fileSize); } $this->_clearBuffer(); $this->_file = $file; }
/** * Get file size * @param null $path * @return integer */ public function getFileSize($path = null) { $file = new File($path); return $file->size(); }
/** * Apply a file range to a file and set the end offset. * * If an invalid range is requested a 416 Status code will be used * in the response. * * @param File $file The file to set a range on. * @param string $httpRange The range to use. * @return void */ protected function _fileRange($file, $httpRange) { $fileSize = $file->size(); $lastByte = $fileSize - 1; $start = 0; $end = $lastByte; preg_match('/^bytes\\s*=\\s*(\\d+)?\\s*-\\s*(\\d+)?$/', $httpRange, $matches); if ($matches) { $start = $matches[1]; $end = isset($matches[2]) ? $matches[2] : ''; } if ($start === '') { $start = $fileSize - $end; $end = $lastByte; } if ($end === '') { $end = $lastByte; } if ($start > $end || $end > $lastByte || $start > $lastByte) { $this->statusCode(416); $this->header(array('Content-Range' => 'bytes 0-' . $lastByte . '/' . $fileSize)); return; } $this->header(array('Content-Length' => $end - $start + 1, 'Content-Range' => 'bytes ' . $start . '-' . $end . '/' . $fileSize)); $this->statusCode(206); $this->_fileRange = array($start, $end); }