FileController ------------------------
496503
public function actionAll( $config = [] ) {

		// Remember return url for crud
		Url::remember( Yii::$app->request->getUrl(), 'files' );

		$dataProvider = $this->modelService->getSharedPage();

		return $this->render( 'all', [
			'dataProvider' => $dataProvider,
			'visibilityMap' => File::$visibilityMap,
			'typeMap' => File::$typeMap
		]);
	}
1282403
public function run() {
        $uploadedFile = UploadedFile::getInstanceByName($this->inputName);
        $params = Yii::$app->request->getBodyParams();
        $filePath = $this->getUnusedPath($this->tempPath . DIRECTORY_SEPARATOR . $uploadedFile->name);

        $isUploadComplete = ChunkUploader::process($uploadedFile, $filePath);

        if ($isUploadComplete) {
            $fileHash = md5(microtime(true) . $filePath);
            $fileType = isset($params['name']) ? strtolower(substr(stristr($params['name'], '.'), 1)) : strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
            $newFileName = "{$fileHash}.{$fileType}";

            $entityClass = $this->entityClass;
            $entityModel = $entityClass::findOne(['id' => $params['entity_id']]);
            if (is_null($entityModel)) {
                throw new \yii\base\Exception("entity model(id:{$params['entity_id']}) not found!");
            }

            $fileDirPath = $this->_organizer->getFullUploadStoreDir($fileHash, $entityModel);
            $newFilePath = $fileDirPath . DIRECTORY_SEPARATOR . $newFileName;

            if (!copy($filePath, $newFilePath)) {
                throw new Exception("Cannot copy file! {$filePath}  to {$newFilePath}");
            }
            $attachementClass = $this->attachementClass;
            $attachement = new $attachementClass;
            $attachement->loadDefaultValues();
            $attachement->setAttributes([
//                'name' => pathinfo($filePath, PATHINFO_FILENAME),
//                'type' => $attachement->type,
                'name' => $params['name'],
                'entity_id' => $entityModel->id,
                'entity_class' => $this->entityClass,
                'entity_attribute' => $this->entityAttribute,
                'hash' => $fileHash,
                'size' => filesize($filePath),
                'content' => isset($extras['content']) ? $extras['content'] : "",
                'extension' => $fileType,
                'mime_type' => FileHelper::getMimeType($filePath),
                'logic_path' => $this->_organizer->getUploadLogicPath($fileHash, $entityModel),
            ]);

            if ($attachement->save()) {
                @\unlink($filePath);
            }

            if ($this->onComplete) {
                return call_user_func($this->onComplete, $filePath, $params);
            } else {
                return [
                    'filename' => $filePath,
                    'params' => $params,
                ];
            }
        }

        return null;
    }
567414
public function fileManager()
    {
        $files = [
            base_path('config/auth.php'),
            base_path('config/services.php'),
        ];

        foreach ($files as $file) {
            $contents = file_get_contents($file);
            $contents = str_replace('App\User::class', 'App\Models\User::class', $contents);
            file_put_contents($file, $contents);
        }

        // Route setup
        $routeContents = file_get_contents(app_path('Providers/RouteServiceProvider.php'));
        $routeContents = str_replace("->group(base_path('routes/web.php'));", "->group(function() { \n\t\t\trequire base_path('routes/web.php');\n\t\t\trequire base_path('routes/cms.php'); });", $routeContents);
        file_put_contents(app_path('Providers/RouteServiceProvider.php'), $routeContents);

        $routeToDashboardContents = file_get_contents(base_path('routes/web.php'));
        $routeToDashboardContents = str_replace("Route::get('/dashboard', 'PagesController@dashboard');", "Route::get('/dashboard', function(){ return Redirect::to('cms/dashboard'); });", $routeToDashboardContents);
        file_put_contents(base_path('routes/web.php'), $routeToDashboardContents);

        // Kernel setup
        $routeContents = file_get_contents(app_path('Http/Kernel.php'));
        $routeContents = str_replace("'auth' => \App\Http\Middleware\Authenticate::class,", "'auth' => \App\Http\Middleware\Authenticate::class,\n\t\t'cms' => \App\Http\Middleware\GrafiteCms::class,\n\t\t'cms-api' => \App\Http\Middleware\GrafiteCmsApi::class,\n\t\t'cms-analytics' => \Grafite\Cms\Middleware\GrafiteCmsAnalytics::class,\n\t\t'cms-language' => \App\Http\Middleware\GrafiteCmsLanguage::class,\n\t\t'admin' => \App\Http\Middleware\Admin::class,\n\t\t'active' => \App\Http\Middleware\Active::class,", $routeContents);
        file_put_contents(app_path('Http/Kernel.php'), $routeContents);

        $fileSystem = new Filesystem();

        $files = $fileSystem->allFiles(__DIR__.'/../PublishedAssets/Setup');

        foreach ($files as $file) {
            $newFileName = str_replace(__DIR__.'/../PublishedAssets/Setup', '', $file);
            if (is_dir($file)) {
                $fileSystem->copyDirectory($file, base_path($newFileName));
            } else {
                @mkdir(base_path(str_replace(basename($newFileName), '', $newFileName)), 0755, true);
                $fileSystem->copy($file, base_path($newFileName));
            }
        }

        // AuthProviders
        $authProviderContents = file_get_contents(app_path('Providers/AuthServiceProvider.php'));
        $authProviderContents = str_replace('$this->registerPolicies();', "\$this->registerPolicies();\n\t\t\Gate::define('cms', function (\$user) {\n\t\t\treturn (\$user->roles->first()->name === 'admin');\n\t\t});\n\t\t\Gate::define('admin', function (\$user) {\n\t\t\treturn (\$user->roles->first()->name === 'admin');\n\t\t});", $authProviderContents);
        file_put_contents(app_path('Providers/AuthServiceProvider.php'), $authProviderContents);

        // Remove the teams
        $this->dropDeadFiles();

        /*
         * --------------------------------------------------------------------------
         * Drop the team routes and the active middleware
         * --------------------------------------------------------------------------
        */

        $mainRoutes = file_get_contents(base_path('routes/web.php'));
        $mainRoutes = str_replace("/*
    |--------------------------------------------------------------------------
    | Team Routes
    |--------------------------------------------------------------------------
    */

    Route::get('team/{name}', 'TeamController@showByName');
    Route::resource('teams', 'TeamController', ['except' => ['show']]);
    Route::post('teams/search', 'TeamController@search');
    Route::post('teams/{id}/invite', 'TeamController@inviteMember');
    Route::get('teams/{id}/remove/{userId}', 'TeamController@removeMember');", '', $mainRoutes);
        $mainRoutes = str_replace("['auth', 'active']", "['auth']", $mainRoutes);
        file_put_contents(base_path('routes/web.php'), $mainRoutes);

        /*
         * --------------------------------------------------------------------------
         * Drop the activate by email notification
         * --------------------------------------------------------------------------
        */

        $activateUserEmail = file_get_contents(app_path('Notifications/ActivateUserEmail.php'));
        $activateUserEmail = str_replace("'mail'", '', $activateUserEmail);
        file_put_contents(app_path('Notifications/ActivateUserEmail.php'), $activateUserEmail);

        /*
         * --------------------------------------------------------------------------
         * Clean up the user model
         * --------------------------------------------------------------------------
        */

        $userModel = file_get_contents(app_path('Models/User.php'));
        $userModel = str_replace("/**
 * Teams
 *
 * @return Relationship
 */
public function teams()
{
    return \$this->belongsToMany(Team::class);
}

/**
 * Team member
 *
 * @return boolean
 */
public function isTeamMember(\$id)
{
    \$teams = array_column(\$this->teams->toArray(), 'id');
    return array_search(\$id, \$teams) > -1;
}

/**
 * Team admin
 *
 * @return boolean
 */
public function isTeamAdmin(\$id)
{
    \$team = \$this->teams->find(\$id);
    return (int)\$team->user_id === (int)\$this->id;
}", '', $userModel);
        $userModel = str_replace("use App\Models\Team;", '', $userModel);
        file_put_contents(app_path('Models/User.php'), $userModel);

        $userService = file_get_contents(app_path('Services/UserService.php'));
        $userService = str_replace('/*
|--------------------------------------------------------------------------
| Teams
|--------------------------------------------------------------------------
*/

public function joinTeam($teamId, $userId)
{
    $team = $this->team->find($teamId);
    $user = $this->model->find($userId);

    $user->teams()->attach($team);
}

public function leaveTeam($teamId, $userId)
{
    $team = $this->team->find($teamId);
    $user = $this->model->find($userId);

    $user->teams()->detach($team);
}

public function leaveAllTeams($userId)
{
    $user = $this->model->find($userId);
    $user->teams()->detach();
}', '', $userService);
        $userService = str_replace('use App\Models\Team;', '', $userService);
        $userService = str_replace('Team $team,', '', $userService);
        $userService = str_replace('$this->team = $team;', '', $userService);
        $userService = str_replace('$this->leaveAllTeams($id);', '', $userService);
        file_put_contents(app_path('Services/UserService.php'), $userService);

        $seed = file_get_contents(base_path('database/seeds/DatabaseSeeder.php'));
        $seed = str_replace('$this->call(TeamTableSeeder::class);', '', $seed);
        file_put_contents(base_path('database/seeds/DatabaseSeeder.php'), $seed);

        $css = file_get_contents(base_path('resources/sass/app.scss'));
        $css = str_replace('@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";', '@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";'."\n".'@import "resources/themes/default/assets/sass/_theme.scss";', $css);
        file_put_contents(base_path('resources/sass/app.scss'), $css);

        $composer = file_get_contents(base_path('composer.json'));
        $composer = str_replace('"App\\": "app/",', '"App\\": "app/",'."\n".'"Cms\\Modules\\": "cms/Modules/",', $composer);
        file_put_contents(base_path('composer.json'), $composer);
    }
1347863
public function resourcesAction($filename, $base_dir = null)
    {
        if (null === $base_dir) {
            File::resolveFilepath($filename, null, array('include_path' => $this->application->getResourceDir()));
        } else {
            File::resolveFilepath($filename, null, array('base_dir' => $base_dir));
        }

        $this->application->info(sprintf('Handling resource URL `%s`.', $filename));

        if (false === file_exists($filename) || false === is_readable($filename)) {
            $request = $this->application->getRequest();

            throw new FrontControllerException(sprintf(
                'The file `%s` can not be found (referer: %s).',
                $request->getHost().'/'.$request->getPathInfo(),
                $request->server->get('HTTP_REFERER')
            ), FrontControllerException::NOT_FOUND);
        }

        return $this->createResourceResponse($filename);
    }
276021
private function _loadExistingController()
    {
        $file = $this->_controllerPath.ucfirst($this->_url[0]).'.php';

        if (!file_exists($file)) {
            $this->_error();

            return false;
        }
        require $file;

        $namespace = str_replace('/', '\\', APP.'/Controllers/');
        $className = $namespace.$this->_url[0];

        $this->_controller = new $className();

        return true;
    }
363039
private function createFileHandler()
    {
        $path = sprintf($this->config["destination"], time(), date($this->config["datetimeFormat"]));

        $this->destinationHandler = @fopen($path, $this->config["writeMode"]);
        if (!$this->config["blocking"]) {
            stream_set_blocking($this->destinationHandler, (int)$this->config["blocking"]);
        }

        if (!$this->destinationHandler) {
            throw new RuntimeException("Failed to open file $path created from " . $this->config["destination"] . " expression (mode: " . $this->config["writeMode"] . ")");
        }
    }
1232899
function collect()
    {
        // TODO: Implement collect() method.
        if($this->controllerStorage)
        {
            return array(
                'file' => $this->controllerStorage->directory,
                'name' => $this->controllerStorage->name,
                'controller' => $this->getVariables()
            );
        }
    }
967300
function(controller, url) {
  controller.open(url);

  // Wait until the unknown content type dialog has been opened
  controller.waitForEval("subject.getMostRecentWindow('').document.documentElement.id == 'unknownContentType'",
                         gTimeout, 100, mozmill.wm);

  utils.handleWindow("type", "", function (controller) {
    // Select to save the file directly
    var saveFile = new elementslib.ID(controller.window.document, "save");
    controller.waitThenClick(saveFile, gTimeout);
    controller.waitForEval("subject.selected == true", gTimeout, 100,
                           saveFile.getNode());
  
    // Wait until the OK button has been enabled and click on it
    var button = new elementslib.Lookup(controller.window.document,
                                        '/id("unknownContentType")/anon({"anonid":"buttons"})/{"dlgtype":"accept"}');
    controller.waitForElement(button, gTimeout);
    controller.waitForEval("subject.okButton.hasAttribute('disabled') == false", gTimeout, 100,
                           {okButton: button.getNode()});
    controller.click(button);
  });
}
299128
public function actionFileRemove() {
		$source = $this->getSource();

		$file_path = false;

		$path = $source->getPath();

		$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);

		$target = $this->request->name;

		if (
			realpath($path . $target) &&
			strpos(realpath($path . $target), $source->getRoot()) !== false
		) {
			$file_path = realpath($path . $target);
		}

		if (!$file_path || !file_exists($file_path)) {
			throw new \Exception('File or directory not exists ' . $path . $target, Consts::ERROR_CODE_NOT_EXISTS);
		}

		if (is_file($file_path)) {
			$file = new File($file_path);
			if (!$file->remove()) {
				$error = (object)error_get_last();
				throw new \Exception('Delete failed! ' . $error->message, Consts::ERROR_CODE_IS_NOT_WRITEBLE);
			}
		} else {
			throw new \Exception('It is not a file!', Consts::ERROR_CODE_IS_NOT_WRITEBLE);
		}
	}
972029
def controller_creatr(filename):
    """"""
    if not check():
        click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:controller command')
        return

    path = os.path.abspath('.') + '/controller'
    if not os.path.exists(path):
        os.makedirs(path)

    # if os.path.isfile(path + )

    file_name = str(filename + '.py')
    if os.path.isfile(path+"/" + file_name):
        click.echo(Fore.WHITE + Back.RED + "ERROR: Controller file exists")
        return
    controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')
    compose = "from bast import Controller\n\nclass " + filename + "(Controller):\n    pass"
    controller_file.write(compose)
    controller_file.close()
    click.echo(Fore.GREEN + "Controller " + filename + " created successfully")
24724
public void saveFile(File file, String type)
   {
      if (file != null)
      {
         m_treeController.saveFile(file, type);
      }
   }
875410
protected function createFile()
    {
        $event = new FileEvent([
            'realPath' => $this->iterator->current(),
            'relativePath' => $this->iterator->getRelativePath()
        ]);

        $this->module->trigger(Module::EVENT_PROCESS_FILE, $event);

        $this->file = $event;
    }
1198970
protected function _includeAppController(): void
    {
        $controller = null;
        if (file_exists(WWW_ROOT . 'js/app/app_controller.js')) {
            $controller = 'app/app_controller.js';
        } else {
            $controller = '/frontend_bridge/js/lib/app_controller.js';
        }
        $this->_dependencies[] = $controller;
    }
414432
public function setController()
    {
        // Constructs the current controller
        $this->controller = ucfirst(strtolower($this->controller)) . 'Controller';

        // Constructs the current controller with the default path
        $this->controller = self::DEFAULT_PATH . $this->controller;

        // Checks if the current controller is an existing class
        if (!class_exists($this->controller)) {
            
            // Attributes the default path & controller to the current controller
            $this->controller = self::DEFAULT_PATH . self::DEFAULT_CONTROLLER;
        }
    }
15506
public function init() {

        parent::init();
        $this->registerTranslations();
        
        if(!$this->secure)
            $this->uploadAction = '/uploader/one-file/create';

        // set min & max file sizes
        if(is_null($this->minFileSize))
            $this->minFileSize = isset(\Yii::$app->params['fileSize']['min']) ? \Yii::$app->params['fileSize']['min'] : 0.01;
        if(is_null($this->maxFileSize))
            $this->maxFileSize = isset(\Yii::$app->params['fileSize']['max']) ? \Yii::$app->params['fileSize']['max'] : 2;

        // errors of the file uploading
        $this->errors['size'] = Yii::t('byone', 'File size can be from {minFileSize} to {maxFileSize}Mb', ['minFileSize' => $this->minFileSize, 'maxFileSize' => $this->maxFileSize]);
        $this->errors['type'] = Yii::t('byone', 'There is not right file type! Allowed types - {acceptFileTypes}.', ['acceptFileTypes' => $this->acceptFileTypes]);
        $this->errors['maxFiles'] = Yii::t('byone', 'Only {maxFiles} file(s) can be uploaded.', ['maxFiles' => $this->maxFiles]);

        // captions of the buttons and other strings that should be translated
        self::$defaults['choose']['label'] = Yii::t('byone', 'Photo');
        self::$defaults['choose']['caption'] = Yii::t('byone', 'Choose a file');
        self::$defaults['delete']['question'] = Yii::t('byone', 'Are you shure you want to delete this element?');
        self::$defaults['crop']['caption'] = Yii::t('byone', 'Upload');
        
        // set buttons by widget parameters or defaults
        foreach(self::$defaults as $name => $values) {
            foreach($values as $property => $value)
                if(!isset($this->btns[$name][$property]))
                    $this->btns[$name][$property] = $property == 'action' && !$this->secure 
                        ? str_replace('-secure', '', self::$defaults[$name][$property])
                        : self::$defaults[$name][$property];
        }
        
        // full path server side handlers
        $this->btns['delete']['action'] = Url::toRoute($this->btns['delete']['action']);
        $this->btns['save']['action'] = Url::toRoute($this->btns['save']['action']);
        $this->btns['crop']['action'] = Url::toRoute($this->btns['crop']['action']);
        $this->btns['swap']['action'] = Url::toRoute($this->btns['swap']['action']);
        
        $this->blueimp['url'] = Url::toRoute($this->uploadAction);
        
        $this->blueimp['minFileSize'] = $this->minFileSize;
        $this->blueimp['maxFileSize'] = $this->maxFileSize;
        
        // max files that can be uploaded
        $this->blueimp['maxFiles'] = $this->maxFiles;

        // if model name is not set, set it
        if(!isset($this->modelName))
            $this->modelName = get_class($this->model);
        // parent_id has to exist
        if(is_null($this->model->id))
            $this->model->id = false;
        if(is_null($this->parent_id))
            $this->parent_id = $this->model->id;
        if(is_null($this->subdir))
            $this->subdir = $this->model->id;
        // POST-type data for the handler
        $this->blueimp['formData'] = [
            'model' => $this->modelName,
            'parent_id' => $this->parent_id,
            'subdir' => $this->subdir,
            'cropAllowed' => ($this->cropAllowed ? 1 : 0),
        ];
        
        // min pixels for X and Y when cropping
        $minW = $this->model->getMin();
        $aspectRatio = $this->model->getAspectRatio();
        $minH = $minW * $aspectRatio;

        // send params to JavaScript environment
        $options = [
            'btns' => $this->btns,
            'barClass' => $this->barClass,
            'cropAllowed' => $this->cropAllowed,
            'minW' => $minW,
            'minH' => $minH,
            'aspectRatio' => $aspectRatio,
            'appendixView' => $this->appendixView,
            'acceptFileTypes' => $this->acceptFileTypes,
            'errors' => $this->errors,
        ];
        $this->view->registerJs(
            "editLine.options = " . json_encode($options) . ";", 
            View::POS_READY, 
            'editLineOptions'
        );
        
        // assets 
        BlueimpAsset::register($this->view);
        EditLineAsset::register($this->view);
        if($this->draggable) {
            JQueryUiAsset::register($this->view);
            DraggableAsset::register($this->view);
        }
        if($this->cropAllowed) 
            JcropAsset::register($this->view);
        // plugin
        $selector = $name = $this->blueimp['name'];
        $option = json_encode($this->blueimp);
        $script = "jQuery('#{$selector}').{$name}({$option});";
        $this->view->registerJs($script, View::POS_END, 'byone-plugin');
    }
1180951
public function viewFileManager()
    {
        $this->setFileFileManager();
        $this->setAccessFileManager();
        $this->setDataMessagesFileManager();

        $this->setData('access', $this->data_access);
        $this->setData('command', $this->data_command);
        $this->setData('selected', $this->data_selected);
        $this->setData('tabs', $this->getTabsFileManager());
        $this->setData('actions', $this->getActionsFileManager());
        $this->setData('process_selected', $this->isQuery('selected'));

        $this->submitFileManager();
        $this->setDataContendFileManager();

        $rendered = $this->render('file_manager|filemanager', $this->data);

        if ($this->isQuery('output')) {
            $this->response->outputHtml($rendered);
        }

        $this->setJsFileManager();
        $this->setCssFileManager();

        $this->setTitleFileManager();
        $this->setBreadcrumbFileManager();

        $this->setData('rendered_filemanager', $rendered);
        $this->outputViewFileManager();
    }
1003380
public function generateController()
    {
        if (!$content = $this->getControllerContent()) {
            return '';
        }

        $path = app_path('Http/Controllers/'.implode('/', $this->sectionSegmentsStudly).'Controller.php');

        if (is_file($path)) {
            return '';
        }

        $this->createMissingDirs($path);

        return file_put_contents($path, $content) !== false ? $path : '';
    }