public function index()
 {
     $login = Auth::check('member');
     $softwares = Software::find('all', array('order' => array('created' => 'DESC')));
     $files = File::find('all');
     return compact('login', 'softwares', 'files');
 }
Exemplo n.º 2
0
 /**
  * Lists all File models.
  * @return mixed
  */
 public function actionIndex()
 {
     if (!Yii::$app->user->can("admin")) {
         throw new HttpException(403, 'You are not allowed to perform this action.');
     }
     $dataProvider = new ActiveDataProvider(['query' => File::find()]);
     return $this->render('index', ['dataProvider' => $dataProvider]);
 }
Exemplo n.º 3
0
 public function document()
 {
     $user = Session::read('member');
     $id = md5($user['email']);
     $document = Details::find('first', array('conditions' => array('user_id' => (string) $user['_id'])));
     //		if(count($document)==0){return $this->redirect('/');}
     $uploadOk = 1;
     if ($this->request->data) {
         $extension = pathinfo($this->request->data['file']['name'], PATHINFO_EXTENSION);
         $allowed = array('pdf');
         if (!in_array(strtolower($extension), $allowed)) {
             $msg = "Sorry, only PDF files are allowed.";
             $uploadOk = 0;
         }
         if ($uploadOk = 1) {
             $option = 'doc';
             $data = array('details_' . $option . '_id' => (string) $document['_id'], 'docname' => $this->request->data['docname'], 'date' => $this->request->data['date'], 'DateTime' => new \MongoDate(), 'keywords' => $this->request->data['keywords'], 'description' => $this->request->data['description'], $option => $this->request->data['file'], $option . '.verified' => 'No', $option . '.IP' => $_SERVER['REMOTE_ADDR']);
             $field = 'details_' . $option . '_id';
             $Documents = Documents::create($data);
             $saved = $Documents->save();
             $fileData = array('file' => $this->request->data['file'], 'documents_' . $option . '_id' => (string) $Documents->_id);
             $file = File::create();
             if ($file->save($fileData)) {
                 $msg = "Upload OK";
             }
             $image_address = File::find('first', array('conditions' => array('documents_doc_id' => (string) $Documents->_id)));
             if ($image_address['filename'] != "") {
                 $imagename_address = $image_address['_id'] . '_' . $image_address['filename'];
                 $path = LITHIUM_APP_PATH . '/webroot/download/' . $imagename_address;
                 file_put_contents($path, $image_address->file->getBytes());
             }
             //		print_r($path);
             $pages = $this->getPDFPages($path);
             // Output: 13
             //				print_r($pages);exit;
             unlink($path);
             $docdata = array();
             foreach ($pages as $page) {
                 $params = explode(":", $page);
                 $left = $params[0];
                 $right = $params[1];
                 $docdata = array_merge($docdata, array($left => trim($right)));
             }
             $data = array("document" => $docdata);
             $conditions = array("_id" => (string) $Documents->_id);
             Documents::update($data, $conditions);
             // Use the function
         }
     }
     return $this->redirect('ex::save');
 }
Exemplo n.º 4
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = File::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'user_id' => $this->user_id, 'size' => $this->size, 'date_entered' => $this->date_entered, 'date_updated' => $this->date_updated]);
     $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'type', $this->type])->andFilterWhere(['like', 'description', $this->description]);
     return $dataProvider;
 }
Exemplo n.º 5
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = File::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['file_id' => $this->file_id, 'file_time' => $this->file_time, 'file_msg_id' => $this->file_msg_id, 'file_user_id' => $this->file_user_id, 'file_size' => $this->file_size]);
     $query->andFilterWhere(['like', 'file_orig_name', $this->file_orig_name])->andFilterWhere(['like', 'file_type', $this->file_type])->andFilterWhere(['like', 'file_name', $this->file_name]);
     return $dataProvider;
 }
Exemplo n.º 6
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = File::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'rec_id' => $this->rec_id, 'type_id' => $this->type_id, 'rec_status_id' => $this->rec_status_id, 'user_id' => $this->user_id, 'dc' => $this->dc]);
     $query->andFilterWhere(['like', 'table_name', $this->table_name])->andFilterWhere(['like', 'class_name', $this->class_name])->andFilterWhere(['like', 'file_name', $this->file_name])->andFilterWhere(['like', 'file_path', $this->file_path])->andFilterWhere(['like', 'note', $this->note]);
     return $dataProvider;
 }
Exemplo n.º 7
0
 public function view($id = null)
 {
     $user = Session::read('member');
     if ($user == "") {
         return $this->redirect('/');
     }
     $image_address = File::find('first', array('conditions' => array('documents_doc_id' => (string) $id)));
     if ($image_address['filename'] != "") {
         $imagename_address = $image_address['_id'] . '_' . $image_address['filename'];
         $path = LITHIUM_APP_PATH . '/webroot/download/' . $imagename_address;
         file_put_contents($path, $image_address->file->getBytes());
     }
     return compact('imagename_address');
 }
Exemplo n.º 8
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = File::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]);
     $query->andFilterWhere(['like', 'filename', $this->filename])->andFilterWhere(['like', 'avatar', $this->avatar])->andFilterWhere(['like', 'type', $this->type]);
     return $dataProvider;
 }
Exemplo n.º 9
0
 /**
 * Creates data provider instance with search query applied
 *
 * @param array $params
 *
 * @return ActiveDataProvider
 */
 public function search($params)
 {
     $query = File::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'startdate' => $this->startdate, 'enddate' => $this->enddate, 'sensorid' => $this->sensorid]);
     $query->andFilterWhere(['like', 'filelink', $this->filelink])->andFilterWhere(['like', 'filename', $this->filename])->andFilterWhere(['like', 'extension', $this->extension])->andFilterWhere(['like', 'status', $this->status]);
     return $dataProvider;
 }
Exemplo n.º 10
0
 private function saveHeaders($file, $fileID)
 {
     //create the path
     $fileName = base_path() . "/public/files/" . $file->getClientOriginalName();
     //create the empty arrays
     $columnTitles = [];
     $taxonomyArray = [];
     $fieldArray = [];
     //load the file
     $rows = Excel::load($fileName, function ($reader) {
     })->get();
     //set the values of the columns as the header
     foreach ($rows as $title => $value) {
         //set the row data
         foreach ($value as $key => $column) {
             $columnTitles[$key][] = $column;
         }
     }
     $files = File::find($fileID);
     foreach ($columnTitles as $key => $value) {
         $field_tax = Field_Taxonomy::where('title', '=', $key);
         $fieldTaxID = 0;
         $count = 1;
         //if the title doesn't exist as a record in the field_tax table
         if ($field_tax->count() === 0) {
             //grab the id of the newly inserted taxonomy record
             $fieldTaxID = Field_Taxonomy::insertGetId(['title' => $key]);
             foreach ($value as $data) {
                 Field::insert(['value' => $data, 'field_taxonomy_id' => $fieldTaxID, 'row_in_file' => $count]);
                 $count++;
             }
             File_Field_Taxonomy::insert(['file_id' => $fileID, 'field_taxonomy_id' => $fieldTaxID]);
         } else {
             $fileArr = explode(".", $file->getClientOriginalName());
             $fileTitleArr = explode("_", $fileArr[0]);
             $fieldTax = Field_Taxonomy::take(1)->select('field_taxonomy_table.id')->join('file_field_taxonomy_table', 'file_field_taxonomy_table.field_taxonomy_id', '=', 'field_taxonomy_table.id')->join('files', 'files.id', '=', 'file_field_taxonomy_table.file_id')->where('title', '=', $key)->where('parsed_title', '=', $fileTitleArr[0])->get();
             if (count($fieldTax) > 0) {
                 $fieldTaxID = $fieldTax[0]->id;
             } else {
                 $fieldTaxID = Field_Taxonomy::insertGetId(['title' => $key]);
             }
             foreach ($value as $data) {
                 Field::insert(['value' => $data, 'field_taxonomy_id' => $fieldTaxID, 'row_in_file' => $count]);
                 $count++;
             }
             File_Field_Taxonomy::insert(['file_id' => $fileID, 'field_taxonomy_id' => $fieldTaxID]);
         }
     }
 }
Exemplo n.º 11
0
 static function getImageAsResponse($id, $imageId, $size = 0)
 {
     $file = File::find($imageId);
     if ($file) {
         try {
             $path = self::getImageFromStorage($id, $file->new_filename);
             $img = Image::make($path);
             if ($size > 0) {
                 $img->resize($size, null, function ($constraint) {
                     $constraint->aspectRatio();
                 });
             }
             return response($img->encode($img->extension), 200)->header('Content-Type', $img->mime);
         } catch (\Exception $e) {
             return new \RuntimeException($e);
         }
     }
 }
Exemplo n.º 12
0
 /**
  * Create a file sharing request
  */
 public function create($input)
 {
     $user = \Auth::user();
     $input['user_id'] = $user->id;
     $now = \Carbon\Carbon::now();
     $input['expires_at'] = $now->addDays($input['expires_at'])->toDateTimeString();
     $request = \App\Models\SharedFileRequest::create($input);
     if ($request) {
         foreach ($input['files'] as $file) {
             $fileShare = \App\Models\SharedFile::create(['request_id' => $request->id, 'file_id' => $file['id'], 'user_id' => $user->id]);
             $file = FSFile::find($file['id']);
             $file->resolvable_type = 'FileShare';
             $file->resolvable_id = $fileShare->id;
             $file->save();
         }
         foreach ($input['recipients'] as $recipient) {
             $d = \App\Models\SharedFileRecipient::create(['request_id' => $request->id, 'email' => $recipient]);
         }
         \Event::fire(new \App\Events\FileShared($request));
     }
     return $request;
 }
Exemplo n.º 13
0
 /**
  * Verify request
  * @param $id
  */
 public function actionVerify($id)
 {
     if (!Yii::$app->user->can("admin")) {
         throw new HttpException(403, 'You are not allowed to perform this action.');
     }
     $user = \Yii::$app->user->identity;
     $request = Request::find()->where(['id' => $id])->one();
     $user = User::find()->where(['id' => $request->user_id])->one();
     $profile = Profile::find()->where(['user_id' => $user->id])->one();
     $request_files = RequestFile::find()->where(['request_id' => $request->id])->all();
     $files = [];
     if ($request_files !== NULL) {
         foreach ($request_files as $rf) {
             $file = File::find()->where(['id' => $rf->file_id])->one();
             array_push($files, $file);
         }
     }
     if ($request === NULL) {
         $this->redirect(['site/error']);
     }
     return $this->render('verify', ['request' => $request, 'user' => $user, 'profile' => $profile, 'files' => $files]);
 }
Exemplo n.º 14
0
 public function Approve($media = null, $id = null, $response = null)
 {
     if ($this->__init() == false) {
         $this->redirect('ex::dashboard');
     }
     if ($response != "") {
         if ($response == "Approve") {
             $data = array($media . ".verified" => "Yes");
         } elseif ($response == "Reject") {
             $data = array($media . ".verified" => "No");
         }
         $details = Details::find('first', array('conditions' => array('_id' => $id)))->save($data);
     }
     $details = Details::find('first', array('conditions' => array('_id' => $id)));
     $image_utility = File::find('first', array('conditions' => array('details_' . $media . '_id' => (string) $details['_id'])));
     if ($image_utility['filename'] != "") {
         $imagename_utility = $image_utility['_id'] . '_' . $image_utility['filename'];
         $path = LITHIUM_APP_PATH . '/webroot/documents/' . $imagename_utility;
         file_put_contents($path, $image_utility->file->getBytes());
     }
     $this->_render['layout'] = 'image';
     $title = "Approve";
     $keywords = "Approve, documents";
     $description = "Admin Approve documents ";
     return compact('imagename_utility', 'media', 'id', 'title', 'keywords', 'description', 'settings');
 }
Exemplo n.º 15
0
 public function settings($option = null)
 {
     $title = "User settings";
     $ga = new GoogleAuthenticator();
     $user = Session::read('default');
     if ($user == "") {
         return $this->redirect('/login');
     }
     $id = $user['_id'];
     $details = Details::find('first', array('conditions' => array('user_id' => (string) $id)));
     $uploadOk = 1;
     $qrCodeUrl = $ga->getQRCodeGoogleUrl(COMPANY_URL . "-" . $details['username'], $details['secret']);
     if ($this->request->data) {
         $imageFileType = pathinfo($this->request->data['file']['name'], PATHINFO_EXTENSION);
         if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
             $msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
             $uploadOk = 0;
             return $this->redirect('Users::settings', compact('msg'));
         }
         if ($uploadOk = 1) {
             $option = $this->request->data['option'];
             $data = array($option => $this->request->data['file'], $option . '.verified' => 'No');
             $field = 'details_' . $option . '_id';
             $remove = File::remove('all', array('conditions' => array($field => (string) $details->_id)));
             $fileData = array('file' => $this->request->data['file'], 'details_' . $option . '_id' => (string) $details->_id);
             $details = Details::find('first', array('conditions' => array('user_id' => (string) $id)))->save($data);
             $file = File::create();
             if ($file->save($fileData)) {
                 $this->redirect('ex::dashboard');
             }
         }
         $TOTP = $details['TOTP.Validate'];
         $secret = $details['secret'];
     }
     $details = Details::find('first', array('conditions' => array('user_id' => (string) $id)));
     $image_address = File::find('first', array('conditions' => array('details_address_id' => (string) $details['_id'])));
     if ($image_address['filename'] != "") {
         $imagename_address = $image_address['_id'] . '_' . $image_address['filename'];
         $path = LITHIUM_APP_PATH . '/webroot/documents/' . $imagename_address;
         file_put_contents($path, $image_address->file->getBytes());
     }
     $image_government = File::find('first', array('conditions' => array('details_government_id' => (string) $details['_id'])));
     if ($image_government['filename'] != "") {
         $imagename_government = $image_government['_id'] . '_' . $image_government['filename'];
         $path = LITHIUM_APP_PATH . '/webroot/documents/' . $imagename_government;
         file_put_contents($path, $image_government->file->getBytes());
     }
     $image_bank = File::find('first', array('conditions' => array('details_bank_id' => (string) $details['_id'])));
     if ($image_bank['filename'] != "") {
         $imagename_bank = $image_bank['_id'] . '_' . $image_bank['filename'];
         $path = LITHIUM_APP_PATH . '/webroot/documents/' . $imagename_bank;
         file_put_contents($path, $image_bank->file->getBytes());
     }
     $settings = Settings::find('first');
     return compact('details', 'user', 'title', 'qrCodeUrl', 'secret', 'option', 'imagename_address', 'imagename_government', 'imagename_bank', 'settings', 'msg');
 }
Exemplo n.º 16
0
 public function profile_picture()
 {
     $picture = File::find($this->profile_picture_id);
     return $picture ? $picture : File::find(DEFAULT_PROFILE_PICTURE_ID);
 }
Exemplo n.º 17
0
 /**
  * Revoke Permission on a File for a User
  *
  * @param Int $id
  * @param String $access
  * @param Int $group
  * @param Request $request
  * @return Response
  */
 public function deleteGroupPermission($id, $access, $group, Request $request)
 {
     if (!$this->appKeyAvailable($request)) {
         return $this->notAuthorized($request);
     }
     $file = File::find($id);
     if (!$this->setSessionUser($request)) {
         $this->setResultError("Not logged in", 401);
     } elseif (!$file) {
         $this->setResultError("File is not found", 404);
     } elseif (!$this->isAllowed($request, 'file', $id, 'update') && !$this->isModerator()) {
         $this->setResultError("Unauthorized action", 403);
     } elseif (!in_array($access, ['read', 'update', 'delete', 'all'])) {
         $this->setResultError("Unknown permission '{$access}'", 400);
     } else {
         $this->setUnAllowed(null, $id, null, $group, $access);
         $this->setResultOk();
     }
     return $this->setResponse();
 }
Exemplo n.º 18
0
 function getPhoto($userId)
 {
     $user = User::find($userId);
     try {
         if ($user) {
             $imageFile = File::find($user->profile_photo_file_id);
             if ($imageFile) {
                 $img = Image::make(env('FILE_UPLOAD_PATH') . $imageFile->new_filename);
                 $img->resize(300, null, function ($constraint) {
                     $constraint->aspectRatio();
                 });
                 return $img->response('png');
             }
         }
     } catch (\Exception $e) {
     }
     $img = Image::make('images/avatar_2x.png');
     return $img->response('png');
 }
Exemplo n.º 19
0
 /**
  * Lists all File models.
  * @return mixed
  */
 public function actionAdmin()
 {
     $dataProvider = new ActiveDataProvider(['query' => File::find()]);
     return $this->render('admin', ['dataProvider' => $dataProvider]);
 }
Exemplo n.º 20
0
 /**
  * Store a newly created plan in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(StorePlanRequest $request)
 {
     // create new record
     $plan = Plan::create($request->except(['start', 'end']));
     // set some defaults
     $plan->changer = Auth::user()->first_name;
     $plan->state = 1;
     $planDate = Carbon::instance($plan->date);
     // insert default service TIMES if requested
     if ($request->input('defaultValues') == 'Y') {
         $type = Type::find($plan->type_id);
         if (count($type)) {
             // default end time is only the time of day. We need to combine this with the plan date
             $startTme = Carbon::parse($type->start);
             $endTime = Carbon::parse($type->end);
             $plan->date = $planDate->copy()->addHour($startTme->hour)->addMinute($startTme->minute);
             $plan->date_end = $planDate->addHour($endTime->hour)->addMinute($endTime->minute);
         }
     } else {
         // request contains custom start and end times
         $startTme = Carbon::parse($request->start);
         $endTime = Carbon::parse($request->end);
         $plan->date = $planDate->copy()->addHour($startTme->hour)->addMinute($startTme->minute);
         $plan->date_end = $planDate->addHour($endTime->hour)->addMinute($endTime->minute);
     }
     $plan->save();
     addDefaultRolesAndResourcesToPlan($plan);
     // insert default items if requested
     if ($request->input('defaultItems') == 'Y') {
         $dItems = DefaultItem::where('type_id', $plan->type_id)->get();
         // $newItems = [];
         foreach ($dItems as $dItem) {
             // get single default item to create a nwe Item object
             $iNew = new Item(['seq_no' => $dItem->seq_no, 'comment' => $dItem->text, 'forLeadersEyesOnly' => $dItem->forLeadersEyesOnly]);
             // save the new item to the new plan
             $plan->items()->save($iNew);
             // if default item contains a default image, link the new Plan item to the image
             if ($dItem->file_id) {
                 $file = File::find($dItem->file_id);
                 $iNew->files()->save($file);
             }
             // array_push( $newItems, $iNew );
         }
     }
     flash('New Plan added with id ' . $plan->id);
     // redirect back to the plan editor to create another plan
     if ($request->input('addAnother') == 'Y') {
         // use heper function to calculate next date for this plan
         $newDate = getNextPlanDate($plan);
         // send the default values to the View
         $request->session()->flash('defaultValues', ['type_id' => $plan->type_id, 'date' => $newDate, 'start' => $startTme->toTimeString(), 'end' => $endTime->toTimeString(), 'leader_id' => $plan->leader_id]);
         // get list of service types
         $types = Type::get();
         // get list of users
         $users = User::orderBy('first_name')->get();
         return view($this->view_one, array('types' => $types, 'users' => $users));
     }
     return \Redirect::route('plans.edit', $plan->id);
 }
Exemplo n.º 21
0
 /**
  * Unlink a file attachment
  *
  * - - RESTful API request - -
  *
  * @param int $id
  *
  */
 public function APIunlink(Request $request)
 {
     $song_id = $request->has('song_id') ? $request->song_id : 0;
     $file_id = $request->has('file_id') ? $request->file_id : 0;
     if (!$song_id || !$file_id) {
         return response()->json(['status' => 404, 'data' => 'API: songId or fileId missing!'], 404);
     }
     // find the single resource
     $file = File::find($file_id);
     if ($file && $file->song_id == $song_id) {
         $file->song_id = null;
         $file->save();
         // return to sender
         return response()->json(['status' => 200, 'data' => 'File unlinked!']);
     }
     return response()->json(['status' => 404, 'data' => 'File with id ' . $file_id . ' not found or song is not linked to this file!'], 404);
 }
Exemplo n.º 22
0
 private function removeFile($id)
 {
     $success = false;
     $file = File::find($id);
     if (unlink($file->real_path())) {
         $success = File::find($id)->forceDelete();
     }
     return $success;
 }
Exemplo n.º 23
0
 public function download($folder_id, $id)
 {
     $file = File::find($id);
     if (!$file) {
         return abort(404);
     }
     return response()->download(public_path($file->path), $file->name);
 }
Exemplo n.º 24
0
 public function profile_picture()
 {
     $picture = File::find($this->profile_picture_id);
     return $picture ? $picture : File::find(DEFAULT_COMPANY_MISSING_PICTURE_ID);
 }
Exemplo n.º 25
0
 public function deleteFile($projectId, $fileId)
 {
     /* @var Project $project */
     /* @var File $file */
     $project = Project::find($projectId);
     $file = File::find($fileId);
     $project->files()->detach($file->id);
     if ($file->delete()) {
         return $file;
     }
     return response("Cannot Delete File", 400);
 }
Exemplo n.º 26
0
 public function destroy(Request $request, $id)
 {
     $v = Announcement::find($id);
     if ($v) {
         // retrieve image detail prior to deletion
         $images = DB::table('files')->join('announcement_files', 'files.id', '=', 'announcement_files.file_id')->where('announcement_files.announcement_id', $id)->get();
         $res = Announcement::where("id", $id)->where('user_id', Auth::user()->id)->delete();
         if ($res) {
             // delete also the images from db and local storage
             if (count($images) > 0) {
                 foreach ($images as $image) {
                     try {
                         $imgFile = File::find($image->file_id);
                         if ($imgFile) {
                             $imgFile->delete();
                             \Illuminate\Support\Facades\File::delete(MyHelper::getImageFromStorage($id, $imgFile->new_filename));
                         }
                     } catch (\Exception $e) {
                         Log::info($e->getMessage());
                     }
                 }
             }
             $request->session()->flash("notif", "Announcement successfully deleted");
             return ['error' => false];
         } else {
             return ['error' => true, 'message' => 'Failed to delete announcement!'];
         }
     } else {
         $request->session()->flash("notif", "announcement not available!");
         return ['error' => true];
     }
 }
Exemplo n.º 27
0
 public function show($id)
 {
     $file = File::find($id);
     return response()->download($file->real_path(), $file->name);
 }
Exemplo n.º 28
0
 /**
  * @param \App\Events\Files\Uploaded $event
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function handle(Uploaded $event)
 {
     $uploadUuid = $event->uploadUuid;
     $request = $event->request;
     /*
     |--------------------------------------------------
     | Move file to its final permanent destination.
     |--------------------------------------------------
     */
     $hash = hash_file('sha256', app('filestream')->getAbsolutePath($uploadUuid));
     $destination = $hash;
     if (config('filesystems.load_balancing.enabled')) {
         $config = config('filesystems.load_balancing');
         $folders = [];
         for ($i = 0; $i < $config['depth']; $i++) {
             $folders[] = substr($hash, -1 * ($i + 1) * $config['length'], $config['length']);
         }
         $destination = implode(DIRECTORY_SEPARATOR, array_merge($folders, [$hash]));
     }
     $filesystem = app('filesystem')->disk();
     !$filesystem->exists($destination) ? $filesystem->move($uploadUuid, $destination) : $filesystem->delete($uploadUuid);
     /*
     |---------------------------------
     | Check the tag and its limit.
     |---------------------------------
     */
     /** @var \App\Models\User $me */
     $me = app('sentinel')->getUser();
     $tag = $request->get('qqtag');
     $tagLimit = config('filesystems.allowed_tags_and_limits.' . $tag);
     if ($tagLimit > 0) {
         $allFilesWithSameTagBelongingToUser = $me->load(['files' => function (BelongsToMany $query) use($tag) {
             $query->wherePivot('tag', '=', $tag);
         }])->files;
         if (($numberOfFilesToDeleteToComplyWitTagLimit = $allFilesWithSameTagBelongingToUser->count() - $tagLimit + 1) > 0) {
             while ($numberOfFilesToDeleteToComplyWitTagLimit > 0) {
                 $pivotToDelete = $allFilesWithSameTagBelongingToUser->shift();
                 app('filestream')->deleteFile($pivotToDelete->hash, $tag);
                 $numberOfFilesToDeleteToComplyWitTagLimit--;
             }
         }
     }
     /*
     |------------------------------------
     | Persist file record in database.
     |------------------------------------
     */
     $uploadedFile = new SymfonyFile(app('filestream')->getAbsolutePath($destination));
     if (!($file = File::find($hash = $uploadedFile->getFilename()))) {
         $file = new File();
         $file->hash = $hash;
         $file->disk = 'local';
         $file->path = trim(str_replace(config('filesystems.disks.local.root'), '', $uploadedFile->getPathname()), DIRECTORY_SEPARATOR);
         $file->mime = $uploadedFile->getMimeType();
         $file->size = $uploadedFile->getSize();
         $file->save();
     }
     $me->files()->newPivotStatement()->whereTag($tag)->whereFileHash($hash)->delete();
     $file->uploaders()->attach([$me->getUserId() => ['uuid' => $request->get('qquuid'), 'original_client_name' => $request->get('qqfilename'), 'tag' => $tag]]);
     return response()->json(['success' => true, 'hash' => $file->hash])->setStatusCode(IlluminateResponse::HTTP_CREATED);
 }
Exemplo n.º 29
0
/**
 * Insert a new item into the list of items of a plan
 *
 * Make sure the new sequence number fits sequentially into 
 *    the list of sequence numbers of the existing items for a plan
 *    and that all current sequence numbers are in 1.0 steps
 *
 * @param object $request
 */
function insertItem($request)
{
    // get plan id from the hidden input field in the form
    $plan_id = $request->plan_id;
    // get new seq no for this item
    $new_seq_no = $request->seq_no;
    // get the Plan model and find the plan
    $plan = Plan::find($plan_id);
    // get all the items for this plan, ordered by their seq_no
    $items = $plan->items()->orderBy('seq_no')->get();
    Log::debug('INSERTITEM - newSeqNo old: ' . $new_seq_no);
    // We are going to number all the items of this plan, starting with 1.0
    $counter = 1.0;
    // if the new item already has a seq_no of 1 or smaller, we change it to one
    //    and increase the counter, so that all subsequent items have the correct seq_no
    if ($new_seq_no <= $counter) {
        $new_seq_no = 1;
        $counter = 2;
    }
    // Loop through each item of the plan, making sure the
    //      seq_no of each item is always 1.0 bigger than the previous
    foreach ($items as $item) {
        Log::debug('$counter - $item->seq_no - $new_seq_no --- ' . $counter . ' - ' . $item->seq_no . ' - ' . $new_seq_no);
        // Is this the position (seq_no) for the NEW ITEM?
        if ($new_seq_no <= $item->seq_no && $new_seq_no > $counter - 1) {
            $new_seq_no = $counter;
            $counter += 1;
        }
        // If we inserted the new item earlier, all subsequent items
        //    need to have a new seq_no
        if ($item->seq_no != $counter) {
            # update the current loop-item to correspond to the counter
            $item->seq_no = $counter;
            # Now get  the actual DB record
            $i = Item::find($item->id);
            // update the item accordingly
            $i->seq_no = $counter;
            $i->save();
        }
        // increase the counter to reflect the current seq_no
        $counter += 1.0;
    }
    // change new seq_no if it's bigger than the current counter
    if ($new_seq_no >= $counter - 1) {
        $new_seq_no = $counter;
    }
    Log::debug('INSERTITEM - newSeqNo new: ' . $new_seq_no);
    // create a new Item using the input data from the request
    $newItem = new Item($request->except(['seq_no', 'moreItems', '_token']));
    $newItem->seq_no = $new_seq_no;
    // check if a song id was provided in the request
    if (isset($request->song_id)) {
        $newItem->song_freshness = calculateSongFreshness($request->song_id, $plan->leader_id, $plan->date);
        $newItem->song_id = $request->song_id;
    }
    // saving the new Item via the relationship to the Plan
    $item = $plan->items()->save($newItem);
    $plan->new_seq_no = $new_seq_no;
    $plan->newest_item_id = $item->id;
    // notify event listener that an item was updated
    $new_item = Item::find($plan->newest_item_id);
    if ($new_item) {
        event(new CspotItemUpdated($new_item));
    }
    // handle file uplaods
    if ($request->hasFile('file')) {
        flash('Image file added!');
        if ($request->file('file')->isValid()) {
            // use the helper function
            $file = saveUploadedFile($request);
            // add the file as a relationship to the song
            $item->files()->save($file);
        } else {
            flash('Uploaded file could not be validated!');
        }
    }
    // handle file linking
    if ($request->has('file_id')) {
        // get the requested file as object
        $file = File::find($request->file_id);
        // and save it to the plan item
        $item->files()->save($file);
        // set item comment to filename
        if ($item->comment == null || $item->comment == false || $item->comment == '' || $item->comment == ' ') {
        }
        $item->update(['comment' => $file->filename]);
        flash('Image file was added to the plan');
    }
    if (isset($newItem->song_id)) {
        $msg = $newItem->song->title;
    } else {
        $msg = $newItem->comment;
    }
    flash('New Item added: ' . $msg);
    return $plan;
}
Exemplo n.º 30
0
 /**
  * Get Resource
  *
  * @param integer $id Resource ID
  *
  * @return App\Models\AppFile Resource instance
  */
 public function get($id)
 {
     $resource = Model::find($id);
     if (!$resource) {
         throw new Exception("Resource Not Found", 404);
     }
     return $resource;
 }