Zpracování uploadu souboru.
516716
public function handleUpload() {
		$files = $this->request->getFiles();
		$token = $this->request->getPost("token");
		$params = json_decode($this->request->getPost("params"), true);
		
		/** @var \Nette\Http\FileUpload $file */
		$file = $files[ $this->uploadControl->getHtmlName() ];
		/** @noinspection PhpInternalEntityUsedInspection */
		$model = $this->uploadControl->getUploadModel();
		$cache = $this->uploadControl->getCache();
		$filter = $this->getFilter();
		
		try {
			if(!is_null($filter) && !$filter->checkType($file)) {
				throw new \Zet\FileUpload\InvalidFileException($this->getFilter()->getAllowedTypes());
			}
			
			if($file->isOk()) {
				$returnData = $model->save($file, $params);
				/** @noinspection PhpInternalEntityUsedInspection */
				$cacheFiles = $cache->load($this->uploadControl->getTokenizedCacheName($token));
				if(empty($cacheFiles)) {
					$cacheFiles = [$this->request->getPost("id") => $returnData];
				} else {
					$cacheFiles[ $this->request->getPost("id") ] = $returnData;
				}
				/** @noinspection PhpInternalEntityUsedInspection */
				$cache->save($this->uploadControl->getTokenizedCacheName($token), $cacheFiles);
			}
			
		} catch(\Zet\FileUpload\InvalidFileException $e) {
			$this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([
				"id" => $this->request->getPost("id"),
				"error" => 100,
				"errorMessage" => $e->getMessage()
			]));
			
		} catch(\Exception $e) {
			$this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([
				"id" => $this->request->getPost("id"),
				"error" => 99,
				"errorMessage" => $e->getMessage()
			]));
		}
		
		$this->presenter->sendResponse(new \Nette\Application\Responses\JsonResponse([
			"id" => $this->request->getPost("id"),
			"error" => $file->getError()
		]));
	}
159245
protected function createComponentUrlForm() : Form
    {
        $form = new Form;

        $form->addText('url')
            ->setRequired('URL stránky je povinná.')
            ->addRule(Form::PATTERN, 'Povolené znaky pro URL: a-z, 0-9, lomítko, pomlčka.', PageRepository::URL_REGEX)
            ->addRule(Form::MIN_LENGTH, 'Minimální délka url je %d znaky.', 2)
            ->addRule(Form::MAX_LENGTH, 'Maximální délka url je %d znaků.', 255)
            ->addFilter(function ($value) {
                return $this->pageManager->webalizeUrl($value);
            });

        $form->addSubmit('save');

        $form->setDefaults([
            'url' => $this->activePage->getPageUrl()->getUrl()
        ]);


        $form->onValidate[] = function (Form $form) { $this->validate($form); };
        $form->onSuccess[] = function (Form $form) { $this->success($form); };


        if (!$this->presenter->user->isAllowed(PageAuthorizator::RES_URL_MODAL))
        {
            $this->setDisabledForm($form, TRUE);
        }

        return $form;
    }
1065278
protected static function _copyModuleBinaries() 
    {
        copy(BASE_PATH . '/vendor/mmi/mmi/src/Mmi/App/mmi', BASE_PATH . '/bin/mmi');
        //iteracja po binarkach
        foreach (new \DirectoryIterator(BASE_PATH . '/bin') as $file) { 
            //katalog (lub wyjście wyżej) 
            if ($file->isDot() || $file->isDir()) { 
                continue; 
            } 
            //zmiana uprawnień 
            chmod($file->getPathname(), 0755); 
        } 
    }
129777
public function filesAction()
    {
        //formularz
        $form = new Form\ConnectorImportFilesForm;
        //formularz zapisany
        if ($form->isSaved()) {
            //przekazanie listy plików do downloadu
            $this->view->files = $form->getOption('data');
            //otwarcie sesji
            $session = new \Mmi\Session\SessionSpace(\Cms\Model\ConnectorModel::SESSION_SPACE);
            $this->view->downloadUrl = base64_encode($session->url);
        } else {
            //form do widoku
            $this->view->form = $form;
        }
    }
54974
public function importFileMeta(array $files)
    {
        //iteracja po plikach (ta sama nazwa "name")
        foreach ($files as $importData) {
            //brak id
            if (!isset($importData['name']) || !isset($importData['id'])) {
                return;
            }
            //sprawdzanie istnienia pliku
            if (null === $file = (new \Cms\Orm\CmsFileQuery)->findPk($importData['id'])) {
                $file = new \Cms\Orm\CmsFileRecord;
            }
            //identyfikatory niezgodne
            if ($file->name && $file->name != $importData['name']) {
                continue;
            }
            //ustawienie danych rekordu rekordu
            $file->setFromArray($importData);
            //poprawny zapis
            if (!$file->save()) {
                return;
            }
        }
        //zwrot ostatniego pliku (potrzebny jest dowolny)
        return $file;
    }
530586
private static function _configureLogger()
    {
        //brak konfiguracji
        if (!self::$_config) {
            //tworzy pustą konfigurację
            return new \Psr\Log\NullLogger;
        }
        //nowy obiekt loggera
        $logger = new Logger(self::$_config->getName());
        //iteracja po konfiguracjach instancji
        foreach (self::$_config as $config) {
            self::_configureInstance($config, $logger);
        }
        return $logger;
    }
757616
public function describeAction()
    {
        //sprawdzamy, czy jest id pliku i form
        if (!$this->getPost()->cmsFileId || !is_array($this->getPost()->form)) {
            return $this->_jsonError(186);
        }
        //szukamy rekordu pliku
        if (null === $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) {
            return $this->_jsonError(186);
        }
        //pobranie danych
        $form = array_merge(['active' => 0, 'sticky' => null], $this->getPost()->form);
        foreach ($form as $field) {
            $form[$field['name']] = $field['value'];
            if ($field['name'] == 'active' || $field['name'] == 'sticky') {
                continue;
            }
            if ($field['name'] == 'original') {
                //dodajemy rozszerzenie
                //pozycja ostatniej kropki w nazwie - rozszerzenie pliku
                $pointPosition = strrpos($record->name, '.');
                if ($pointPosition !== false) {
                    $form['original'] .= substr($record->name, $pointPosition);
                }
                $record->data->original = $form['original'];
                continue;
            }
            $record->data->{$field['name']} = $field['value'];
        }
        //próba zapisu postera
        if (isset($form['poster']) && $form['poster']) {
            $form['posterFileName'] = $this->_savePoster($form['poster'], $record);
        }
        unset($form['poster']);
        if ($record->data instanceof \Mmi\DataObject) {
            //czyszczenie nieprzesłanych checkboxów
            foreach (array_keys($record->data->toArray()) as $name) {
                //nie czyścimy postera jeśli był wgrany
                if ($name == 'posterFileName') {
                    continue;
                }
                if (!isset($form[$name])) {
                    $record->data->{$name} = null;
                }
            }
        }
        $record->active = isset($form['active']) ? $form['active'] : $record->active;
        $record->sticky = isset($form['sticky']) ? $form['sticky'] : $record->sticky;
        $record->original = isset($form['original']) ? $form['original'] : $record->original;
        if ($record->sticky) {
            $result = $record->setSticky();
        } else {
            $result = $record->save();
        }
        if ($result) {
            //jeśli wykonać operację po edycji
            if ($this->getPost()->afterEdit) {
                $this->_operationAfter($this->getPost()->afterEdit, $record);
            }
            return json_encode(['result' => 'OK']);
        }
        return $this->_jsonError(186);
    }
279808
public function returnSubscribeCallback()
    {
        // Khởi tạo cấu hình Csp Config
        $cspConfig = $this->config[self::CSP_CONFIG];
        $this->debug->debug(__FUNCTION__, '$cspConfig: ' . json_encode($cspConfig));
        // Nhận tham số đầu vào
        $getRequestUri = $_SERVER['REQUEST_URI'];
        $getData       = explode('?link=', $getRequestUri);
        $this->debug->debug(__FUNCTION__, 'Request from IP: ' . json_encode($this->IP->getIpAddress()));
        $this->debug->debug(__FUNCTION__, '$getRequestUri: ' . json_encode($getRequestUri));
        $this->debug->debug(__FUNCTION__, '$getData: ' . json_encode($getData));
        $decrypt = $this->decrypt($getData); // Nghi ngờ đoạn này chưa đúng, theo logic phải là $getData[1];
        $this->debug->debug(__FUNCTION__, '$decrypt Data: ' . json_encode($decrypt));
        if (empty($decrypt)) {
            $result = [
                'status' => 1
            ];
        } else {
            $transactionCount = 1;
            $contentDecrypt   = explode("&", $decrypt);
            $this->debug->info(__FUNCTION__, '$decrypt Content Data: ' . json_encode($contentDecrypt));
            if (count($contentDecrypt) >= self::CSP_RETURN_MIN_PARAMS) {
                $this->debug->info(__FUNCTION__, 'Content Data >= ' . self::CSP_RETURN_MIN_PARAMS);
                $result = [
                    'status' => 0,
                    'data'   => [
                        'transactionCount' => $transactionCount,
                        'transactionId'    => trim($contentDecrypt[0]),
                        'msisdn'           => trim($contentDecrypt[1]),
                        'confirmStatus'    => trim($contentDecrypt[2]),
                        'resultCode'       => trim($contentDecrypt[3]),
                        'telcoId'          => 3,
                        'requestIp'        => $this->IP->getIpAddress()
                    ]
                ];
            } else {
                $this->debug->info(__FUNCTION__, 'Content Data < ' . self::CSP_RETURN_MIN_PARAMS);
                $result = [
                    'status' => 1,
                    'data'   => [
                        'transactionCount' => $transactionCount,
                        'transactionId'    => isset($contentDecrypt[0]) ? trim($contentDecrypt[0]) : '',
                        'msisdn'           => isset($contentDecrypt[1]) ? trim($contentDecrypt[1]) : '',
                        'confirmStatus'    => isset($contentDecrypt[2]) ? trim($contentDecrypt[2]) : '',
                        'resultCode'       => 0,
                        'telcoId'          => 3,
                        'requestIp'        => $this->IP->getIpAddress()
                    ]
                ];
            }
        }
        $this->debug->info(__FUNCTION__, 'Final Result: ' . json_encode($result));

        return $result;
    }
362004
public function pluploadAction()
    {
        set_time_limit(5 * 60);
        //obiekt handlera plupload
        $pluploadHandler = new Model\PluploadHandler();
        //jeśli wystąpił błąd
        if (!$pluploadHandler->handle()) {
            return $this->_jsonError($pluploadHandler->getErrorCode(), $pluploadHandler->getErrorMessage());
        }
        //jeśli wykonać operację po przesłaniu całego pliku i zapisaniu rekordu
        if ($this->getPost()->afterUpload && null !== $record = $pluploadHandler->getSavedCmsFileRecord()) {
            $this->_operationAfter($this->getPost()->afterUpload, $record);
        }
        return json_encode(['result' => 'OK', 'cmsFileId' => $pluploadHandler->getSavedCmsFileId()]);
    }
102318
public function indexAction()
    {
        $config = clone (\App\Registry::$config);
        //za długie dane do wyświetlenia
        $config->navigation = self::THREE_DOTS;
        $config->router = self::THREE_DOTS;
        $this->view->config = \Mmi\Http\ResponseDebugger\Colorify::colorify(print_r($config, true));
        $this->view->server = \Mmi\Http\ResponseDebugger\Colorify::colorify(print_r($_SERVER, true));
    }
130065
public function importFileAction()
    {
        //text/plain
        $this->getResponse()->setTypePlain();
        //adres endpointu
        $endpoint = base64_decode($this->url) . '/?module=cms&controller=connector&name=' . $this->name . '&action=';
        try {
            //wczytanie danych
            $data = json_decode(file_get_contents($endpoint . 'exportFileMeta'), true);
        } catch (\Exception $e) {
            //zwrot pustego statusu
            return 'ERR';
        }
        //próba importu meta-danych
        if (null === $file = (new Model\ConnectorModel)->importFileMeta($data)) {
            //plik istnieje, lub próba nie udana
            return 'META ERROR';
        }
        try {
            mkdir(dirname($file->getRealPath()), 0777, true);
        } catch (\Exception $e) {
            //nic
        }
        try {
            //próba pobrania i zapisu binarium
            file_put_contents($file->getRealPath(), file_get_contents($endpoint . 'exportFileBinary'));
        } catch (\Exception $e) {
            die($e->getMessage());
            //zwrot pustego statusu
            return 'BIN ERROR';
        }
        return 'OK';
    }
1352744
function main (params) {
  return new Promise((resolve, reject) => {
    var debug = typeof params.debug === 'boolean' ? params.debug : false

    if (typeof params !== 'object') {
      if (debug) console.log('Format ze starej wersji.')
      /** @throws Dane powinny być podane w formie obiektu, a nie są. */
      reject(new Error('Nieprawidłowy format danych.'))
      return
    }
    if (
      (typeof params.username === 'string' &&
        (params.username !== '' && params.username !== ' ')
      ) &&
      (
        (typeof params.password === 'string' &&
          (params.password !== '' && params.password !== ' ')
        ) ||
        (typeof params.hash === 'string' &&
          (params.hash !== '' && params.hash !== ' ')
        )
      )
    ) {
      if (debug) console.log('Loguję...')
      login(params).then(o => {
        resolve(new Client(params.username, o.agent, o.id, o.hash))
      }).catch(e => {
        reject(e)
      })
    } else {
      reject(new Error('Nieprawidłowy format danych.'))
    }
  })
}
501456
public function deleteAction()
    {
        //szukamy rekordu pliku
        if (!$this->getPost()->cmsFileId || null === $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) {
            return $this->_jsonError(178);
        }
        //sprawdzenie zgodności z obiektem formularza
        if ($record->object === $this->getPost()->object && $record->objectId == $this->getPost()->objectId) {
            //usuwanie
            if ($record->delete()) {
                //jeśli wykonać operację po usunięciu
                if ($this->getPost()->afterDelete) {
                    $this->_operationAfter($this->getPost()->afterDelete, $record);
                }
                return json_encode(['result' => 'OK']);
            }
        }
        return $this->_jsonError(178);
    }
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();
        }
    }
837815
public function detailsAction()
    {
        if (!$this->getPost()->cmsFileId) {
            return $this->_jsonError(185);
        }
        //szukamy rekordu pliku
        if (null == $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) {
            return $this->_jsonError(185);
        }
        //wycinamy rozszerzenie z nazwy oryginalnego pliku do edycji
        //pozycja ostatniej kropki w nazwie
        $pointPosition = strrpos($record->original, '.');
        if ($pointPosition !== false) {
            $record->original = substr($record->original, 0, $pointPosition);
        }
        $data = [];
        if ($record->data instanceof \Mmi\DataObject) {
            //parametry
            $data = $record->data->toArray();
        }
        $data['urlFile'] = ((\App\Registry::$config->cdn) ? : $record->getUrl());
        if ($record->data->posterFileName) {
            $data['poster'] = $record->getPosterUrl();
        }    
        return json_encode(['result' => 'OK', 'record' => $record, 'data' => $data]);
    }
647017
protected static function _updateRecordFromRequestFile(\Mmi\Http\RequestFile $file, \Cms\Orm\CmsFileRecord $record)
    {
        //typ zasobu
        $record->mimeType = $file->type;
        //klasa zasobu
        $class = explode('/', $file->type);
        $record->class = $class[0];
        //oryginalna nazwa pliku
        $record->original = $file->name;
        //rozmiar pliku
        $record->size = $file->size;
        //daty dodania i modyfikacji
        if (!$record->dateAdd) {
            $record->dateAdd = date('Y-m-d H:i:s');
        }
        if (!$record->dateModify) {
            $record->dateModify = date('Y-m-d H:i:s');
        }
        //właściciel pliku
        $record->cmsAuthId = \App\Registry::$auth ? \App\Registry::$auth->getId() : null;
        if ($record->active === null) {
            //domyślnie aktywny
            $record->active = 1;
        }
        return $record;
    }
1261953
public static function inputToResource($input)
    {
        //jeśli resource zwrot
        if (gettype($input) == 'resource') {
            return $input;
        }
        //jeśli krótki content zakłada że to ścieżka pliku
        return imagecreatefromstring((strlen($input) < self::BINARY_MIN_LENGTH) ? file_get_contents($input) : $input);
    }