Imports system/service

@return bool
@throws \DreamFactory\Core\Exceptions\InternalServerErrorException
493323
protected function insertService()
    {
        $data = $this->package->getResourceFromZip('system/service.json');
        $services = $this->cleanDuplicates($data, 'system', 'service');

        if (!empty($services)) {
            try {
                foreach ($services as $i => $service) {
                    unset($service['id']);
                    unset($service['last_modified_by_id']);
                    $service['created_by_id'] = Session::getCurrentUserId();
                    if (!empty($oldRoleId = array_get($service, 'config.default_role'))) {
                        $newRoleId = $this->getNewRoleId($oldRoleId);
                        if (!empty($newRoleId)) {
                            array_set($service, 'config.default_role', $newRoleId);
                        } else {
                            // If no new role found then do not store config. default_role field is not nullable.
                            $this->log(
                                'warning',
                                'Skipping config for service ' .
                                $service['name'] .
                                '. Default role not found by role id ' .
                                $oldRoleId
                            );
                            \Log::debug('Skipped service.', $service);
                            unset($service['config']);
                        }
                    }
                    if (!empty($oldDoc = array_get($service, 'doc'))) {
                        $service['service_doc_by_service_id'] = $oldDoc;
                        unset($service['doc']);
                    }
                    $services[$i] = $service;
                }

                $payload = ResourcesWrapper::wrapResources($services);
                $result = ServiceManager::handleRequest(
                    'system', Verbs::POST, 'service', [], [], $payload, null, true, true
                );
                if ($result->getStatusCode() >= 300) {
                    throw ResponseFactory::createExceptionFromResponse($result);
                }

                return true;
            } catch (\Exception $e) {
//                if ($e->getCode() === HttpStatusCodes::HTTP_FORBIDDEN) {
//                    $this->log('error', "Failed to insert services. " . $this->getErrorDetails($e));
//                } else {
//                    throw new InternalServerErrorException("Failed to insert services. " . $this->getErrorDetails($e));
//                }
                $this->throwExceptions($e, 'Failed to insert services');
            }
        }

        return false;
    }
1302358
public function importAction()
    {
        /* @var $form \Zork\Form\Form */
        $request        = $this->getRequest();
        $serviceLocator = $this->getServiceLocator();
        $returnUri      = $request->getQuery( 'returnUri' );
        $return         = $this->getValidReturnUri( $returnUri );
        $form           = $serviceLocator->get( 'Form' )
                                         ->get( 'Grid\Customize\Import' );

        if ( $request->isPost() )
        {
            $form->setData( $data = ArrayUtils::merge(
                $request->getPost()
                        ->toArray(),
                $request->getFiles()
                        ->toArray()
            ) );

            if ( ! empty( $data['returnUri'] ) )
            {
                $return = $this->getValidReturnUri(
                    $data['returnUri'],
                    $return
                );
            }

            if ( $form->isValid() )
            {
                $data       = $form->getData();
                $file       = $data['file']['tmp_name'];
                $name       = $data['file']['name'];
                $translator = $serviceLocator->get( 'translator' );
                $result     = $serviceLocator->get( 'Grid\Customize\Model\Importer' )
                                             ->import( $file, $name );

                if ( $result->isSuccess() )
                {
                    $this->messenger()
                         ->add(
                             sprintf(
                                 $translator->translate( 'customize.import.success.link.%s' ),
                                 $this->url()
                                      ->fromRoute( 'Grid\Paragraph\Render\Paragraph', array(
                                          'locale'        => (string) $this->locale(),
                                          'paragraphId'   => $result->getCreatedParagraphId(),
                                      ) )
                             ),
                             false,
                             Message::LEVEL_INFO
                         );
                }
                else
                {
                    $code = $result->getCode();

                    if ( ! isset( static::$importErrorMessages[$code] ) )
                    {
                        $code = ImportResult::UNKNOWN_ERROR;
                    }

                    $this->messenger()
                         ->add(
                             sprintf(
                                 $translator->translate( 'customize.import.failed.message.%s.%s' ),
                                 $translator->translate( static::$importErrorMessages[$code] ),
                                 $result->getErrorMessage()
                             ),
                             false,
                             Message::LEVEL_ERROR
                         );
                }

                if ( $return )
                {
                    return $this->redirect()
                                ->toUrl( $return );
                }
                else if ( $result->isSuccess() )
                {
                    return $this->redirect()
                                ->toRoute( 'Grid\Customize\CssAdmin\List', array(
                                    'locale' => (string) $this->locale(),
                                ) );
                }
            }
        }
        else if ( $return )
        {
            $form->get( 'returnUri' )
                 ->setValue( $return );
        }

        $form->setCancel(
            $return ? $return
                    : $this->url()
                           ->fromRoute( 'Grid\Customize\CssAdmin\List', array(
                               'locale' => (string) $this->locale(),
                           ) )
        );

        return array(
            'form' => $form,
        );
    }
1238157
public function boot()
    {
        $systemLocales = config('multilingual.locales');

        $this->publishes([
            __DIR__.'/config/multilingual.php' => config_path('multilingual.php'),
        ]);


        $this->app['validator']->extendImplicit('translatable_required', function ($attribute, $value, $parameters) use ($systemLocales) {
            if (! is_array($value)) {
                return false;
            }

            // Get only the locales that has a value and exists in the system locales array
            $locales = array_filter(array_keys($value), function ($locale) use ($value, $systemLocales) {
                return @$value[$locale] && in_array($locale, $systemLocales);
            });

            foreach ($systemLocales as $systemLocale) {
                if (! in_array($systemLocale, $locales)) {
                    return false;
                }
            }

            return true;
        });
    }
408587
public function ImportForm()
    {
        $modelSNG = singleton($this->modelClass);
        $modelName = $modelSNG->i18n_singular_name();
        // check if a import form should be generated
        if (!$this->showImportForm ||
            (is_array($this->showImportForm) && !in_array($this->modelClass, $this->showImportForm))
        ) {
            return false;
        }

        $importers = $this->getModelImporters();
        if (!$importers || !isset($importers[$this->modelClass])) {
            return false;
        }

        if (!$modelSNG->canCreate(Security::getCurrentUser())) {
            return false;
        }

        $fields = new FieldList(
            new HiddenField('ClassName', false, $this->modelClass),
            new FileField('_CsvFile', false)
        );

        // get HTML specification for each import (column names etc.)
        $importerClass = $importers[$this->modelClass];
        /** @var BulkLoader $importer */
        $importer = new $importerClass($this->modelClass);
        $spec = $importer->getImportSpec();
        $specFields = new ArrayList();
        foreach ($spec['fields'] as $name => $desc) {
            $specFields->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
        }
        $specRelations = new ArrayList();
        foreach ($spec['relations'] as $name => $desc) {
            $specRelations->push(new ArrayData(array('Name' => $name, 'Description' => $desc)));
        }
        $specHTML = $this->customise(array(
            'ClassName' => $this->sanitiseClassName($this->modelClass),
            'ModelName' => Convert::raw2att($modelName),
            'Fields' => $specFields,
            'Relations' => $specRelations,
        ))->renderWith($this->getTemplatesWithSuffix('_ImportSpec'));

        $fields->push(new LiteralField("SpecFor{$modelName}", $specHTML));
        $fields->push(
            new CheckboxField(
                'EmptyBeforeImport',
                _t('SilverStripe\\Admin\\ModelAdmin.EMPTYBEFOREIMPORT', 'Replace data'),
                false
            )
        );

        $actions = new FieldList(
            FormAction::create('import', _t('SilverStripe\\Admin\\ModelAdmin.IMPORT', 'Import from CSV'))
                ->addExtraClass('btn btn-outline-secondary font-icon-upload')
        );

        $form = new Form(
            $this,
            "ImportForm",
            $fields,
            $actions
        );
        $form->setFormAction(
            Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'ImportForm')
        );

        $this->extend('updateImportForm', $form);

        return $form;
    }
1068274
public static function compiles()
    {
        $files = [];

        foreach (modules()->repositories() as $repository) {
            foreach ($repository->all() as $module) {
                $serviceProvider = module_class($module['slug'], 'Providers\\ModuleServiceProvider', $repository->location);

                if (class_exists($serviceProvider)) {
                    $files = array_merge($files, forward_static_call([$serviceProvider, 'compiles']));
                }
            }
        }

        return array_map('realpath', $files);
    }
695798
protected function registerServices()
    {
        $services = array_filter($this->config->get('app.services'), function ($service) {
            return class_exists($service);
        });

        foreach ($services as $service) {
            /** @var \Fyuze\Kernel\Service $obj */
            $obj = new $service($this->container);
            $obj->services();

            $this->services[] = $obj;
        }
    }
1305341
public function main()
    {
        $this->info('Task: import system roles');
        $this->hr();

        $roles = Configure::read('RolesCapabilities.Roles');
        if (empty($roles)) {
            $this->warn("No roles configured for importing.  Nothing to do.");

            return true;
        }

        /**
         * @var \RolesCapabilities\Model\Table\RolesTable $table
         */
        $table = TableRegistry::get('RolesCapabilities.Roles');

        foreach ($roles as $role) {
            if (empty($role['name'])) {
                $this->warn("Skipping role without a name.");
                continue;
            }

            if ($table->exists(['name' => $role['name']])) {
                $this->warn("Role [" . $role['name'] . "] already exists. Skipping.");
                continue;
            }

            $this->info("Role [" . $role['name'] . "] does not exist. Creating.");
            $entity = $table->newEntity();
            $entity = $table->patchEntity($entity, $role);

            $group = $this->getGroupByRoleName($entity->get('name'));
            if (empty($group)) {
                $this->abort("Failed to fetch group [" . $entity->get('name') . "]");
            }

            $result = $table->save($entity);
            if (!$result) {
                $this->err("Errors: \n" . implode("\n", $this->getImportErrors($entity)));
                $this->abort("Failed to create role [" . $entity->get('name') . "]");
            }

            $msg = 'Role [' . $entity->get('name') . '] imported';
            // associate imported role with matching group
            if ($table->Groups->link($entity, [$group])) {
                $msg .= ' and associated with group [' . $group->get('name') . ']';
            }
            $msg .= ' successfully';

            $this->info($msg);
        }

        $this->success('System roles imported successfully');
    }
1327380
public function import() {
    $task = $this->taskDrush()
      ->drush('sql-drop')
      ->drush('sql-cli < ' . $this->getConfigValue('setup.dump-file'));
    $result = $task->run();
    $exit_code = $result->getExitCode();

    if ($exit_code) {
      throw new BltException("Unable to import setup.dump-file.");
    }
  }
1318289
public function import(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
    {
        return $this->getFactory()->createCompanyDataImport()->import($dataImporterConfigurationTransfer);
    }
742027
protected function importConfigurations()
    {
        foreach ($this->files as $key => $file) {
            if (!file_exists(static::$path.DS.$file.'.php')) {
                throw new \Exception("File doesn't exists in the path ".static::$path.DS.$file.'.php');
            }

            /*
            | We will include configuration file into array only
            | for the first time
             */
            if (!isset(static::$config[$key])) {
                static::set($key, include static::$path.DS.$file.'.php');
            }
        }
    }
101825
public function hasAnsiSupport(): bool
	{
		if($this->hasAnsiSupport === null)
		{
			$this->hasAnsiSupport = PHP_OS_FAMILY !== 'Windows' || (getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON');
		}

		return $this->hasAnsiSupport;
	}
940363
public function main()
    {
        $this->info('Task: import system menus');
        $this->hr();

        $data = $this->getSystemMenus();
        if (empty($data)) {
            $this->warn("System menus are not configured.  Nothing to do.");

            return true;
        }
        // get menus table
        $table = TableRegistry::getTableLocator()->get('Menu.Menus');

        foreach ($data as $menu) {
            if (empty($menu['name'])) {
                $this->warn("Skipping menu without a name.");
                continue;
            }

            if ($table->exists(['name' => $menu['name']])) {
                $this->warn("Menu [" . $menu['name'] . "] already exists. Skipping.");
                continue;
            }

            $this->info("Menu [" . $menu['name'] . "] does not exist.  Creating.");
            $entity = $table->newEntity();
            $entity = $table->patchEntity($entity, $menu);
            $result = $table->save($entity);
            if (!$result) {
                $this->err("Errors: \n" . implode("\n", $this->getImportErrors($entity)));
                $this->abort("Failed to create menu [" . $menu['name'] . "]");
            }
        }

        $this->success('System menus imported successfully');
    }
231492
public function boot()
    {
        if ($this->booted) {
            return $this;
        }

        $services = $this->configurations();

        $services[] = \Bow\Configuration\Configurations\ActionnerConfiguration::class;

        $service_collection = [];

        $container = Capsule::getInstance();

        // Configuration of services
        foreach ($services as $service) {
            if ($this->without_session && $service == \Bow\Session\SessionConfiguration::class) {
                continue;
            }

            if (class_exists($service, true)) {
                $class = new $service($container);

                $class->create($this);

                $service_collection[] = $class;
            }
        }

        // Start of services or initial code
        foreach ($service_collection as $service) {
            $service->run();
        }

        $this->booted = true;

        return $this;
    }
712306
protected function importData()
    {
        if (($handle = fopen($this->file, "r")) !== false) {
            $header = fgetcsv($handle, 0, ',');
            $result = [];
            while (false !== ($row = fgetcsv($handle))) {
                $new = [];
                foreach ($header as $key => $value) {
                    $new[$value] = array_get($row, $key);
                }
                $result[] = $new;
                if (count($result) === 500) {
                    $this->insertTableData($result);
                }
            }

            if (count($result) > 0) {
                $this->insertTableData($result, false);
            }

            fclose($handle);
            unlink($this->file);
        } else {
            throw new InternalServerErrorException('Could not open uploaded CSV file.');
        }
    }
671495
public function boot()
    {
        if (true === $this->booted) {
            return $this;
        }

        if($this->isDebug()) {
            ExceptionHandler::register(true, 'UTF-8', 'PPI Framework', self::VERSION, true);
        }

        $this->serviceManager = $this->buildServiceManager();
        $this->log('debug', sprintf('Booting %s ...', $this->name));

        // Loading our Modules
        $this->getModuleManager()->loadModules();
        if ($this->debug) {
            $modules = $this->getModuleManager()->getModules();
            $this->log('debug', sprintf('All modules online (%d): "%s"', count($modules), implode('", "', $modules)));
        }

        // Lets get all the services our of our modules and start setting them in the ServiceManager
        $moduleServices = $this->serviceManager->get('ModuleDefaultListener')->getServices();
        foreach ($moduleServices as $key => $service) {
            $this->serviceManager->setFactory($key, $service);
        }

        $this->booted = true;
        if ($this->debug) {
            $this->log('debug', sprintf('%s has booted (in %.3f secs)', $this->name, microtime(true) - $this->startTime));
        }

        return $this;
    }
909594
public function boot()
    {
        Storage::extend('oss', function ($app, $config) {
            $accessId = $config['access_id'];
            $accessKey = $config['access_key'];
            $endPoint = $config['endpoint'];
            $bucket = $config['bucket'];

            $prefix = null;
            if (isset($config['prefix'])) {
                $prefix = $config['prefix'];
            }

            $client = new OssClient($accessId, $accessKey, $endPoint);
            $adapter = new AliyunOssAdapter($client, $bucket, $prefix);

            $filesystem = new Filesystem($adapter);
            $filesystem->addPlugin(new PutFile());
            $filesystem->addPlugin(new SignedDownloadUrl());

            return $filesystem;
        });
    }
373233
public function compile()
    {
        $this->manageInheritance();
        $this->serviceConfig = $this->insertParameters($this->serviceConfig);
        $this->buildArguments('Arguments');
        $this->buildArguments('MethodArguments');
        $this->buildCallsArguments();
        $this->buildFactoryArgument();

        return $this->buildServiceConfig();
    }