Obsługa pojedynczego uploadu
@param array $fileData dane pliku
@return \Mmi\Http\RequestFile
184224
protected function _handleSingleUpload(array $fileData)
    {
        //wstepne sprawdzenie czy plik istnieje, czy tablica nie jest pusta
        if(!isset($fileData['name']) || !isset($fileData['tmp_name'])){
            return;
        }

        //przypadek gdy file data to prosta tablica klucz => wartość bez zagnieżdżeń
        // $fileData = ['name' => 'nazwa_pliku.jpg']
        if(is_string($fileData['name'])){
            //czy plik istnieje
            if($fileData['tmp_name'] == ''){
                return;
            }
            $fieldName = $fileData['name'];
        }

        //przypadek trochę bardziej skomplikowany gdzie sa zagnieżdżenia:
        // $fileData['name'] = ['cmsAttribute' => 'nazwa_pliku.png']
        if(is_array($fileData['name'])){
            //sprawdzamy czy nie ejst to kilka plików
            if(count(reset($fileData['name'])) > 1){
                return;
            }
            //czy plik istnieje
            if(is_array(reset($fileData['name'])) || reset($fileData['tmp_name']) == ''){
                return;
            }

            $fieldName = key($fileData['name']);

            foreach ($fileData as $key => $value) {
                $fileData[$key] = current($value);
            }
        }

        $file = new RequestFiles();
        $file->{$fieldName} = new RequestFile($fileData);

        return  $file;
    }
1266414
public function setup(\Mmi\Http\Request $request)
    {
        //aktywuje liście drzewa
        $activatedTree = $this->_setupActive($this->_config->build, $request->toArray());
        //uzupełnia breadcrumbs na podstawie aktywnych
        if (isset($activatedTree['tree'][0]['children'])) {
            //ustawia breadcrumby
            $this->_setupBreadcrumbs($activatedTree['tree'][0]['children']);
        }
        return $this;
    }
634587
public function create(array $entityData)
    {
        $this->preCreate($entityData);
        $entity = $this->doCreate($entityData);
        $this->getEntityManager()->persist($entity);
        $this->getEntityManager()->flush($entity);
        $this->postCreate($entity);
        $this->getEntityManager()->flush($entity);

        return $entity;
    }
1330714
protected function _retrievePostOrder(\Mmi\Http\RequestPost $post)
    {
        //brak zmian sortowania dla tego grida
        if (false === strpos($post->order, $this->_grid->getClass())) {
            return;
        }
        //obsługa joinowanych
        $fieldName = substr($post->order, strpos($post->order, '[') + 1, -1);
        $tableName = null;
        if (strpos($fieldName, '.')) {
            $fieldTable = explode('.', $fieldName);
            $tableName = $fieldTable[0];
            $fieldName = $fieldTable[1];
        }
        //nowy obiekt sortowania
        $gso = (new GridStateOrder())
            ->setField($fieldName)
            ->setTableName($tableName);
        //kalkulacja metody sortowania
        switch ($post->method) {
            //poprzednia metoda to DESC - usuwanie sortowania
            case 'orderDesc':
                return $gso->unsetMethod();
            //poprzednia metoda to ASC - zmiana na DESC
            case 'orderAsc':
                return $gso->setMethod('orderDesc');
        }
        //nowe sortowanie - ASC
        return $gso->setMethod('orderAsc');
    }
96230
public function uploaderAction()
    {
        //parametry dla ajaxa
        $this->view->ajaxParams = [
            'module' => 'cms',
            'controller' => 'file',
            'action' => 'upload',
            'class' => $this->class,
            'object' => $this->object,
            'objectId' => $this->objectId,
            'types' => $this->types,
            'js' => $this->js,
            //znacznik czasu
            't' => $t = round(microtime(true)),
            //hash zabezpieczający oparty o znacznik czasu
            'hash' => md5($t . '+' . \Mmi\Session\Session::getId() . '+' . $this->class)
        ];
        //blad
        $this->view->error = $this->error;
        //lista obrazów
        $this->view->images = \Cms\Orm\CmsFileQuery::imagesByObject($this->object, $this->objectId)
            ->orderAscDateAdd()
            ->find();
        //lista pozostałych plików
        $this->view->files = \Cms\Orm\CmsFileQuery::notImagesByObject($this->object, $this->objectId)
            ->orderAscDateAdd()
            ->find();
    }
187710
public function add(array $data = []) : Request
  {
    $this->data = array_merge($this->data, $data);

    $files = array_filter($data, function($file) {
      if (isset($file['type']) && isset($file['name']) && isset($file['size'])) return $file;
    });

    $this->files = array_merge($this->files, $files);
    return $this;
  }
8647
public function upload(FileRequest $request)
    {
        $crudeName = $request->input('crudeName');
        $crude = CrudeInstance::get($crudeName);
        $files = $request->file()['file'];
        $id = $request->input('modelId');
        $errors = [];

        if ($crude instanceof \JanDolata\CrudeCRUD\Engine\Interfaces\WithValidationInterface) {
            foreach($files as $key => $file) {
                $rules = $crude->getValidationRules(['file']);

                $mime = $file->getMimeType();
                $fileTypeRules = 'file_'.collect(explode('/', $mime))->first();

                empty($crude->getValidationRules([$fileTypeRules])[$fileTypeRules])
                    ? $rules = $rules
                    : $rules['file'] = $rules['file'] . '|' . $crude->getValidationRules([$fileTypeRules])[$fileTypeRules];

                $validator = Validator::make(['file' => $file], $rules);

                if ($validator->fails()) {
                    unset($files[$key]);
                    $errors[] = $file->getClientOriginalName() . ': '. $validator->messages()->first();
                }
            }
        }

        $model = empty($files)
            ? $crude->getById($id)
            : $crude->uploadFilesById($id, $files);

        $response = ['success' => true, 'model' => $model];

        if (!empty($errors)) {
            $response = array_merge($response, ['errors' => join('<br/>', $errors)]);
            $response['success'] = false;
        }

        return $response;
    }
1314591
public function deploy()
    {
        //wyłączenie bufora lokalnego
        \App\Registry::$config->localCache->active = false;
        //wyłączenie bufora aplikacji
        \App\Registry::$config->cache->active = false;
        //inicjalizacja tablicy inkrementali
        $incrementals = [];
        //iteracja po modułach aplikacji
        foreach (\Mmi\Mvc\StructureParser::getModules() as $module) {
            //moduł nie zawiera incrementali
            if (!file_exists($module . '/Resource/incremental/' . \App\Registry::$config->db->driver)) {
                continue;
            }
            //iteracja po incrementalach
            foreach (glob($module . '/Resource/incremental/' . \App\Registry::$config->db->driver . '/*.sql') as $file) {
                //dodawanie incrementala do tablicy
                $incrementals[basename($file)] = $file;
            }
        }
        //sortowanie plików po nazwach
        ksort($incrementals);
        //przywracanie incrementali
        foreach ($incrementals as $incremental) {
            //importowanie incrementala
            $this->_importIncremental($incremental);
            //flush wyniku na ekran
            flush();
        }
    }
750991
protected function _appendFiles($id, $files)
    {
        try {
            foreach ($files as $fileSet) {
                \Cms\Model\File::appendFiles($this->_fileObjectName, $id, $fileSet);
            }
            //rekord edytowany - nie łączymy uploaderów z tymczasowym uploadem
            if ($this->getOption(self::EDITING_RECORD_OPTION_KEY)) {
                return;
            }
            //przenoszenie z uploadera
            \Cms\Model\File::move('tmp-' . $this->_fileObjectName, \Mmi\Session\Session::getNumericId(), $this->_fileObjectName, $id);
        } catch (\Exception $e) {
            \Mmi\App\FrontController::getInstance()->getLogger()->warning($e->getMessage());
        }
    }
138286
public function editAction()
    {
        $this->getResponse()->setTypeJson();
        $error = json_encode(['error' => 'Edycja nie powiodła się, brak pliku']);
        //brak id
        if (!$this->id) {
            return $error;
        }
        //brak pliku
        if (null === ($file = (new CmsFileQuery)->findPk($this->id))) {
            return $error;
        }
        //błędny plik
        if ($this->hash != $file->getHashName()) {
            return $error;
        }
        //zapis
        $postData = $this->getPost()->toArray();
        if (!empty($postData)) {
            $file->setFromArray($postData)
                ->save();
        }
        //json na potrzeby wyświetlenia formularza
        return $file->toJson();
    }
656352
protected function _savePoster($blob, \Cms\Orm\CmsFileRecord $file)
    {
        //brak danych
        if (!\preg_match('/^data:(image\/[a-z]+);base64,(.*)/i', $blob, $match)) {
            return;
        }
        //nazwa postera
        $posterFileName = substr($file->name, 0, strpos($file->name, '.')) . '-' . $file->id . '.' . \Mmi\Http\ResponseTypes::getExtensionByType($match[1]);
        //próba utworzenia katalogu
        try {
            //tworzenie katalogu
            mkdir(dirname($file->getRealPath()), 0777, true);
        } catch (\Exception $e) {
            //nic
        }
        //zapis
        file_put_contents(str_replace($file->name, $posterFileName, $file->getRealPath()), base64_decode($match[2]));
        //zapis do rekordu
        $file->data->posterFileName = $posterFileName;
        return $posterFileName;
    }
171942
public static function appendFiles($object, $id = null, array $files = [], array $allowedTypes = [])
    {
        //pola formularza
        foreach ($files as $fileSet) {
            //pojedynczy upload
            if ($fileSet instanceof \Mmi\Http\RequestFile) {
                if (null === self::appendFile($fileSet, $object, $id, $allowedTypes)) {
                    return false;
                }
                continue;
            }
            //pliki w polu formularza
            foreach ($fileSet as $file) {
                /* @var $file \Mmi\Http\RequestFile */
                if (null === self::appendFile($file, $object, $id, $allowedTypes)) {
                    return false;
                }
            }
        }
        return true;
    }
260489
protected static function _copyDistFiles() 
    { 
        //iteracja po wymaganych plikach 
        foreach (self::$_distFiles as $src => $dest) { 
            //kalkulacja ścieżki 
            $source = BASE_PATH . $src; 
            //brak pliku 
            if (!file_exists($source)) { 
                continue; 
            } 
            //kopiowanie katalogów 
            \Mmi\FileSystem::copyRecursive($source, BASE_PATH . $dest, false); 
            //usuwanie źródła 
            \Mmi\FileSystem::rmdirRecursive($source); 
            //usuwanie placeholderów 
            \Mmi\FileSystem::unlinkRecursive('.placeholder', BASE_PATH . $dest); 
        } 
    }
932732
private function _saveFile()
    {
        $requestFile = $this->_getRequestFile();
        //jeśli niedopuszczalny plik
        if (!$this->_filterFile($requestFile)) {
            //usuwamy plik z katalogu plupload
            @unlink($this->_filePath);
            $this->_setError(PLUPLOAD_TYPE_ERR, "Niedopuszczalny typ pliku");
            return false;
        }
        //jeśli przesłano plik dla konkretnego id w bazie
        if ($this->_cmsFileId) {
            if (null !== $this->_cmsFileRecord = (new \Cms\Orm\CmsFileQuery)->findPk($this->_cmsFileId)) {
                return $this->_replaceFile($requestFile);
            }
        }
        //nie było pliku - tworzymy nowy
        return $this->_createNewFile($requestFile);
    }
189538
protected function sendRequest(array $requestData): TransferInterface
    {
        $response = $this->adapter->sendRequest($requestData);

        return $this->converter->toTransactionResponseTransfer($response);
    }
531871
public function uploadAction ()
    {
        $handle = $this->getRequest()->files->get('file');
        
        if ($handle && $handle->getError()){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $this->container->get('translator')
                    ->trans('file_upload_http_error', array(), 'ThraceMediaBundle')
            ));
        }

        $imageManager = $this->container->get('thrace_media.imagemanager');
        $options = $this->container->getParameter('thrace_media.plupload.options');
        $extension = $handle->getClientOriginalExtension();
        $name = uniqid() . '.' . $extension;
        
        if(!$extension){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => sprintf('Unknown Mime Type: "%s"', $handle->getMimeType())
            ));
        }

        $validate = $this->validateImage($handle);

        if ($validate !== true) {
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $validate
            ));
        }

        $content = $imageManager->normalizeImage(
            $name, file_get_contents($handle->getRealPath()), 
            $options['normalize_width'], $options['normalize_height']
        );
        
        $imageManager->saveToTemporaryDirectory($name, $content);
        $imageManager->makeImageCopyToOriginalDirectory($name);
        $hash = $imageManager->checksumTemporaryFileByName($name);

        return new JsonResponse(array(
            'success' => true,
            'name'    => $name,
            'hash'    => $hash
        ));
    }
419917
private function _createNewFile(\Mmi\Http\RequestFile $requestFile)
    {
        if (null === $this->_cmsFileRecord = \Cms\Model\File::appendFile($requestFile, $this->_formObject, $this->_formObjectId)) {
            $this->_setError(PLUPLOAD_MOVE_ERR, "Błąd tworzenia nowego rekordu pliku");
            $result = false;
        } else {
            $result = $this->_cmsFileRecord->save();
        }
        //usuwamy plik z katalogu plupload
        @unlink($this->_filePath);
        return $result;
    }