Pop\Project\Install\Dbs::install PHP Метод

install() публичный статический Метод

Install the database
public static install ( string $dbname, array $db, string $dir, mixed $install = null, boolean $suppress = false, boolean $clear = true ) : array
$dbname string
$db array
$dir string
$install mixed
$suppress boolean
$clear boolean
Результат array
    public static function install($dbname, $db, $dir, $install = null, $suppress = false, $clear = true)
    {
        // Detect any SQL files
        $sqlFiles = array();
        if (is_string($dir) && file_exists($dir) && strtolower(substr($dir, -4)) == '.sql') {
            $sqlFiles[] = $dir;
        } else {
            $dir = new \Pop\File\Dir($dir, true);
            $files = $dir->getFiles();
            foreach ($files as $file) {
                if (strtolower(substr($file, -4)) == '.sql') {
                    $sqlFiles[] = $file;
                }
            }
        }
        // If SQLite, create folder and empty SQLite file
        if (stripos($db['type'], 'sqlite') !== false) {
            if (is_string($install) && file_exists($install)) {
                $db['database'] = $install;
            } else {
                // Define folders to create
                $folders = array($install->project->base, $install->project->base . '/module', $install->project->base . '/module/' . $install->project->name, $install->project->base . '/module/' . $install->project->name . '/data');
                // Create the folders
                foreach ($folders as $folder) {
                    if (!file_exists($folder)) {
                        mkdir($folder);
                    }
                }
                // Create empty SQLite file and make file and folder writable
                chmod($install->project->base . '/module/' . $install->project->name . '/data', 0777);
                touch($install->project->base . '/module/' . $install->project->name . '/data/' . $db['database']);
                chmod($install->project->base . '/module/' . $install->project->name . '/data/' . $db['database'], 0777);
                $db['database'] = $install->project->base . '/module/' . $install->project->name . '/data/' . $db['database'];
            }
        }
        // Create DB connection
        if (stripos($db['type'], 'Pdo_') !== false) {
            $type = 'Pdo';
            $db['type'] = strtolower(substr($db['type'], strpos($db['type'], '_') + 1));
        } else {
            $type = $db['type'];
        }
        $popdb = Db::factory($type, $db);
        // If there are SQL files, parse them and execute the SQL queries
        if (count($sqlFiles) > 0) {
            if (!$suppress) {
                echo 'SQL files found. Executing SQL queries...' . PHP_EOL;
            }
            // Clear database
            if ($clear) {
                $oldTables = $popdb->adapter()->getTables();
                if (count($oldTables) > 0) {
                    if ($type == 'Mysqli' || $db['type'] == 'mysql') {
                        $popdb->adapter()->query('SET foreign_key_checks = 0;');
                        foreach ($oldTables as $tab) {
                            $popdb->adapter()->query("DROP TABLE " . $tab);
                        }
                        $popdb->adapter()->query('SET foreign_key_checks = 1;');
                    } else {
                        if ($type == 'Pgsql' || $db['type'] == 'pgsql') {
                            foreach ($oldTables as $tab) {
                                $popdb->adapter()->query("DROP TABLE " . $tab . ' CASCADE');
                            }
                        } else {
                            foreach ($oldTables as $tab) {
                                $popdb->adapter()->query("DROP TABLE " . $tab);
                            }
                        }
                    }
                }
            }
            $prefix = isset($db['prefix']) ? $db['prefix'] : null;
            foreach ($sqlFiles as $sqlFile) {
                $sql = trim(file_get_contents($sqlFile));
                $explode = strpos($sql, ";\r\n") !== false ? ";\r\n" : ";\n";
                $statements = explode($explode, $sql);
                // Loop through each statement found and execute
                foreach ($statements as $s) {
                    if (!empty($s)) {
                        try {
                            $popdb->adapter()->query(str_replace('[{prefix}]', $prefix, trim($s)));
                        } catch (\Exception $e) {
                            echo $e->getMessage() . PHP_EOL . PHP_EOL;
                            exit(0);
                        }
                    }
                }
            }
        }
        // Get table info
        $tables = array();
        try {
            // Get Sqlite table info
            if (stripos($db['type'], 'sqlite') !== false) {
                $tablesFromDb = $popdb->adapter()->getTables();
                if (count($tablesFromDb) > 0) {
                    foreach ($tablesFromDb as $table) {
                        $tables[$table] = array('primaryId' => null, 'auto' => false);
                        $popdb->adapter()->query("PRAGMA table_info('" . $table . "')");
                        while (($row = $popdb->adapter()->fetch()) != false) {
                            if ($row['pk'] == 1) {
                                $tables[$table] = array('primaryId' => $row['name'], 'auto' => true);
                            }
                        }
                    }
                }
                // Else, get MySQL, PgSQL and SQLSrv table info
            } else {
                if (stripos($db['type'], 'pgsql') !== false) {
                    $schema = 'CATALOG';
                    $tableSchema = " AND TABLE_SCHEMA = 'public'";
                    $tableName = 'table_name';
                    $constraintName = 'constraint_name';
                    $columnName = 'column_name';
                } else {
                    if (stripos($db['type'], 'sqlsrv') !== false) {
                        $schema = 'CATALOG';
                        $tableSchema = null;
                        $tableName = 'TABLE_NAME';
                        $constraintName = 'CONSTRAINT_NAME';
                        $columnName = 'COLUMN_NAME';
                    } else {
                        $schema = 'SCHEMA';
                        $tableSchema = null;
                        $tableName = 'TABLE_NAME';
                        $constraintName = 'CONSTRAINT_NAME';
                        $columnName = 'COLUMN_NAME';
                    }
                }
                $popdb->adapter()->query("SELECT * FROM information_schema.TABLES WHERE TABLE_" . $schema . " = '" . $dbname . "'" . $tableSchema);
                // Get the auto increment info (mysql) and set table name
                while (($row = $popdb->adapter()->fetch()) != false) {
                    $auto = !empty($row['AUTO_INCREMENT']) ? true : false;
                    $tables[$row[$tableName]] = array('primaryId' => null, 'auto' => $auto);
                }
                // Get the primary key info
                foreach ($tables as $table => $value) {
                    // Pgsql sequence info for auto increment
                    if ($db['type'] == 'Pgsql') {
                        $popdb->adapter()->query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = '" . $table . "'");
                        $columns = array();
                        while (($row = $popdb->adapter()->fetch()) != false) {
                            $columns[] = $row['column_name'];
                        }
                        if (count($columns) > 0) {
                            foreach ($columns as $column) {
                                $popdb->adapter()->query("SELECT pg_get_serial_sequence('" . $table . "', '" . $column . "')");
                                while (($row = $popdb->adapter()->fetch()) != false) {
                                    if (!empty($row['pg_get_serial_sequence'])) {
                                        $idAry = explode('_', $row['pg_get_serial_sequence']);
                                        if (isset($idAry[1]) && in_array($idAry[1], $columns)) {
                                            $tables[$table]['auto'] = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Get primary id, if there is one
                    $ids = array();
                    $popdb->adapter()->query("SELECT * FROM information_schema.KEY_COLUMN_USAGE WHERE CONSTRAINT_" . $schema . " = '" . $dbname . "' AND TABLE_NAME = '" . $table . "'");
                    while (($row = $popdb->adapter()->fetch()) != false) {
                        if (isset($row[$constraintName])) {
                            if (!isset($tables[$table]['primaryId'])) {
                                $tables[$table]['primaryId'] = $row[$columnName];
                            } else {
                                if (!in_array($row[$columnName], $ids)) {
                                    $tables[$table]['primaryId'] .= '|' . $row[$columnName];
                                }
                            }
                            $ids[] = $row[$columnName];
                        }
                    }
                }
            }
            if (isset($db['prefix'])) {
                foreach ($tables as $table => $value) {
                    $tables[$table]['prefix'] = $db['prefix'];
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage() . PHP_EOL . PHP_EOL;
            exit(0);
        }
        return $tables;
    }

Usage Example

Пример #1
0
 /**
  * Install config method
  *
  * @param mixed  $form
  * @param string $docRoot
  * @return void
  */
 public function config($form, $docRoot = null)
 {
     if (null === $docRoot) {
         $docRoot = $_SERVER['DOCUMENT_ROOT'] . BASE_PATH;
     }
     // Get config file contents
     $cfgFile = new File($docRoot . '/config.php');
     $config = $cfgFile->read();
     // Get DB interface and type
     if (strpos($form->db_adapter, 'Pdo') !== false) {
         $dbInterface = 'Pdo';
         $dbType = strtolower(substr($form->db_adapter, strrpos($form->db_adapter, '\\') + 1));
     } else {
         $dbInterface = html_entity_decode($form->db_adapter, ENT_QUOTES, 'UTF-8');
         $dbType = null;
     }
     // If DB is SQLite
     if (strpos($form->db_adapter, 'Sqlite') !== false) {
         touch($docRoot . $form->content_path . '/.htphire.sqlite');
         $relativeDbName = "__DIR__ . '" . $form->content_path . '/.htphire.sqlite';
         $dbName = realpath($docRoot . $form->content_path . '/.htphire.sqlite');
         $dbUser = null;
         $dbPassword = null;
         $dbHost = null;
         $installFile = $dbName;
         chmod($dbName, 0777);
     } else {
         $relativeDbName = null;
         $dbName = $form->db_name;
         $dbUser = $form->db_username;
         $dbPassword = $form->db_password;
         $dbHost = $form->db_host;
         $installFile = null;
     }
     $dbPrefix = $form->db_prefix;
     // Set config values
     $config = str_replace("define('CONTENT_PATH', '/phire-content');", "define('CONTENT_PATH', '" . $form->content_path . "');", $config);
     $config = str_replace("define('APP_URI', '/phire');", "define('APP_URI', '" . $form->app_uri . "');", $config);
     $config = str_replace("define('DB_INTERFACE', '');", "define('DB_INTERFACE', '" . $dbInterface . "');", $config);
     $config = str_replace("define('DB_TYPE', '');", "define('DB_TYPE', '" . $dbType . "');", $config);
     $config = str_replace("define('DB_NAME', '');", "define('DB_NAME', " . (null !== $relativeDbName ? $relativeDbName : "'" . $dbName) . "');", $config);
     $config = str_replace("define('DB_USER', '');", "define('DB_USER', '" . $dbUser . "');", $config);
     $config = str_replace("define('DB_PASS', '');", "define('DB_PASS', '" . $dbPassword . "');", $config);
     $config = str_replace("define('DB_HOST', '');", "define('DB_HOST', '" . $dbHost . "');", $config);
     $config = str_replace("define('DB_PREFIX', '');", "define('DB_PREFIX', '" . $dbPrefix . "');", $config);
     $this->data['configWritable'] = is_writable($docRoot . '/config.php');
     if ($form instanceof \Pop\Form\Form) {
         // Store the config values in session in case config file is not writable.
         $sess = Session::getInstance();
         $sess->config = serialize(htmlentities($config, ENT_QUOTES, 'UTF-8'));
         $sess->app_uri = $form->app_uri;
     }
     if ($this->data['configWritable']) {
         $cfgFile->write($config)->save();
     }
     // Install the database
     $sqlFile = __DIR__ . '/../../../data/phire.' . str_replace(array('pdo\\', 'mysqli'), array('', 'mysql'), strtolower($form->db_adapter)) . '.sql';
     $db = array('database' => $dbName, 'username' => $dbUser, 'password' => $dbPassword, 'host' => $dbHost, 'prefix' => $dbPrefix, 'type' => str_replace('\\', '_', $form->db_adapter));
     Dbs::install($dbName, $db, $sqlFile, $installFile, true);
     if (stripos($form->db_adapter, 'Pdo\\') !== false) {
         $adapter = 'Pdo';
         $type = strtolower(substr($form->db_adapter, strpos($form->db_adapter, '\\') + 1));
     } else {
         $adapter = $form->db_adapter;
         $type = null;
     }
     // Set the default system config
     $db = Db::factory($adapter, array('database' => $dbName, 'username' => $dbUser, 'password' => $dbPassword, 'host' => $dbHost, 'type' => $type));
     // Get server info
     if (isset($_SERVER) && isset($_SERVER['SERVER_SOFTWARE'])) {
         $server = new Server();
         $os = $server->getOs() . ' (' . $server->getDistro() . ')';
         $srv = $server->getServer() . ' ' . $server->getServerVersion();
         $domain = $_SERVER['HTTP_HOST'];
         $doc = $_SERVER['DOCUMENT_ROOT'];
     } else {
         $os = '';
         $srv = '';
         $domain = '';
         $doc = '';
     }
     // Set the system configuration
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . \Phire\Project::VERSION . "' WHERE setting = 'system_version'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . $db->adapter()->escape($domain) . "' WHERE setting = 'system_domain'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . $db->adapter()->escape($doc) . "' WHERE setting = 'system_document_root'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . $db->adapter()->escape($os) . "' WHERE setting = 'server_operating_system'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . $db->adapter()->escape($srv) . "' WHERE setting = 'server_software'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . $db->adapter()->version() . "' WHERE setting = 'database_version'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . PHP_VERSION . "' WHERE setting = 'php_version'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . date('Y-m-d H:i:s') . "' WHERE setting = 'installed_on'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "config SET value = '" . $db->adapter()->escape($form->language) . "' WHERE setting = 'default_language'");
     $db->adapter()->query("UPDATE " . $db->adapter()->escape($dbPrefix) . "user_types SET password_encryption = '" . $db->adapter()->escape((int) $form->password_encryption) . "' WHERE id = 2001");
 }
All Usage Examples Of Pop\Project\Install\Dbs::install