Import admins.

@param \Cortex\Auth\Models\Admin                            $admin
@param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable

@return \Illuminate\View\View
974727
public function import(Admin $admin, ImportRecordsDataTable $importRecordsDataTable)
    {
        return $importRecordsDataTable->with([
            'resource' => $admin,
            'tabs' => 'adminarea.admins.tabs',
            'url' => route('adminarea.admins.stash'),
            'id' => "adminarea-attributes-{$admin->getRouteKey()}-import-table",
        ])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
    }
1181802
public function admin( $options, $component ) {

		$this->languages_available = get_available_languages();

		/**
		 * format: array( language, version, updated, english_name, native_name, package, iso, strings )
		 */
		require_once ABSPATH . 'wp-admin/includes/translation-install.php';

		$this->languages_translated = wp_get_available_translations();

		// en_US is always installed (default locale of WP)
		$data = array(
			'en_US' => array(
				'id'          => 'en_US',
				'locale'      => 'en_US',
				'lang'        => 'English',
				'lang_native' => 'English',
				'enabled'     => 'Default',
			),
		);

		foreach ( $this->languages_available as $locale ) {
			$checked = checked( isset( $this->languages[ $locale ] ), true, false );

			$enabled = sprintf( '<input type="checkbox" name="pods_i18n_enabled_languages[%s]" value="%s"%s />', esc_attr( $locale ), esc_attr( $locale ), $checked );

			$data[ $locale ] = array(
				'id'          => $locale,
				'locale'      => $locale,
				'lang'        => $this->languages_translated[ $locale ]['english_name'],
				'lang_native' => $this->languages_translated[ $locale ]['native_name'],
				'enabled'     => $enabled,
			);
		}

		$ui = array(
			'component'        => $component,
			// 'data' => $data,
			// 'total' => count( $data ),
			// 'total_found' => count( $data ),
			'items'            => __( 'Languages', 'pods' ),
			'item'             => __( 'Language', 'pods' ),
			'fields'           => array(
				'manage' => array(
					'enabled'     => array(
						'label' => __( 'Active', 'pods' ),
						'type'  => 'raw',
					),
					'locale'      => array(
						'label'   => __( 'Locale', 'pods' ),
						'classes' => array( 'column-secondary' ),
					),
					'lang'        => array( 'label' => __( 'Language', 'pods' ) ),
					'lang_native' => array( 'label' => __( 'Native name', 'pods' ) ),
					/*
					'fields' => array(
						'label' => __( 'Fields', 'pods' ),
						'type' => 'text',
						'options' => array(
							'text_allow_html' => 1,
							'text_allowed_html_tags' => 'br code'
						)
					),*/
				),
			),
			'actions_disabled' => array( 'edit', 'add', 'delete', 'duplicate', 'view', 'export' ),
			'actions_custom'   => array(
				// 'add' => array( $this, 'admin_add' ),
				// 'edit' => array( $this, 'admin_edit' ),
				// 'delete' => array( $this, 'admin_delete' )
			),
			'search'           => false,
			'searchable'       => false,
			'sortable'         => false,
			'pagination'       => false,
		);

		/**
		 * Filter the language data
		 *
		 * @since 0.1.0
		 *
		 * @param array
		 */
		$data = apply_filters( 'pods_component_i18n_admin_data', $data );

		/**
		 * Filter the UI fields
		 *
		 * @since 0.1.0
		 *
		 * @param array
		 */
		$ui['fields'] = apply_filters( 'pods_component_i18n_admin_ui_fields', $ui['fields'], $data );

		$ui['data']        = $data;
		$ui['total']       = count( $data );
		$ui['total_found'] = count( $data );

		/*
		if ( !pods_is_admin( array( 'pods_i18n_activate_lanuages' ) ) )
			$ui[ 'actions_disabled' ][] = 'edit';*/

		echo '<div id="pods_admin_i18n" class="pods-submittable-fields">';

		// Do save action here because otherwise the loading of post_types get done first and labels aren't translated
		if ( pods_is_admin( $this->capability ) && isset( $_POST['_nonce_i18n'] ) && wp_verify_nonce( $_POST['_nonce_i18n'], $this->nonce ) ) {
			pods_message( __( 'Updated active languages.', 'pods' ) );
		}

		pods_ui( $ui );

		// @todo Do this in pods_ui so we don't rely on javascript
		echo '<div id="pods_i18n_settings_save">';
		wp_nonce_field( $this->nonce, '_nonce_i18n', false );
		submit_button();
		echo '</div>';

		echo '</div>';
	}
772130
public function build(AdminInterface $admin, RouteCollection $collection)
    {
        $collection->add('list');
        $collection->add('create');
        $collection->add('batch', null, [], [], [], '', [], ['POST']);
        $collection->add('edit', $admin->getRouterIdParameter().'/edit', [], ['id' => '.+']);
        $collection->add('delete', $admin->getRouterIdParameter().'/delete', [], ['id' => '.+']);
        $collection->add('export');
        $collection->add('show', $admin->getRouterIdParameter().'/show', [], ['id' => '.+'], [], '', [], ['GET']);

        if ($admin->isAclEnabled()) {
            $collection->add('acl', $admin->getRouterIdParameter().'/acl', [], ['id' => '.+']);
        }

        // add children urls
        foreach ($admin->getChildren() as $children) {
            $collection->addCollection($children->getRoutes());
        }
    }
771081
protected function streamOutput(ExportableInterface $adminList, $format)
    {
        $response = new StreamedResponse();
        $response->setCallback(function () use ($adminList, $format) {
            $writer = WriterFactory::create($format);
            $writer->openToBrowser('export.'.$format);

            $row = [];
            /** @var Field $column */
            foreach ($adminList->getExportColumns() as $column) {
                $row[] = $this->translator->trans($column->getHeader());
            }
            $writer->addRow($row);

            $iterator = $adminList->getIterator();
            $rows = [];
            foreach ($iterator as $item) {
                if (array_key_exists(0, $item)) {
                    $itemObject = $item[0];
                } else {
                    $itemObject = $item;
                }

                $row = [];
                /** @var Field $column */
                foreach ($adminList->getExportColumns() as $column) {
                    $columnName = $column->getName();
                    $itemHelper = $itemObject;
                    if ($column->hasAlias()) {
                        $itemHelper = $column->getAliasObj($itemObject);
                        $columnName = $column->getColumnName($columnName);
                    }
                    $data = $adminList->getStringValue($itemHelper, $columnName);
                    if (null !== $column->getTemplate()) {
                        if (!$this->renderer->exists($column->getTemplate())) {
                            throw new ExportException('No export template defined for ' . get_class($data), $data);
                        }

                        $data = $this->renderer->render($column->getTemplate(), ['object' => $data]);
                    }

                    $row[] = $data;
                }
                $rows[] = $row;
            }

            $writer->addRows($rows);
            $writer->close();
        });

        return $response;
    }
608482
public function ProcessImportDb() {
      // Grab a list of all of the tables.
      $TableNames = $this->SQL->FetchTables(':_z%');
      if (count($TableNames) == 0) {
         throw new Gdn_UserException('Your database does not contain any import tables.');
      }

      $Tables = array();
      foreach ($TableNames as $TableName) {
         $TableName = StringBeginsWith($TableName, $this->Database->DatabasePrefix, TRUE, TRUE);
         $DestTableName = StringBeginsWith($TableName, 'z', TRUE, TRUE);
         $TableInfo = array('Table' => $DestTableName);

         $ColumnInfos = $this->SQL->FetchTableSchema($TableName);
         $Columns = array();
         foreach ($ColumnInfos as $ColumnInfo) {
            $Columns[GetValue('Name', $ColumnInfo)] = Gdn::Structure()->ColumnTypeString($ColumnInfo);
         }
         $TableInfo['Columns'] = $Columns;
         $Tables[$DestTableName] = $TableInfo;
      }
      $this->Data['Tables'] = $Tables;
      return TRUE;
   }
807444
protected function _importResult(Import $import, array $headers, int $rowNumber, array $data) : void
    {
        $importTable = TableRegistry::get('CsvMigrations.ImportResults');
        Assert::isInstanceOf($importTable, ImportResultsTable::class);

        $query = $importTable->find('all')
            ->enableHydration(true)
            ->where(['import_id' => $import->get('id'), 'row_number' => $rowNumber]);

        try {
            $importResult = $query->firstOrFail();
        } catch (RecordNotFoundException $e) {
            return;
        }

        Assert::isInstanceOf($importResult, ImportResult::class);

        // skip successful imports
        if ($importTable::STATUS_SUCCESS === $importResult->get('status')) {
            return;
        }

        $table = TableRegistry::get($importResult->get('model_name'));

        $data = $this->_prepareData($import, $headers, $data);
        $csvFields = FieldUtility::getCsv($table);
        $data = $this->_processData($table, $csvFields, $data);

        // skip empty processed data
        if (empty($data)) {
            $this->_importFail($importResult, ['Row has no data']);

            return;
        }

        try {
            $entity = $table->newEntity();
            $entity = $table->patchEntity($entity, $data);

            $table->save($entity) ?
                $this->_importSuccess($importResult, $entity) :
                $this->_importFail($importResult, $entity->getErrors());
        } catch (CakeException $e) {
            $this->_importFail($importResult, [$e->getMessage()]);
        } catch (PDOException $e) {
            $this->_importFail($importResult, [$e->getMessage()]);
        }
    }
87596
public static function import($records)
    {
        $objects = array();
        $className = get_called_class();
        $defaults = self::schema()->defaults();

        foreach ($records as $record) {
            $objects []= $className::fromArray()
                ->load(array_merge($defaults, $record))->markSaved(false)->save();
        }

        return $objects;
    }
998327
public function Index() {
      $this->Permission('Garden.Import'); // This permission doesn't exist, so only users with Admin == '1' will succeed.
      $Timer = new Gdn_Timer();

      // Determine the current step.
      $this->Form = new Gdn_Form();
      $Imp = new ImportModel();
      $Imp->LoadState();

      // Search for the list of acceptable imports.
      $ImportPaths = array();
      $ExistingPaths = SafeGlob(PATH_UPLOADS.'/export*', array('gz', 'txt'));
      $ExistingPaths2 = SafeGlob(PATH_UPLOADS.'/porter/export*', array('gz'));
      $ExistingPaths = array_merge($ExistingPaths, $ExistingPaths2);
      foreach ($ExistingPaths as $Path)
         $ImportPaths[$Path] = basename($Path);
      // Add the database as a path.
      $ImportPaths = array_merge(array('db:' => T('This Database')), $ImportPaths);

      if($Imp->CurrentStep < 1) {
         // Check to see if there is a file.
         $ImportPath = C('Garden.Import.ImportPath');
         $Validation = new Gdn_Validation();


         if (strcasecmp(Gdn::Request()->RequestMethod(), 'post') == 0) {
            $Upload = new Gdn_Upload();
            $Validation = new Gdn_Validation();
            if (count($ImportPaths) > 0)
               $Validation->ApplyRule('PathSelect', 'Required', T('You must select a file to import.'));

            if (count($ImportPaths) == 0 || $this->Form->GetFormValue('PathSelect') == 'NEW')
               $TmpFile = $Upload->ValidateUpload('ImportFile', FALSE);
            else
               $TmpFile = '';

            if ($TmpFile) {
               $Filename = $_FILES['ImportFile']['name'];
               $Extension = pathinfo($Filename, PATHINFO_EXTENSION);
               $TargetFolder = PATH_ROOT . DS . 'uploads' . DS . 'import';
               if(!file_exists($TargetFolder)) {
                  mkdir($TargetFolder, 0777, TRUE);
               }
               $ImportPath = $Upload->GenerateTargetName(PATH_ROOT . DS . 'uploads' . DS . 'import', $Extension);
               $Upload->SaveAs($TmpFile, $ImportPath);
               $Imp->ImportPath = $ImportPath;
               $this->Form->SetFormValue('PathSelect', $ImportPath);

               $UploadedFiles = GetValue('UploadedFiles', $Imp->Data);
               $UploadedFiles[$ImportPath] = basename($Filename);
               $Imp->Data['UploadedFiles'] = $UploadedFiles;
            } elseif (($PathSelect = $this->Form->GetFormValue('PathSelect'))) {
               if ($PathSelect == 'NEW')
                  $Validation->AddValidationResult('ImportFile', 'ValidateRequired');
               else
                  $Imp->ImportPath = $PathSelect;
            } elseif (!$Imp->ImportPath && count($ImportPaths) == 0) {
               // There was no file uploaded this request or before.
               $Validation->AddValidationResult('ImportFile', $Upload->Exception);
            }

            // Validate the overwrite.
            if(TRUE || strcasecmp($this->Form->GetFormValue('Overwrite'), 'Overwrite') == 0) {
               if (!StringBeginsWith($this->Form->GetFormValue('PathSelect'), 'Db:', TRUE)) {
                  $Validation->ApplyRule('Email', 'Required');
                  if (!$this->Form->GetFormValue('UseCurrentPassword'))
                     $Validation->ApplyRule('Password', 'Required');
               }
            }

            if ($Validation->Validate($this->Form->FormValues())) {
               $this->Form->SetFormValue('Overwrite', 'overwrite');
               $Imp->FromPost($this->Form->FormValues());
               $this->View = 'Info';
            } else {
               $this->Form->SetValidationResults($Validation->Results());
            }
         } else {
            $this->Form->SetFormValue('PathSelect', $Imp->ImportPath);
         }
         $Imp->SaveState();
      } else {
         $this->SetData('Steps', $Imp->Steps());
         $this->View = 'Info';
      }

      if (!StringBeginsWith($Imp->ImportPath, 'db:') && !file_exists($Imp->ImportPath))
         $Imp->DeleteState();

      try {
         $UploadedFiles = GetValue('UploadedFiles', $Imp->Data, array());
         $ImportPaths = array_merge($ImportPaths, $UploadedFiles);
         $this->SetData('ImportPaths', $ImportPaths);
         $this->SetData('Header', $Imp->GetImportHeader());
         $this->SetData('Stats', GetValue('Stats', $Imp->Data, array()));
         $this->SetData('GenerateSQL', GetValue('GenerateSQL', $Imp->Data));
         $this->SetData('ImportPath', $Imp->ImportPath);
         $this->SetData('OriginalFilename', GetValue('OriginalFilename', $Imp->Data));
         $this->SetData('CurrentStep', $Imp->CurrentStep);
         $this->SetData('LoadSpeedWarning', $Imp->LoadTableType(FALSE) == 'LoadTableWithInsert');
      } catch(Gdn_UserException $Ex) {
         $this->Form->AddError($Ex);
         $Imp->SaveState();
         $this->View = 'Index';
      }
      $this->Render();
   }
1260737
public function bind(AbstractAdmin $admin, Request $request)
    {
        if ($this->request) {
            throw new \RuntimeException('A datagrid can only be bound once to a request');
        }

        // configure our datagrid
        $resolver = new OptionsResolver();
        $this->configureOptions($resolver);
        $this->options = $resolver->resolve($admin->getDatagridOptions());

        $this->admin = $admin;
        $this->request = $request;

        // attach our fields, filters and actions
        $this->admin->buildDatagrid($this);

        $this->applyFilters();
    }
377894
public function import(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
    {
        return $this->getFactory()
            ->getProductQuantityDataImporter()
            ->import($dataImporterConfigurationTransfer);
    }
442526
public function import(Ability $ability, ImportRecordsDataTable $importRecordsDataTable)
    {
        return $importRecordsDataTable->with([
            'resource' => $ability,
            'tabs' => 'adminarea.abilities.tabs',
            'url' => route('adminarea.abilities.stash'),
            'id' => "adminarea-abilities-{$ability->getRouteKey()}-import-table",
        ])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
    }
1190841
public function import(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
    {
        return $this->getFactory()->createMerchantRelationshipDataImport()->import($dataImporterConfigurationTransfer);
    }
997794
public function importProductMeasurementUnit(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
    {
        return $this->getFactory()
            ->getProductMeasurementUnitDataImporter()
            ->import($dataImporterConfigurationTransfer);
    }
1212427
public function admin( $options, $component ) {

		global $wp_roles;

		// Hook into Gravity Forms roles (since it only adds filter if Members plugin itself is activated
		if ( class_exists( 'RGForms' ) && ! has_filter(
			'members_get_capabilities', array(
				'RGForms',
				'members_get_capabilities',
			)
		) ) {
			add_filter( 'members_get_capabilities', array( 'RGForms', 'members_get_capabilities' ) );
		}

		$default_role = get_option( 'default_role' );

		$roles = array();

		foreach ( $wp_roles->role_objects as $key => $role ) {
			$count = $this->count_users( $key );

			$roles[ $key ] = array(
				'id'           => $key,
				'label'        => $wp_roles->role_names[ $key ],
				'name'         => $key,
				'capabilities' => count( (array) $role->capabilities ),
				'users'        => sprintf( _n( '%s User', '%s Users', $count, 'pods' ), $count ),
			);

			if ( $default_role == $key ) {
				$roles[ $key ]['label'] .= ' (site default)';
			}

			if ( 0 < $count && pods_is_admin( array( 'list_users' ) ) ) {
				$roles[ $key ]['users'] .= '<br /><a href="' . admin_url( esc_url( 'users.php?role=' . $key ) ) . '">' . __( 'View Users', 'pods' ) . '</a>';
			}
		}

		$ui = array(
			'component'        => $component,
			'data'             => $roles,
			'total'            => count( $roles ),
			'total_found'      => count( $roles ),
			'items'            => 'Roles',
			'item'             => 'Role',
			'fields'           => array(
				'manage' => array(
					'label'        => array( 'label' => __( 'Label', 'pods' ) ),
					'name'         => array( 'label' => __( 'Name', 'pods' ) ),
					'capabilities' => array( 'label' => __( 'Capabilities', 'pods' ) ),
					'users'        => array(
						'label'   => __( 'Users', 'pods' ),
						'type'    => 'text',
						'options' => array(
							'text_allow_html'        => 1,
							'text_allowed_html_tags' => '',
						),
					),
				),
			),
			'actions_disabled' => array( 'duplicate', 'view', 'export' ),
			'actions_custom'   => array(
				'add'    => array( $this, 'admin_add' ),
				'edit'   => array( $this, 'admin_edit' ),
				'delete' => array( $this, 'admin_delete' ),
			),
			'search'           => false,
			'searchable'       => false,
			'sortable'         => false,
			'pagination'       => false,
		);

		if ( isset( $roles[ pods_var( 'id', 'get', - 1 ) ] ) ) {
			$ui['row'] = $roles[ pods_var( 'id', 'get', - 1 ) ];
		}

		if ( ! pods_is_admin( array( 'pods_roles_add' ) ) ) {
			$ui['actions_disabled'][] = 'add';
		}

		if ( ! pods_is_admin( array( 'pods_roles_edit' ) ) ) {
			$ui['actions_disabled'][] = 'edit';
		}

		if ( count( $roles ) < 2 || ! pods_is_admin( array( 'pods_roles_delete' ) ) ) {
			$ui['actions_disabled'][] = 'delete';
		}

		pods_ui( $ui );
	}
463551
def active_admin_import(options = {}, &block)
      options.assert_valid_keys(*Options::VALID_OPTIONS)

      options = Options.options_for(config, options)
      params_key = ActiveModel::Naming.param_key(options[:template_object])

      collection_action :import, method: :get do
        authorize!(ActiveAdminImport::Auth::IMPORT, active_admin_config.resource_class)
        @active_admin_import_model = options[:template_object]
        render template: options[:template]
      end

      action_item :import, only: :index, if: options[:if] do
        if authorized?(ActiveAdminImport::Auth::IMPORT, active_admin_config.resource_class)
          link_to(
            I18n.t('active_admin_import.import_model', plural_model: options[:plural_resource_label]),
            action: :import
          )
        end
      end

      collection_action :do_import, method: :post do
        authorize!(ActiveAdminImport::Auth::IMPORT, active_admin_config.resource_class)
        _params = params.respond_to?(:to_unsafe_h) ? params.to_unsafe_h : params
        params = ActiveSupport::HashWithIndifferentAccess.new _params
        @active_admin_import_model = options[:template_object]
        @active_admin_import_model.assign_attributes(params[params_key].try(:deep_symbolize_keys) || {})
        # go back to form
        return render template: options[:template] unless @active_admin_import_model.valid?
        @importer = Importer.new(
          options[:resource_class],
          @active_admin_import_model,
          options
        )
        begin
          result = @importer.import

          if block_given?
            instance_eval(&block)
          else
            instance_exec result, options, &DEFAULT_RESULT_PROC
          end
        rescue ActiveRecord::Import::MissingColumnError, NoMethodError, ActiveRecord::StatementInvalid, CSV::MalformedCSVError => e
          Rails.logger.error(I18n.t('active_admin_import.file_error', message: e.message))
          Rails.logger.error(e.backtrace.join("\n"))
          flash[:error] = I18n.t('active_admin_import.file_error', message: e.message[0..200])
        end
        redirect_to options[:back]
      end
      # rubocop:enable Metrics/AbcSize
    end
1305482
public function importBusinessUnitUser(?DataImporterConfigurationTransfer $dataImporterConfigurationTransfer = null): DataImporterReportTransfer
    {
        return $this->getFactory()->getCompanyBusinessUnitUserDataImport()->import($dataImporterConfigurationTransfer);
    }
1172767
private function createAdmin(): void
    {
        $this->connection->beginTransaction();
        try {
            $this->userService->createUser(
                [
                    'email' => $this->email,
                    'password' => $this->password,
                    'is_active' => BoolEnum::yes()->id(),
                    'activated_at' => Carbon::now()->toDateTimeString(),
                ],
                [
                    'first_name' => 'Super',
                    'last_name' => 'Admin',
                    // TODO set admin default photo
                ],
                [
                    $this->roleRepository->getRoleSuperAdminId(),
                    $this->roleRepository->getRoleUserId()
                ]
            );
        } catch (\Throwable $exception) {
            $this->connection->rollBack();

            report($exception);

            $this->info('error:');
            $this->error($exception->getMessage());

            exit;
        }

        $this->connection->commit();
    }