Upload files, create thumbs and save it to db
TODO chunk in multi-functions

@param  Request $request
@param  string  $belongsToApp
@return array
@throws \Exception
6755
public function upload($request, $belongsToApp = '')
    {
        $results = array();
        $carbon = new Carbon();

        $destinationBasePath = uploadsPath(); // upload basic path
        $year = $carbon->year;
        $month = str_pad($carbon->month, 2, '0', STR_PAD_LEFT);
        $day = str_pad($carbon->day, 2, '0', STR_PAD_LEFT);

        $datePath = $year."/".$month.'/'.$day;
        $destinationPath = uploadsPath($datePath);
        $fileDirectory = 'public'.explode('public', $destinationPath)[1];
        $fileDirectory = str_replace('\\', '/', $fileDirectory);

        $destinationOriginalDirectory = $destinationPath."/original";

        foreach ($request->all() as $key => $value){
            // continue when we are looping throw post type
            if ($key == "postTypes" || $key == "albumID" || $key == "fromAlbum") {
                continue;
            }

            // uploaded file
            $file = $request->file($key);
            $extension = strtolower($file->getClientOriginalExtension()); // getting image extension
            $fileNameWithoutExtension = str_slug(basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension()), '-');
            $fileName = $fileNameWithoutExtension.'.'.$extension;
            $fileSizeOriginal = $file->getClientSize();
            $fileSize = round($fileSizeOriginal/1048576*1024);

            // change filename if filename already exists
            if(file_exists($destinationOriginalDirectory.'/'.$fileName)) {
                $exists = true;
                while($exists === true){
                    $random = str_random(5);
                    $fileName = $fileNameWithoutExtension.'-'.$random.'.'.$extension;
                    if(!file_exists($destinationOriginalDirectory.'/'.$fileName)) {
                        $exists = false;
                        break;
                    }
                }
            }

            $destinationOriginalPath = $destinationOriginalDirectory.'/'.$fileName;

            // validate file type
            if(!$this->isAllowedExtension($extension)) {
                throw new FileException("File type not allowed");
            }

            //validate size
            if($fileSize > config('filesystems.upload_max_filesize')) {
                throw new FileException('File is to large. Max filesize is '. config('filesystems.upload_max_filesize') .'kb');
            }

            //check if $destinationBasePath is writable
            if(!File::isWritable($destinationBasePath)) {
                throw new FileException('The directory  "'.$destinationBasePath.'" is not writable. Please contact your administrator');
            }

            //crate original original size path if it doesn't excist
            if (!File::exists($destinationOriginalDirectory)) {
                if(!File::makeDirectory($destinationOriginalDirectory, 0755, true)) {
                    throw new FileException('The directory  "'.$destinationOriginalDirectory.'" could not be created. Please contact your administrator');
                }
            }

            //check if $destinationPath is writable
            if(!File::isWritable($destinationPath)) {
                throw new FileException('The directory  "'.$destinationPath.'" is not writable. Please contact your administrator');
            }

            //check if $destinationOriginalDirectory is writable
            if(!File::isWritable($destinationOriginalDirectory)) {
                throw new FileException('The directory  "'.$destinationOriginalDirectory.'" is not writable. Please contact your administrator');
            }

            // if file is successfully uploaded
            if($file->move($destinationOriginalDirectory, $fileName)) {
                // set params to the media object
                $media = new Media();
                $media->title = $fileNameWithoutExtension;
                $media->description = '';
                $media->extension = $extension;
                $media->url = $fileDirectory.'/original/'.$fileName;
                $media->filename = $fileName;
                $media->fileDirectory = $fileDirectory;
                $media->filesize = round(($fileSize/1000), 2);
                $media->createdByUserID = Auth::user()->userID;

                if($this->hasImageExtension($extension)) {
                    $media->type = "image";
                    // if the uploaded file is a image set his dimensions in the database
                    $img = Image::make($destinationOriginalPath);
                    $width = $img->width();
                    $height = $img->height();
                    $media->dimensions = $width."x".$height;

                }else if($this->hasDocumentExtension($extension)) {
                    $media->type = "document";
                }elseif($this->hasAudioExtension($extension)) {
                    $media->type = "audio";
                }elseif($this->hasVideoExtension($extension)) {
                    $media->type = "video";
                }else{
                    throw new FileException("Extension type not allowed");
                }

                // Fire event
                Event::fire('media:creating', [$media, $request]);

                if($media->save()) {
                    // optimize original image
                    if(config('media.optimize_original_image')) {
                        $this->optimize($destinationOriginalDirectory . '/' . $fileName);
                    }

                    // Create thumbs
                    $this->createDefaultThumbs($media, $belongsToApp);

                    // Fire event
                    Event::fire('media:created', [$media, $request]);

                    $msg = 'File is successfully uploaded';
                    array_push($results, ['result_code' => 'ok','filename'=> $fileName, 'extension' => $extension, 'msg' => $msg, 'url' => $destinationOriginalPath]);
                }else{
                    unlink($destinationOriginalDirectory, $fileName);
                    $err = 'File could not be saved. Please try again later or contact your administrator';
                    array_push($results, ['result_code' => 'failed','filename'=> $fileName, 'extension' => $extension, 'msg' => $err, 'url' => '']);
                }
            }else{
                $err = 'File could not be uploaded. Please try again later or contact your administrator';
                array_push($results, ['result_code' => 'failed','filename'=> $fileName, 'extension' => $extension, 'msg' => $err, 'url' => '']);
            }

        }
        return $results;
    }
648555
public function uploadAction(Request $request)
    {
        $files = $this->uploadFiles($request);
        $data = [];

        foreach ($files as $file) {
            $data[] = $this->serializer->serialize($file);
        }

        return new JsonResponse($data, 200);
    }
907640
public function upload(ThumbnailRequest $request)
    {
        $crudeName = $request->input('crudeName');
        $crude = CrudeInstance::get($crudeName);
        $column = $request->input('columnName');
        $file = $request->file()['file'];

        $id = $request->input('modelId');
        $model = $crude->uploadThumbnailByIdAndColumn($id, $column, $file);

        return ['success' => true, 'model' => $model];
    }
321670
public function belongsToMany(
        $entity,
        string $related,
        string $table = null,
        string $foreignKey = null,
        string $otherKey = null
    ): BelongsToMany {
        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addManyRelation($relation);
        $this->addForeignRelation($relation);
        $this->addPivotRelation($relation);

        // First, we'll need to determine the foreign key and "other key" for the
        // relationship. Once we have determined the keys we'll make the query
        // instances as well as the relationship instances we need for this.
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $relatedMap = $relatedMapper->getEntityMap();

        $otherKey = $otherKey ?: $relatedMap->getForeignKey();

        // If no table name was provided, we can guess it by concatenating the two
        // models using underscores in alphabetical order. The two model names
        // are transformed to snake case from their default CamelCase also.
        if (is_null($table)) {
            $table = $this->joiningTable($relatedMap);
        }

        return new BelongsToMany($relatedMapper, $entity, $table, $foreignKey, $otherKey, $relation);
    }
636244
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
    {
        $args = func_get_args();
        $args['type'] = 'belongsTo';
        return $this->setRelationship(json_encode($args));
    }
72888
public function saveTableToSession(Request $request, TableModel $table)
    {
        $request->getSession()->set(TableModel::buildSessionPath($request), serialize($table));
    }
1135358
public function permissions() : BelongsToMany
    {
        $pivotTable = config('lia.database.user_permissions_table');

        $relatedModel = config('lia.database.permissions_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'user_id', 'permission_id');
    }
142230
public function update($request) {
        $this->resolveModel();
        $model = Dir::apiModel($this->model);
        $modelFind = $model::find($request->id);

        if(!empty($request->relationalModel)) {
            $idRelationalModel = trim(strtolower($request->relationalModel), 's');
            $idRelationalModel =  $idRelationalModel.'Id';
            if($modelFind->$idRelationalModel != $request->idRelational) killer('400');
        }

        foreach($modelFind->getTuples() as $tuple)
            if(!empty($request->$tuple))
                $modelFind->$tuple = $request->$tuple;

        $modelFind->update();
        return $modelFind;
    }
1149187
public function insert (Request $request)
    {
        if ($this->category->categoryExist($request->input('title') , $request->input('model_type')))
            throw new CategoryException(trans('Categories::category.error-message.categoryExist'));

        $category = $this->category->newInstance($request->except('_token'));
        $slug = new Slugger($this->modelType);
        $category->slug = $slug->storeSlug($request->input('slug') , $request->input('title'));
        $category->model_type = $this->modelType;
        $category->save();

        return $category;

    }
857449
public function belongsTo($sPrimaryKeyName, $sEntityJoinName, $sForeignKeyName, $sNamespaceEntity, array $aOptions = array())
	{
	    $this->_aHasOne[$sEntityJoinName] = array($sPrimaryKeyName, $sEntityJoinName, $sForeignKeyName, $sNamespaceEntity);
	}
1058293
public function uploadAction(Request $request)
    {
        $media = $this->get('opifer.media.media_manager')->createMedia();
        $em = $this->getDoctrine()->getManager();

        foreach ($request->files->all() as $files) {
            if ((!is_array($files)) && (!$files instanceof \Traversable)) {
                $files = [$files];
            }

            foreach ($files as $file) {
                $media = clone $media;
                $media->setFile($file);

                if (strpos($file->getClientMimeType(), 'image') !== false) {
                    $media->setProvider('image');
                } else {
                    $media->setProvider('file');
                }

                $em->persist($media);
            }
        }
        $em->flush();

        $media = $this->get('jms_serializer')->serialize($media, 'json');

        return new Response($media, 200, ['Content-Type' => 'application/json']);
    }
183478
public function attachFile($id, $table, \Symfony\Component\HttpFoundation\File\UploadedFile $file)
    {
        $newFileName = md5(microtime() . '.' . strtolower($file->getClientOriginalExtension()));
        $relativePath = $table . '/' . date('Y/m/d');
        $relativeFilePath = $relativePath . '/' . $newFileName;
        $dstPath = APP_UPLOADS_DIR . '/' . $relativePath;
        $file->move($dstPath, $newFileName);
        $pic = new \Towel\Model\Pic();

        $pic->object_id = $id;
        $pic->object_type = $table;
        $pic->pic = $relativeFilePath;
        $pic->created = time();
        $pic->save();
    }
315391
public function saveAction(Request $request)
    {
        $objectType = $request->get('objectType');
        $objectId = $request->get('objectId');
        $data = $request->get('identities');

        if (!$data) {
            throw new InvalidArgumentException('No save data.');
        }

        $identities = json_decode($data, true);

        $objectIdentityResolver = $this->get('phlexible_access_control.object_identity_resolver');
        $objectIdentity = $objectIdentityResolver->resolve($objectType, $objectId);

        $accessManager = $this->get('phlexible_access_control.access_manager');
        $acl = $accessManager->findAcl($objectIdentity);

        if (!$acl) {
            $acl = $accessManager->createAcl($objectIdentity);
        }

        foreach ($acl->getEntries() as $ace) {
            $acl->removeEntry($ace);
        }
        foreach ($identities as $objectIdentity) {
            if ($objectIdentity['mask'] === null && $objectIdentity['stopMask'] === null && $objectIdentity['noInheritMask'] === null) {
                continue;
            }

            $ace = new Entry(
                $acl,
                $objectIdentity['objectType'],
                $objectIdentity['objectId'],
                $objectIdentity['securityType'],
                $objectIdentity['securityId'],
                $objectIdentity['mask'],
                $objectIdentity['stopMask'],
                $objectIdentity['noInheritMask']
            );

            $acl->addEntry($ace);
        }

        $accessManager->updateAcl($acl);

        return new ResultResponse(true, 'Rights saved.');
    }
334626
function belongsToArea(suggestion, instance){
    var parentSuggestion = instance.selection,
        result = parentSuggestion && parentSuggestion.data && instance.bounds;

    if (result) {
        collection_util.each(instance.bounds.all, function (bound, i) {
            return (result = parentSuggestion.data[bound] === suggestion.data[bound]);
        });
    }
    return result;
}
50516
public function deleteApp(Request $request, ApiApplication $application)
    {
        $this->assertJsonRequestFormat($request);

        $this->getApiApplicationManipulator()->delete($application);

        return $this->app->json(['success' => true]);
    }
640411
protected function buildBelongsToInfo($key, BelongsTo $relation)
    {
        $other = $relation->getRelated();
        return [
            'type'         => 'object|class:'.get_class($other),
            'foreign_keys' => [$this->getForeignKey($relation)]
        ];
    }
116242
public function upload(Request $request)
    {
        $attachment = [];
        foreach ($request->allFiles() as $files) {
            $files = Arr::wrap($files);

            foreach ($files as $file) {
                $attachment[] = $this->createModel($file, $request);
            }
        }

        $attachment = count($attachment) > 1 ? $attachment : reset($attachment);

        return response()->json($attachment);
    }