Export entire database to PHP fixtures.

By default, all generated PHP files will be placed in `/tmp/fixture/`
directory, this can be changed using the `--destination` argument.

@return bool
355557
public function main()
    {
        $options = (array)$this->params;
        $destination = normalizePath("{$options['destination']}/");

        if (is_string($options['tables'])) {
            $options['tables'] = explode(',', $options['tables']);
        }

        if (is_string($options['no-data'])) {
            $options['no-data'] = explode(',', $options['no-data']);
        }

        if (file_exists($destination)) {
            $dst = new Folder($destination);
            $dst->delete();
            $this->out(__d('system', 'Removing existing directory: {0}', $destination), 1, Shell::VERBOSE);
        } else {
            new Folder($destination, true);
            $this->out(__d('system', 'Creating directory: {0}', $destination), 1, Shell::VERBOSE);
        }

        $db = ConnectionManager::get('default');
        $db->connect();
        $schemaCollection = $db->schemaCollection();
        $tables = $schemaCollection->listTables();

        foreach ($tables as $table) {
            if (!empty($options['tables']) && !in_array($table, $options['tables'])) {
                $this->out(__d('system', 'Table "{0}" skipped', $table), 1, Shell::VERBOSE);
                continue;
            }

            $Table = TableRegistry::get($table);
            $Table->behaviors()->reset();
            $fields = [
                '_constraints' => [],
                '_indexes' => [],
                '_options' => (array)$Table->schema()->options(),
            ];
            $columns = $Table->schema()->columns();
            $records = [];
            $primaryKeys = [];

            foreach ($Table->schema()->indexes() as $indexName) {
                $index = $Table->schema()->index($indexName);
                if (!empty($index['columns'])) {
                    $fields['_indexes']["{$table}_{$indexName}_index"] = $index;
                }
            }

            foreach ($columns as $column) {
                $fields[$column] = $Table->schema()->column($column);
            }

            foreach ($Table->schema()->constraints() as $constraint) {
                $constraintName = in_array($constraint, $columns) ? Inflector::underscore("{$table}_{$constraint}") : $constraint;
                $fields['_constraints'][$constraintName] = $Table->schema()->constraint($constraint);
                if (isset($fields['_constraints']['primary']['columns'])) {
                    $primaryKeys = $fields['_constraints']['primary']['columns'];
                }
            }

            foreach ($fields as $column => $info) {
                if (isset($info['length']) &&
                    in_array($column, $primaryKeys) &&
                    isset($info['autoIncrement']) &&
                    $info['autoIncrement'] === true
                ) {
                    unset($fields[$column]['length']);
                }
            }

            // FIX: We need RAW data for time instead of Time Objects
            $originalTypes = [];
            foreach ($Table->schema()->columns() as $column) {
                $type = $Table->schema()->columnType($column);
                $originalTypes[$column] = $type;
                if (in_array($type, ['date', 'datetime', 'time'])) {
                    $Table->schema()->columnType($column, 'string');
                }
            }

            if ($options['mode'] === 'full') {
                foreach ($Table->find('all') as $row) {
                    $row = $row->toArray();
                    if ($this->params['no-id'] && isset($row['id'])) {
                        unset($row['id']);
                    }
                    $records[] = $row;
                }
            }

            $className = Inflector::camelize($table) . 'Fixture';
            if ($options['fixture'] && in_array($className, ['AcosFixture', 'UsersFixture'])) {
                $records = [];
            }

            // undo changes made by "FIX"
            foreach ($originalTypes as $column => $type) {
                $fields[$column]['type'] = $type;
            }

            if (empty($fields['_indexes'])) {
                unset($fields['_indexes']);
            }

            $fields = $this->_arrayToString($fields);
            $records = in_array($table, $options['no-data']) ? '[]' : $this->_arrayToString($records);

            $fixture = $this->_classFileHeader($className);
            $fixture .= "{\n";
            $fixture .= "\n";
            $fixture .= "    /**\n";
            $fixture .= "     * Table name.\n";
            $fixture .= "     *\n";
            $fixture .= "     * @var string\n";
            $fixture .= "     */\n";
            $fixture .= "    public \$table = '{$table}';\n";
            $fixture .= "\n";
            $fixture .= "    /**\n";
            $fixture .= "     * Table columns.\n";
            $fixture .= "     *\n";
            $fixture .= "     * @var array\n";
            $fixture .= "     */\n";
            $fixture .= "    public \$fields = {$fields};\n";
            $fixture .= "\n";
            $fixture .= "    /**\n";
            $fixture .= "     * Table records.\n";
            $fixture .= "     *\n";
            $fixture .= "     * @var array\n";
            $fixture .= "     */\n";
            $fixture .= "    public \$records = {$records};\n";
            $fixture .= "}\n";

            $file = new File(normalizePath("{$destination}/{$className}.php"), true);
            $file->write($fixture, 'w', true);
            $this->out(__d('system', 'Table "{0}" exported!', $table), 1, Shell::VERBOSE);
        }

        $this->out(__d('system', 'Database exported to: {0}', $destination));

        return true;
    }
940445
public static function phpini()
    {
        if (!self::isDebug()) {
            return false;
        }

        $data = get_cfg_var('cfg_file_path');
        if (!@file($data)) {
            return false;
        }
        $ini = parse_ini_file($data, true);
        return self::i()->dump($ini, '! php.ini !');
    }
518443
public function export_to_client() {
        if(!Permission::check('CODE_BANK_ACCESS')) {
            return Security::permissionFailure($this);
        }
        
        
        //Bump up time limit we may need it
        set_time_limit(480);
        
        
        //Dump Data
        $languages=$this->queryToArray(DB::query('SELECT "ID", "Name", "FileExtension", "HighlightCode", "UserLanguage" FROM "SnippetLanguage"'));
        $snippets=$this->queryToArray(DB::query('SELECT "ID", "Title", "Description", "Tags", "LanguageID", "PackageID", "FolderID" FROM "Snippet"'));
        $versions=$this->queryToArray(DB::query('SELECT "ID", "Created", "Text", "ParentID" FROM "SnippetVersion"'));
        $packages=$this->queryToArray(DB::query('SELECT "ID", "Title" FROM "SnippetPackage"'));
        $folders=$this->queryToArray(DB::query('SELECT "ID", "Name", "ParentID", "LanguageID" FROM "SnippetFolder"'));
        
        
        //Build final response array
        $response=array(
                        'format'=>'ToClient',
                        'data'=>array(
                                    'languages'=>$languages,
                                    'snippets'=>$snippets,
                                    'versions'=>$versions,
                                    'packages'=>$packages,
                                    'folders'=>$folders
                                )
                    );
        
        
        //Send File
        SS_HTTPRequest::send_file(json_encode($response), date('Y-m-d_hi').'.cbexport', 'application/json')->output();
        
        
        //Save session and exit
        Session::save();
        exit;
    }
809085
private function getDumpFolderPath()
    {
        if (is_null($this->tmpFilePath)) {
            $dumpName = $this->getDumpName();
            $databaseName = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('dbName');
            $this->tmpFilePath = $this->tempDirectory . '/' . $databaseName . '_dbdump/'. $dumpName .'/';
            $this->getFileHandler()->createDirectory($this->tmpFilePath);
        }

        return $this->tmpFilePath;
    }
1023424
public function loadFixtures()
    {
        $this->loadFixtureFiles();
        foreach ($this->fixture_files as $file) {
            $fixture_data = Yaml::parse(file_get_contents($file));
            // if nothing is specified, we use doctrine orm for persistence
            $persistence = isset($fixture_data['persistence']) ? $fixture_data['persistence'] : 'orm';

            $persister = $this->getPersister($persistence);
            $manager = $persister->getManagerForClass($fixture_data['model']);

            $fixture = $this->getFixtureClass($persistence);
            $fixture = new $fixture($fixture_data, $this, $file);
            $fixture->load($manager, func_get_args());
        }

        if (!is_null($this->acl_manager)) {
            foreach ($this->fixture_files as $file) {
                $fixture = new YamlAclFixture($file, $this);
                $fixture->load($this->acl_manager, func_get_args());
            }
        }
    }
952558
public function backup()
    {
        $this->command->out()->out('Backing up SQL...');

        $this->lastBackup = $sql = $this->getSQLExport();

        $config = Ioc::getConfig();
        $dir = $config->get('path.temp') . '/migration/sql-backup';

        Folder::create($dir);
        
        $this->rotate($dir);

        $file = $dir . '/sql-backup-' . gmdate('Y-m-d-H-i-s-') . uniqid() . '.sql';

        file_put_contents($file, $sql);

        $this->command->out()->out('SQL backup to: <info>' . $file . '</info>')->out();

        return true;
    }
601345
protected function moveSettings()
    {
        try {
            if (!$this->fs->exists($this->appRoot.'/sites/'.$this->directory.'/settings.php')) {
                $this->fs->copy(
                    $this->appRoot.'/sites/'.$this->uri.'/settings.php',
                    $this->appRoot.'/sites/'.$this->directory.'/settings.php'
                );
                $this->fs->remove($this->appRoot.'/sites/'.$this->uri.'/settings.php');
            }
        } catch (IOExceptionInterface $e) {
            $this->getIo()->error(
                sprintf(
                    $this->trans('commands.multisite.update.errors.copy-fail'),
                    $this->appRoot.'/sites/'.$this->explodeDirectory[0].'/settings.php',
                    $this->directory.'/settings.php'
                )
            );
            return 1;
        }
    }
784830
public function save()
    {
        $keys = array_keys($this->langstrings);
        sort($keys);

        $maxlen       = 0;
        $langPrefixes = array();
        foreach ($keys as $key) {
            $tokens = explode('.', $key);
            if (preg_match('/tl_layout\.[a-z]+\.css\./', $key)) {
                $tokens = array($tokens[0], $tokens[1] . '.' . $tokens[2], $tokens[3]);
            }
            $langPrefix = '$GLOBALS[\'TL_LANG\']';
            foreach ($tokens as $token) {
                $langPrefix .= '[\'' . $token . '\']';
            }

            $langPrefixes[$key] = $langPrefix;

            if (strlen($langPrefix) > $maxlen) {
                $maxlen = strlen($langPrefix);
            }
        }

        $buffer = $this->getHead() . PHP_EOL . PHP_EOL;
        foreach ($keys as $key) {
            $prefix  = $langPrefixes[$key];
            $buffer .= sprintf(
                '%s = %s;' . PHP_EOL,
                $prefix . str_repeat(' ', ($maxlen - strlen($prefix))),
                var_export($this->getValue($key), true)
            );
        }
        $buffer  .= PHP_EOL;
        $resource = fopen($this->filename, 'wb');
        fputs($resource, $buffer);

        fclose($resource);
    }
754494
public static function database()
    {
        $path = static::$root.'Database/';

        //--------------------------------------------------------
        // Calling drivers
        //--------------------------------------------------------

        $files = ['Driver', 'MysqlDriver'];
        $folder = $path.'Drivers'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling exporters
        //--------------------------------------------------------

        $files = ['Exporter', 'Importer'];
        $folder = $path.'InOut/Mysql/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Connectors
        //--------------------------------------------------------

        $files = ['MysqlConnector'];
        $folder = $path.'Connectors'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Exceptions
        //--------------------------------------------------------

        $files = ['ConnectorException', 'QueryException', 'SeedersEmptyException', 'DatabaseArgumentsException', 'DatabaseConnectionException', 'SchemaTableExistsException', 'SchemaTableNotExistException'];
        $folder = $path.'Exceptions'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Schemas
        //--------------------------------------------------------

        $files = ['Schema', 'MysqlSchema'];
        $folder = $path.'Schemas'.'/';

        self::call($files, $folder);

        //--------------------------------------------------------
        // Calling Database parts
        //--------------------------------------------------------

        $files = ['Migration', 'Seeder', 'DBTable', 'Query', 'Row', 'Database'];
        $folder = $path;

        self::call($files, $folder);
    }
1690
public function generate()
    {
        $tempPath = sys_get_temp_dir() . '/';

        // FastCGI fix for Windows machines, where temp path is not available to
        // PHP, and defaults to the unwritable system directory.  If the temp
        // path is pointing to the system directory, shift to the 'TEMP'
        // sub-folder, which should also exist, but actually be writable.
        if (IS_WIN && $tempPath == getenv("SystemRoot") . '/') {
            $tempPath = getenv("SystemRoot") . '/TEMP/';
        }

        $keyFile = $tempPath . md5(microtime(true));

        if (!is_dir($tempPath)) {
            mkdir($tempPath);
        }

        $return = array('private_key' => '', 'public_key' => '');

        $output = @shell_exec('ssh-keygen -t rsa -b 2048 -f '.$keyFile.' -N "" -C "deploy@phpci"');

        if (!empty($output)) {
            $pub = file_get_contents($keyFile . '.pub');
            $prv = file_get_contents($keyFile);

            if (!empty($pub)) {
                $return['public_key'] = $pub;
            }

            if (!empty($prv)) {
                $return['private_key'] = $prv;
            }
        }

        return $return;
    }
244142
protected function exportControllers()
    {
        foreach ($this->controllers as $pathIn => $pathOut) {
            if ($this->files->exists($controller = app_path('Http/Controllers/'.$pathOut))
                && ! $this->option('force')) {
                if (! $this->confirm("The [{$pathOut}] controller already exists. Do you want to overwrite it?")) {
                    continue;
                }
            }

            $this->files->put(
                $controller,
                $this->compileStub($this->files->get(__DIR__.'/stubs/make/controllers/'.$pathIn))
            );
        }
    }
1082508
def fixtures():
    """"""
    temp_path = os.path.join(os.path.dirname(__file__), 'temp')
    demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files')

    # Create location
    loc = Location(name='local', uri=temp_path, default=True)
    db.session.add(loc)
    db.session.commit()

    # Example files from the data folder
    demo_files = (
        'markdown.md',
        'csvfile.csv',
        'zipfile.zip',
        'jsonfile.json',
        'xmlfile.xml',
        'notebook.ipynb',
        'jpgfile.jpg',
        'pngfile.png',
    )

    rec_uuid = uuid4()
    provider = RecordIdProvider.create(object_type='rec', object_uuid=rec_uuid)
    data = {
        'pid_value': provider.pid.pid_value,
    }

    record = Record.create(data, id_=rec_uuid)
    bucket = Bucket.create()
    RecordsBuckets.create(record=record.model, bucket=bucket)

    # Add files to the record
    for f in demo_files:
        with open(os.path.join(demo_files_path, f), 'rb') as fp:
            record.files[f] = fp

    record.files.flush()
    record.commit()
    db.session.commit()
962109
protected function createMigration()
    {
        $migrationFile = base_path("/database/migrations") . "/" . date('Y_m_d_His')
            . "_create_settings_table.php";

        $output = $this->laravel->view->make('settings::generators.migration')->render();

        if (!file_exists($migrationFile) && $fs = fopen($migrationFile, 'x')) {
            fwrite($fs, $output);
            fclose($fs);

            return true;
        }

        return false;
    }
463302
public function export_dbconfig() {
        $cfg = new stdClass();
        $cfg->dbtype    = $this->get_dbtype();
        $cfg->dblibrary = $this->get_dblibrary();
        $cfg->dbhost    = $this->dbhost;
        $cfg->dbname    = $this->dbname;
        $cfg->dbuser    = $this->dbuser;
        $cfg->dbpass    = $this->dbpass;
        $cfg->prefix    = $this->prefix;
        if ($this->dboptions) {
            $cfg->dboptions = $this->dboptions;
        }

        return $cfg;
    }
521389
public function dumpDB($dumpName = 'test')
    {
        $this->setDumpName($dumpName);
        $tables = $this->getDbTables();

        foreach ($tables as $table) {
            $databaseHandler = $this->getDatabaseHandler();
            $directory = $this->getDumpDirectory();
            $databaseHandler->export($directory . '/' . $table . '.sql', array($table));
        }
        $this->saveChecksum($this->getTableChecksum($tables));
    }
398723
public function move()
    {
        // do any actions if files exists

        foreach ($this->files as $n => $file) {

            $filename = $file->getName();

            if (isset($this->rules['hash']) === true) {
                if (empty($this->rules['hash']) === true) {
                    $this->rules['hash'] = 'md5';
                }

                if (!is_string($this->rules['hash']) === true) {
                    $filename = call_user_func($this->rules['hash']) . '.' . $file->getExtension();
                } else {
                    $filename = $this->rules['hash']($filename) . '.' . $file->getExtension();
                }
            }

            if (isset($this->rules['sanitize']) === true) {
                $filename = Format::toLatin($filename, '', true);
            }

            if (isset($this->rules['directory'])) {
                $tmp = rtrim($this->rules['directory'], '/') . DIRECTORY_SEPARATOR . $filename;
            } else {
                $tmp = rtrim($this->rules['dynamic'], '/') . DIRECTORY_SEPARATOR . $filename;

            }

            // move file to target directory
            $isUploaded = $file->moveTo($tmp);

            if ($isUploaded === true) {
                $this->info[] = [
                    'path'      =>  $tmp,
                    'directory' => dirname($tmp),
                    'filename'  => $filename,
                    'size'      => $file->getSize(),
                    'extension' => $file->getExtension(),
                ];
            }
        }

        return $this->getInfo();
    }
425672
private function exportTables()
    {
        // Exporting tables one by one
        foreach ($this->tables as $table) {
            if ($this->matches($table, $this->dumpSettings['exclude-tables'])) {
                continue;
            }
            $this->getTableStructure($table);
            if (false === $this->dumpSettings['no-data']) { // don't break compatibility with old trigger
                $this->listValues($table);
            } elseif (true === $this->dumpSettings['no-data']
                 || $this->matches($table, $this->dumpSettings['no-data'])) {
                continue;
            } else {
                $this->listValues($table);
            }
        }
    }