extension() public static method

Extract the file extension from a file path.
public static extension ( string $path ) : string
$path string
return string
Example #1
2
 /**
  * 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");
 }
Example #2
1
 public function post_new()
 {
     $input = Input::all();
     //grab our input
     $rules = array('name' => 'required|alpha', 'lastName' => 'required|alpha', 'permit' => 'required|min:2', 'lot' => 'required|integer', 'msc' => 'integer', 'ticket' => 'required|min:2|numeric|unique:tickets,ticketID', 'fineAmt' => 'required|numeric', 'licensePlate' => 'required|alpha_num', 'licensePlateState' => 'required|max:2', 'dateIssued' => 'required', 'violations' => 'required', 'areaOfViolation' => 'required|alpha_num', 'appealLetter' => 'required|max:700');
     //validation rules
     $validation = Validator::make($input, $rules);
     //let's run the validator
     if ($validation->fails()) {
         return Redirect::to('appeal/new')->with_errors($validation);
     }
     //hashing the name of the file uploaded for security sake
     //then we'll be dropping it into the public/uploads file
     //get the file extension
     $extension = File::extension($input['appealLetter']['name']);
     //encrypt the file name
     $file = Crypter::encrypt($input['appealLetter']['name'] . time());
     //for when the crypter likes to put slashes in our scrambled filname
     $file = preg_replace('#/+#', '', $file);
     //concatenate extension and filename
     $filename = $file . "." . $extension;
     Input::upload('appealLetter', path('public') . 'uploads/', $filename);
     //format the fine amount in case someone screws it up
     $fineamt = number_format(Input::get('fineAmt'), 2, '.', '');
     //inserts the form data into the database assuming we pass validation
     Appeal::create(array('name' => Input::get('name'), 'lastName' => Input::get('lastName'), 'permitNumber' => Input::get('permit'), 'assignedLot' => Input::get('lot'), 'MSC' => Input::get('msc'), 'ticketID' => Input::get('ticket'), 'fineAmt' => $fineamt, 'licensePlate' => Str::upper(Input::get('licensePlate')), 'licensePlateState' => Input::get('licensePlateState'), 'dateIssued' => date('Y-m-d', strtotime(Input::get('dateIssued'))), 'violations' => Input::get('violations'), 'areaOfViolation' => Input::get('areaOfViolation'), 'letterlocation' => URL::to('uploads/' . $filename), 'CWID' => Session::get('cwid')));
     return Redirect::to('appeal/')->with('alertMessage', 'Appeal submitted successfully.');
 }
Example #3
0
 public function action_create()
 {
     $input = Input::all();
     if (isset($input['description'])) {
         $input['description'] = filter_var($input['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
     }
     $rules = array('image' => 'required|image|max:200', 'description' => 'required', 'name' => 'required');
     $messages = array('image_required' => 'Please select an image for upload!', 'image_max' => 'Make sure image is no larger than 500kb', 'image_image' => 'Please select an image file');
     $validation = Validator::make($input, $rules, $messages);
     if ($validation->fails()) {
         return Redirect::to('admin/gallery/new')->with_errors($validation);
     }
     $extension = File::extension($input['image']['name']);
     $directory = path('public') . 'uploads/' . sha1(Auth::user()->id);
     $filename = sha1(Auth::user()->id . time()) . ".{$extension}";
     $upload_success = Input::upload('image', $directory, $filename);
     if ($upload_success) {
         $photo = new Image(array('name' => Input::get('name'), 'location' => '/uploads/' . sha1(Auth::user()->id) . '/' . $filename, 'description' => $input['description'], 'type' => $extension));
         Auth::user()->images()->insert($photo);
         Session::flash('status_create', 'Successfully uploaded your new Instapic');
         Session::flash('id', $photo->id);
     } else {
         Log::write('admin.gallery.create', 'Image was not uploaded, $photo->create() returned false.');
         Session::flash('error_create', 'An error occurred while uploading your new Instapic - please try again.');
     }
     return Redirect::to('admin/gallery/new');
 }
 /**
  * Attempts to upload a file, adds it to the database and removes other database entries for that file type if they are asked to be removed
  * @param  string  $field             The name of the $_FILES field you want to upload
  * @param  boolean $upload_type       The type of upload ('news', 'gallery', 'section') etc
  * @param  boolean $type_id           The ID of the item (above) that the upload is linked to
  * @param  boolean $remove_existing   Setting this to true will remove all existing uploads of the passed in type (useful for replacing news article images when a new one is uploaded for example)
  * @return object                     Returns the upload object so we can work with the uploaded file and details
  */
 public static function upload($field = 'image', $upload_type = false, $type_id = false, $remove_existing = false)
 {
     if (!$field || !$upload_type || !$type_id) {
         return false;
     }
     $input = Input::file($field);
     if ($input && $input['error'] == UPLOAD_ERR_OK) {
         if ($remove_existing) {
             static::remove($upload_type, $type_id);
         }
         $ext = File::extension($input['name']);
         $filename = Str::slug(Input::get('title'), '-');
         Input::upload('image', './uploads/' . $filename . '.' . $ext);
         $upload = new Upload();
         $upload->link_type = $upload_type;
         $upload->link_id = $type_id;
         $upload->filename = $filename . '.' . $ext;
         if (Koki::is_image('./uploads/' . $filename . '.' . $ext)) {
             $upload->small_filename = $filename . '_small' . '.' . $ext;
             $upload->thumb_filename = $filename . '_thumb' . '.' . $ext;
             $upload->image = 1;
         }
         $upload->extension = $ext;
         $upload->user_id = Auth::user()->id;
         $upload->save();
         return $upload;
     }
 }
Example #5
0
 public function action_create()
 {
     /*$slug = $this->slugger(Input::get('title'));
     
     		$db = Post::create(array(
     				'post_title' => Input::get('title'),
     				'post_content' => Input::get('content'),
     				'excerpt' => Input::get('excerpt'),
     				'slug' => $slug,
     				'user_id' => Auth::user()->id,
     			));
     		
     		if(!$db){
     			Log::write('posts.create', 'Post was not created, post->create() returned false.');
     			 return Redirect::to('posts/new')
     		                 ->with('error_create', 'Unable to create post!');
     		} */
     $db = Post::find(2);
     $input = Input::all();
     $rules = array('image' => 'required|image|max:200');
     $messages = array('image_required' => 'Please select an image for upload!', 'image_max' => 'Make sure image is no larger than 500kb', 'image_image' => 'Please select an image file');
     $validation = Validator::make($input, $rules, $messages);
     if ($validation->fails()) {
         return Redirect::to('posts/new')->with_errors($validation);
     }
     $extension = File::extension($input['image']['name']);
     $directory = path('public') . 'uploads/' . sha1(Auth::user()->id);
     $filename = sha1(Auth::user()->id . time()) . ".{$extension}";
     $upload_success = Input::upload('image', $directory, $filename);
     if ($upload_success) {
         $photo = new Image(array('image_name' => $filename, 'image_location' => '/uploads/' . sha1(Auth::user()->id) . '/' . $filename, 'image_size' => $input['image']['size'], 'image_type' => $extension));
         $db->images()->insert($photo);
     }
     return Redirect::to('posts/new')->with('status_create', 'New Post Created')->with('id', $db->id);
 }
Example #6
0
 public function scan($recursive = true, $dir = '', &$list = [])
 {
     $dir = $dir ?: $this->path;
     if ($handle = opendir($dir)) {
         $this->exclude = empty($this->exclude) ? ['extension' => [], 'file' => [], 'dir' => []] : $this->exclude;
         while (($file = readdir($handle)) !== false) {
             $extension = File::extension($file);
             if ($file == '.' || $file == '..' || in_array($extension, $this->exclude['extension'])) {
                 continue;
             }
             $path = $dir . DIRECTORY_SEPARATOR . $file;
             if (is_readable($path)) {
                 if (is_dir($path) && !in_array($file, $this->exclude['dir'])) {
                     $list[] = ['name' => $file, 'type' => 'directory', 'path' => $path];
                     if ($recursive) {
                         $this->scan($recursive, $path, $list);
                     }
                 } elseif (is_file($path) && !in_array($file, $this->exclude['file'])) {
                     $list[] = ['name' => $file, 'extension' => $extension, 'type' => 'file', 'path' => $path];
                 }
             }
         }
         closedir($handle);
     }
     return array_map('array_filter', $list);
 }
Example #7
0
 public function post_upload()
 {
     $input = Input::get();
     $file = Input::file('fileInput');
     $separator = $input['claimdetailid'] != NULL ? $input['claimid'] . '/' . $input['claimdetailid'] : $input['claimid'];
     $extension = File::extension($file['name']);
     $directory = 'upload/claims/' . sha1(Auth::user()->userid) . '/' . str_replace("-", "", date('Y-m-d')) . '/' . $separator;
     $filename = Str::random(16, 'alpha') . time() . ".{$extension}";
     if (!is_dir(path('public') . $directory)) {
         mkdir(path('public') . $directory, 0777, true);
     }
     $maxSize = ini_get('upload_max_filesize') * 1024 * 1024 * 1024;
     if ($file['size'] != null && $file['size'] < $maxSize) {
         try {
             $upload_success = Input::upload('fileInput', path('public') . $directory, $filename);
             if ($upload_success) {
                 $input['recpath'] = $directory . '/' . $filename;
                 $receipt = new Claims_Receipt();
                 $receipt->fill($input);
                 $receipt->save();
                 Log::write('Claims Receipt', 'File Uploaded : ' . $filename . ' by ' . Auth::user()->username);
                 return $directory . '/' . $filename;
             }
         } catch (Exception $e) {
             Log::write('Claims Receipt', 'Upload error: ' . $e->getMessage());
         }
     } else {
         Log::write('Claims Receipt', 'Upload error: Exceed max size ' . ini_get('upload_max_filesize'));
     }
 }
Example #8
0
 /**
  * Upload the image while creating/updating records
  * @param File Object $file
  */
 public function setImageAttribute($file)
 {
     // Only if a file is selected
     if ($file) {
         File::exists(public_path() . '/uploads/') || File::makeDirectory(public_path() . '/uploads/');
         File::exists(public_path() . '/' . $this->images_path) || File::makeDirectory(public_path() . '/' . $this->images_path);
         File::exists(public_path() . '/' . $this->thumbs_path) || File::makeDirectory(public_path() . '/' . $this->thumbs_path);
         $file_name = $file->getClientOriginalName();
         $file_ext = File::extension($file_name);
         $only_fname = str_replace('.' . $file_ext, '', $file_name);
         $file_name = $only_fname . '_' . str_random(8) . '.' . $file_ext;
         $image = Image::make($file->getRealPath());
         if (isset($this->attributes['folder'])) {
             // $this->attributes['folder'] = Str::slug($this->attributes['folder'], '_');
             $this->images_path = $this->attributes['folder'] . '/';
             $this->thumbs_path = $this->images_path . '/thumbs/';
             File::exists(public_path() . '/' . $this->images_path) || File::makeDirectory(public_path() . '/' . $this->images_path);
             File::exists(public_path() . '/' . $this->thumbs_path) || File::makeDirectory(public_path() . '/' . $this->thumbs_path);
         }
         if (isset($this->attributes['image'])) {
             // Delete old image
             $old_image = $this->getImageAttribute();
             File::exists($old_image) && File::delete($old_image);
         }
         if (isset($this->attributes['thumbnail'])) {
             // Delete old thumbnail
             $old_thumb = $this->getThumbnailAttribute();
             File::exists($old_thumb) && File::delete($old_thumb);
         }
         $image->save(public_path($this->images_path . $file_name))->fit(150, 150)->save(public_path($this->thumbs_path . $file_name));
         $this->attributes['image'] = "{$this->attributes['folder']}/{$file_name}";
         $this->attributes['thumbnail'] = "{$this->attributes['folder']}/thumbs/{$file_name}";
         unset($this->attributes['folder']);
     }
 }
Example #9
0
 public static function upload($model, $modelName, $name, $attribute, $removePastImage = true, $sizes = array())
 {
     $uploadOptions = $attribute["uploadOptions"];
     $path = "public";
     $beforeImage = $model->{$name};
     if (isset($uploadOptions["sizes"])) {
         $sizes = $uploadOptions["sizes"];
     }
     if (isset($uploadOptions["path"])) {
         $path = $uploadOptions["path"];
     }
     $files = Input::file($name);
     if ($files["name"] == "") {
         return false;
     }
     $extension = File::extension($files["name"]);
     $directory = path($path) . $uploadOptions["directory"];
     $nameFile = sha1(Session::has("token_user") . microtime());
     $filename = "{$nameFile}.{$extension}";
     $fullPath = $directory . "/" . $filename;
     $defaultImage = $directory . "/" . $filename;
     $defaultImageName = $filename;
     $successUpload = Input::upload($name, $directory, $filename);
     if ($successUpload === false) {
         return false;
     }
     if (File::exists($directory . "/" . $beforeImage)) {
         File::delete($directory . "/" . $beforeImage);
     }
     var_dump($beforeImage);
     $beforeExtension = File::extension($beforeImage);
     $preg = $directory . "/" . preg_replace("/\\.{$beforeExtension}/", "", $beforeImage);
     if (!empty($beforeImage)) {
         foreach (glob("{$preg}*", GLOB_ONLYDIR) as $key => $dir) {
             File::rmdir($dir);
         }
     }
     foreach ($sizes as $key => $size) {
         if (!preg_match("/\\d*x\\d*/", $size)) {
             throw new Exception("Size doesnt have a valid format valid for {$size} example: ddxdd", 1);
         }
         if (!class_exists("Resizer")) {
             throw new Exception("Bundle Resizer must be installed <br> Please got to <a href='http://bundles.laravel.com/bundle/resizer'>http://bundles.laravel.com/bundle/resizer</a>", 1);
         }
         $filename = $nameFile . "_{$key}.{$extension}";
         $sizeOptions = preg_split("/x/", $size);
         $fullPath = $directory . "/{$nameFile}{$key}/" . $filename;
         $beforeImageWithSize = $directory . "/{$nameFile}{$key}/" . $beforeImage;
         if (!is_dir($directory . "/" . $nameFile . $key)) {
             mkdir($directory . "/" . $nameFile . $key, 0777);
         }
         $success = Resizer::open($defaultImage)->resize($sizeOptions[0], $sizeOptions[1], 'fit')->save($fullPath, 90);
         if ($success === false) {
             return false;
         }
     }
     return array("fullPath" => $defaultImage, "fileName" => $defaultImageName);
 }
Example #10
0
 /**
  * @return string
  */
 public function info() : string
 {
     if ($filename = $this->resolvePath()) {
         list($width, $height) = getimagesize($filename);
         return strtr(static::TEMPLATE_INFO, [':type' => \File::extension($filename), ':width' => $width, ':height' => $height]);
     } else {
         return '';
     }
 }
 public function postStore()
 {
     $id = \Input::get('id');
     /*
      * Validate
      */
     $rules = array('image' => 'mimes:jpg,jpeg,png,gif|max:500', 'name' => 'required|unique:categories,name' . (isset($id) ? ',' . $id : ''), 'short_description' => 'required', 'order' => 'required|min:0');
     $validation = \Validator::make(\Input::all(), $rules);
     if ($validation->passes()) {
         $name = \Input::get('name');
         $short_description = \Input::get('short_description');
         $long_description = \Input::get('long_description');
         $image = \Input::file('image');
         $active = \Input::get('active') == '' ? FALSE : TRUE;
         $order = \Input::get('order');
         $parent_id = \Input::get('parent_id');
         $cn_name = \Input::get('cn_name');
         $cn_short_description = \Input::get('cn_short_description');
         $cn_long_description = \Input::get('cn_long_description');
         $options = array('name' => $cn_name, 'short_description' => $cn_short_description, 'long_description' => $cn_long_description);
         $category = isset($id) ? Category::find($id) : new Category();
         $category->name = $name;
         $category->short_description = $short_description;
         $category->long_description = $long_description;
         $category->active = $active;
         $category->order = $order;
         $category->category_id = $parent_id;
         $category->options = json_encode($options);
         $category->save();
         if (\Input::hasFile('image')) {
             // Delete all existing images for edit
             if (isset($id)) {
                 $category->deleteAllImages();
             }
             //set the name of the file
             $originalFilename = $image->getClientOriginalName();
             $filename = str_replace(' ', '', $name) . \Str::random(20) . '.' . \File::extension($originalFilename);
             //Upload the file
             $isSuccess = $image->move('assets/img/categories', $filename);
             if ($isSuccess) {
                 // create photo
                 $newimage = new Image();
                 $newimage->path = $filename;
                 // save photo to the loaded model
                 $category->images()->save($newimage);
             }
         }
     } else {
         if (isset($id)) {
             return \Redirect::to('admin/categories/edit/' . $id)->withErrors($validation)->withInput();
         } else {
             return \Redirect::to('admin/categories/create')->withErrors($validation)->withInput();
         }
     }
     return \Redirect::to('admin/categories');
 }
Example #12
0
 public function assets($file = null)
 {
     if (!is_null($file) && \File::isDirectory($this->themesAssetsPath)) {
         if (!\File::exists($this->themesAssetsPath . $file)) {
             return \Response::make("Not found!", 404);
         }
         $requestedFile = \File::get($this->themesAssetsPath . $file);
         return \Response::make($requestedFile, 200, array('Content-Type' => $this->mimeMap[\Str::lower(\File::extension($this->themesAssetsPath . $file))]));
     }
     return \Redirect::route('app.home');
 }
Example #13
0
 public function fileExistFormatImage($path, $width)
 {
     $url = getcwd() . $path;
     $add = '';
     $ext = array('jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG', 'gif', 'GIF');
     if (\File::exists($url)) {
         $extension = \File::extension($url);
         if (in_array($extension, $ext)) {
             $asset = asset($path);
             return '<img src="' . $asset . '" alt="" width="' . $width . 'px" />';
         }
     }
 }
Example #14
0
 public function getFileTypeAttribute()
 {
     $extension = File::extension($this->url);
     if ($extension == 'png' || $extension == 'jpg' || $extension == 'bmp') {
         return 'image';
     } elseif ($extension == 'mp4') {
         return 'video';
     } elseif ($extension == 'pdf') {
         return 'pdf';
     } elseif ($extension == '' || $extension == 'com') {
         return 'link';
     }
     return 'other';
 }
 /**
  * 生成文件名
  * @param $file UploadedFile|SplFileInfo|string
  * @return string
  */
 public function makeFileName($file)
 {
     if (is_a($file, UploadedFile::class)) {
         $filename = date('Y-m-d-') . md5(md5_file($file->getRealPath()) . time()) . '.' . $file->getClientOriginalExtension();
     } elseif (is_a($file, SplFileInfo::class)) {
         $filename = date('Y-m-d-') . md5(md5_file($file->getRealPath()) . time()) . '.' . $file->getExtension();
     } elseif (is_string($file)) {
         $extension = \File::extension($file);
         $filename = date('Y-m-d-') . md5($file . time()) . '.' . $extension;
     } else {
         throw new \RuntimeException(__METHOD__ . ' needs a UploadedFile|SplFileInfo|string instance or a file path string');
     }
     return $filename;
 }
Example #16
0
 public function addFile(File $file, $filename = null)
 {
     // sanitize filename
     if (!($filename = Sanitizer::filename($filename))) {
         $filename = String::random(8);
     }
     $realFile = new File($filename);
     // if file type is known, set new extension
     $newFilename = $realFile->basename(false) . '.' . $realFile->extension();
     // store files in flat hirarchy
     $file = $file->move(new Dir(STATIC_DIR . $this->path), $newFilename, true);
     $this->fromArray(array('filename' => $file->basename(), 'mime_type' => $file->mimeType()));
     return $this;
 }
Example #17
0
 /**
  * @return array
  */
 public function info()
 {
     if ($this->info) {
         return $this->info;
     }
     $file = $this->getFullPath();
     if (!$this->exists()) {
         return '';
     }
     list($width, $height) = getimagesize($file);
     $extension = \File::extension($file);
     $name = \File::name($file);
     $info = ['extension' => $extension, 'name' => $name, 'width' => $width, 'height' => $height];
     return $info;
 }
 public function get_get($file_name = '')
 {
     if (!empty($file_name)) {
         $_public = path('public');
         $_data = Config::get('cms::settings.data');
         $_ext = File::extension($file_name);
         $img_mimes = array('jpg', 'jpeg', 'gif', 'png');
         if (in_array($_ext, $img_mimes)) {
             $_ext = 'img';
         }
         $_path = $_public . $_data . '/' . $_ext . '/';
         return Response::download($_path . $file_name);
     }
     return Response::error('404');
 }
Example #19
0
 public function downloadFilepraktikum($idpraktikum)
 {
     $praktikum = Praktikum::findOrFail($idpraktikum);
     $praktikumTitle = $praktikum->title;
     $filepraktikum = $praktikum->files;
     $pathTofile = public_path() . '/files/' . $filepraktikum;
     //get the file location.
     $fileExtension = \File::extension($pathTofile);
     //get the file extension
     if (\File::exists($pathTofile)) {
         return response()->download($pathTofile, $praktikumTitle . "." . $fileExtension);
     } else {
         return "File tidak terdapat dalam sistem";
     }
 }
Example #20
0
 public function post_results()
 {
     $rules = array('sample' => 'required|image');
     //Validate input
     $validation = Validator::make(Input::all(), $rules);
     if ($validation->fails()) {
         return Redirect::back()->with_errors($validation)->with_input();
     }
     $url = array();
     //save files if exists
     foreach (array('sample', 'control') as $image) {
         if (File::exists(Input::file($image . '.tmp_name'))) {
             $name = Input::file($image . '.name');
             $ext = strtolower(File::extension($name));
             $url[$image] = $this->upload_path . '/' . $image . "." . $ext;
             $url[$image] = $this->image_url . '/' . $image . "." . $ext;
             Input::upload($image, $this->upload_path, $image . "." . $ext);
         }
     }
     //end foreach
     //analyze images submitted
     $litmus = new Litmus($this->LITMUS_ACCOUNT, $this->LITMUS_TOKEN);
     if (isset($url['sample'])) {
         $litmus->set_sample_url($url['sample']);
     }
     if (isset($url['control'])) {
         $litmus->set_control_url($url['control']);
     }
     if (Input::has('scale_id')) {
         $litmus->set_scale_id(Input::get('scale_id'));
     }
     $response = $litmus->analyze();
     if ($response->status == 'error') {
         echo $response->message;
         exit;
     }
     //recursive function for outputting a heirarchial data tree
     $string = "<ul>" . Mockup\Util::recursiveTree($response) . "</ul>";
     $data = array();
     $data['title'] = "Image Analysis";
     $data['lead'] = "Response from Litmus API";
     $tabs = array(array('Swatch', '#swatch', 'active'), array('Code', '#code'));
     $data['tabs'] = View::make('mockup::partials.tabs')->with('tabs', $tabs)->render();
     $data['code'] = $string;
     $data['response'] = $response;
     Asset::container('scripts')->add('colorbox', 'bundles/mockup/assets/js/colorbox.js');
     return View::make('mockup::pages.result', $data);
 }
Example #21
0
 /** 
  * Force a file download by setting headers.  
  * @param string path to file 
  * @param string extension 
  * @param string file name on client side  
  * @example download('folder/error_log.pdf') 
  * @example download('folder/error_log.pdf', 'pdf' ,'log.pdf')  
  * @return boolean
  */
 public static function download($path = false, $extension = false, $name = false)
 {
     if ($path && File::isFile($path)) {
         if (!$extension) {
             $extension = File::extension($path);
         }
         if (!$name) {
             $name = basename($path);
         }
         header('Content-Type: application/' . $extension);
         header("Content-Transfer-Encoding: Binary");
         header("Content-disposition: attachment; filename=" . $name);
         readfile($path);
         exit;
     }
     return false;
 }
Example #22
0
 /**
  * Attempts to upload a file, adds it to the database and removes other database entries for that file type if they are asked to be removed
  * @param  string  $field             The name of the $_FILES field you want to upload
  * @param  boolean $upload_type       The type of upload ('news', 'gallery', 'section') etc
  * @param  boolean $type_id           The ID of the item (above) that the upload is linked to
  * @param  boolean $remove_existing   Setting this to true will remove all existing uploads of the passed in type (useful for replacing news article images when a new on
  * @param  boolean $title             Sets the title of the upload
  * @param  boolean $path_to_store     Sets the path to the upload (where it should go)
  * @return object                     Returns the upload object so we can work with the uploaded file and details
  */
 public static function upload($details = array())
 {
     $upload_details = array('remove_existing_for_link' => true, 'path_to_store' => path('public') . 'uploads/', 'resizing' => array('small' => array('w' => 200, 'h' => 200), 'thumb' => array('w' => 200, 'h' => 200)));
     if (!empty($details)) {
         $required_keys = array('upload_field_name', 'upload_type', 'upload_link_id', 'title');
         $continue = true;
         foreach ($required_keys as $key) {
             if (!isset($details[$key]) || empty($details[$key])) {
                 Messages::add('error', 'Your upload array details are not complete... please fill this in properly.');
                 $continue = false;
             }
         }
         if ($continue) {
             $configuration = $details + $upload_details;
             $input = Input::file($configuration['upload_field_name']);
             if ($input && $input['error'] == UPLOAD_ERR_OK) {
                 if ($configuration['remove_existing_for_link']) {
                     static::remove($configuration['upload_type'], $configuration['upload_link_id']);
                 }
                 $ext = File::extension($input['name']);
                 $filename = Str::slug($configuration['upload_type'] . '-' . $configuration['upload_link_id'] . '-' . Str::limit(md5($input['name']), 10, false) . '-' . $configuration['title'], '-');
                 Input::upload($configuration['upload_field_name'], $configuration['path_to_store'], $filename . '.' . $ext);
                 $upload = new Upload();
                 $upload->link_type = $configuration['upload_type'];
                 $upload->link_id = $configuration['upload_link_id'];
                 $upload->filename = $filename . '.' . $ext;
                 if (Koki::is_image($configuration['path_to_store'] . $filename . '.' . $ext)) {
                     $upload->small_filename = $filename . '_small' . '.' . $ext;
                     $upload->thumb_filename = $filename . '_thumb' . '.' . $ext;
                     $upload->image = 1;
                 }
                 $upload->extension = $ext;
                 $upload->user_id = Auth::user()->id;
                 $upload->save();
                 if (Koki::is_image($configuration['path_to_store'] . $filename . '.' . $ext)) {
                     WideImage::load($configuration['path_to_store'] . $upload->filename)->resize($configuration['resizing']['small']['w'], $configuration['resizing']['small']['h'])->saveToFile($configuration['path_to_store'] . $upload->small_filename);
                     WideImage::load($configuration['path_to_store'] . $upload->small_filename)->crop('center', 'center', $configuration['resizing']['thumb']['w'], $configuration['resizing']['thumb']['h'])->saveToFile($configuration['path_to_store'] . $upload->thumb_filename);
                 }
                 return true;
             }
         }
     } else {
         Messages::add('error', 'Your upload array details are empty... please fill this in properly.');
     }
     return false;
 }
Example #23
0
 /**
  * Upload the attachment
  *
  * @param  array  $input
  * @return bool
  */
 public static function upload($input)
 {
     $path = \Config::get('application.upload_path');
     if (!file_exists($path = $path . $input['project_id'])) {
         mkdir($path);
     }
     if (!file_exists($path = $path . '/' . $input['upload_token'])) {
         mkdir($path);
     }
     $file = \Input::file('Filedata');
     \File::upload('Filedata', $file_path = $path . '/' . $file['name']);
     $fill = array('uploaded_by' => \Auth::user()->id, 'filename' => $file['name'], 'fileextension' => \File::extension($file_path), 'filesize' => $file['size'], 'upload_token' => $input['upload_token']);
     $attachment = new static();
     $attachment->fill($fill);
     $attachment->save();
     return true;
 }
Example #24
0
 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);
 }
Example #25
0
 /**
  * Appends an incremental counter to a file name.
  *
  * @param $file
  * @return string
  */
 function append_counter_to_filename($file)
 {
     if (!File::exists($file)) {
         return $file;
     }
     $filename = basename($file);
     $ext = File::extension($file);
     if ($ext) {
         $ext = ".{$ext}";
         $filename = substr($filename, 0, strlen($filename) - strlen($ext));
     }
     $increment = 1;
     if (preg_match('/(.)+_\\d+/', $filename)) {
         $pos = strrpos($file, "_");
         $filename = substr($filename, 0, $pos);
         $increment = intval(substr($filename, $pos + 1)) + 1;
     }
     return $filename . "_" . $increment . $ext;
 }
Example #26
0
 public static function get($file)
 {
     $extension = File::extension($file);
     if (array_key_exists($extension, self::$type)) {
         return self::$type[$extension];
     } else {
         if (function_exists('finfo_open') && function_exists('finfo_file') && function_exists('finfo_close')) {
             $info = finfo_open(FILEINFO_MIME_TYPE);
             $mime = finfo_file($info, $file);
             finfo_close($info);
             return $mime;
         } elseif (function_exists('mime_content_type')) {
             $mime = mime_content_type($file);
             return $mime;
         } else {
             return 'application/octet-stream';
         }
     }
 }
Example #27
0
 /**
  * Twig Markup Filter 'flipCss'
  * @param $paths
  * @param bool $force
  * @return array|string
  */
 public function flipCss($paths)
 {
     if (!LanguageDetector::isRtl()) {
         return $paths;
     }
     if (!is_array($paths)) {
         $paths = [$paths];
     }
     $rPaths = [];
     foreach ($paths as $path) {
         $assetPath = $path;
         if (File::exists(dirname($assetPath) . '/' . File::name($assetPath) . '.rtl.' . File::extension($assetPath))) {
             $newPath = dirname($assetPath) . '.rtl.' . File::extension($assetPath);
         } else {
             $newPath = CssFlipper::flipCss($assetPath, true);
         }
         $rPaths[] = $newPath;
     }
     return $rPaths;
 }
 public function postUpload()
 {
     $input = Input::all();
     $rules = array('photo' => 'required|image|max:500');
     $v = Validator::make($input, $rules);
     if ($v->fails()) {
         return Redirect::to('profile');
     }
     $extensions = File::extension($input['photo'], ['name']);
     $directory = path('app') . 'foundation-5.4.0/img' . sha1(Auth::user()->id);
     $filename = sha1(Auth::user()->id) . ".{$extension}";
     $upload_success = Input::upload('photo', $directory, $filename);
     if ($upload_success) {
         $photo = new Photo(array('location' => URL::to('uploads/' . sha1(Auth::user()->id) . '/' . $filename)));
         Auth::user()->photos()->insert($photo);
         Session::flash('status_success', 'successful yay');
     } else {
         Session::flash('status_error', 'failed NO!!!! upload failed');
     }
     return Redirect::to('profile');
 }
 public function getAddOn($path)
 {
     $path = dirname(__FILE__) . '/../addons/' . $path;
     $ext = File::extension($path);
     $type = 'text/html';
     switch ($ext) {
         case 'css':
             $type = 'text/css';
             break;
         case 'js':
             $type = 'text/javascript';
             break;
         case 'png':
             $type = 'image/png';
             break;
         default:
             # code...
             break;
     }
     $contents = File::get($path);
     $response = Response::make($contents, 200);
     $response->header('Content-Type', $type);
     return $response;
 }
 /**
  * @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('文件未接收完整,请求继续发送数据');
 }