/** * Register module * * @param Application $application * @throws Exception * @return Module */ public function register(Application $application) { parent::register($application); if (null !== $this->application->router()) { $this->application->router()->addControllerParams('*', ['application' => $this->application, 'request' => new Request(), 'response' => new Response()]); } if (!empty($this->application->config()['database']) && !empty($this->application->config()['database']['adapter'])) { $adapter = $this->application->config()['database']['adapter']; $options = ['database' => $this->application->config()['database']['database'], 'username' => $this->application->config()['database']['username'], 'password' => $this->application->config()['database']['password'], 'host' => $this->application->config()['database']['host'], 'type' => $this->application->config()['database']['type']]; $check = \Pop\Db\Db::check($adapter, $options); if (null !== $check) { throw new Exception('DB ' . $check); } $this->application->services()->set('database', ['call' => 'Pop\\Db\\Db::connect', 'params' => ['adapter' => $adapter, 'options' => $options]]); } if ($this->application->services()->isAvailable('database')) { Record::setDb($this->application->getService('database')); } if (isset($this->config['forms'])) { $this->application->mergeConfig(['forms' => $this->config['forms']]); } if (isset($this->config['resources'])) { $this->application->mergeConfig(['resources' => $this->config['resources']]); } $this->application->on('app.route.pre', 'App\\Event\\Ssl::check', 1000)->on('app.dispatch.pre', 'App\\Event\\Session::check', 1001)->on('app.dispatch.pre', 'App\\Event\\Acl::check', 1000); $this->initNav(); return $this; }
/** * Register module * * @param Application $application * @throws Exception * @return Module */ public function register(Application $application) { parent::register($application); // Add route params for the controllers if (null !== $this->application->router()) { $this->application->router()->addControllerParams('*', ['application' => $this->application, 'console' => new \Pop\Console\Console(120, ' ')]); } if (!empty($this->application->config()['database']) && !empty($this->application->config()['database']['adapter'])) { $adapter = $this->application->config()['database']['adapter']; $options = ['database' => $this->application->config()['database']['database'], 'username' => $this->application->config()['database']['username'], 'password' => $this->application->config()['database']['password'], 'host' => $this->application->config()['database']['host'], 'type' => $this->application->config()['database']['type']]; $check = \Pop\Db\Db::check($adapter, $options); if (null !== $check) { throw new Exception('DB ' . $check); } $this->application->services()->set('database', ['call' => 'Pop\\Db\\Db::connect', 'params' => ['adapter' => $adapter, 'options' => $options]]); } if ($this->application->services()->isAvailable('database')) { Record::setDb($this->application->getService('database')); } // Set up triggers to check the application session $this->application->on('app.route.pre', function () { if (isset($_SERVER['argv'][1])) { echo PHP_EOL . ' App Console' . PHP_EOL; echo ' ===========' . PHP_EOL . PHP_EOL; } }, 1000); $this->application->on('app.dispatch.post', function () { echo PHP_EOL; }, 1000); return $this; }
public function testAddFieldsFromTableException() { $this->setExpectedException('Pop\\Form\\Exception'); Users::setDb(Db::factory('Sqlite', array('database' => __DIR__ . '/../tmp/test.sqlite'))); $f = Fields::factory(array()); $f->addFieldsFromTable(array()); }
/** * Quote the value with single quotes * * @param string $value * @return string */ public function quote($value) { if ($value != '?' && substr($value, 0, 1) != ':' && preg_match('/^\\$\\d*\\d$/', $value) == 0 && !is_int($value) && !is_float($value)) { $value = "'" . $this->db->adapter()->escape($value) . "'"; } return $value; }
/** * Set the field values * * @param array $values * @return Install */ public function setFieldValues(array $values = null) { parent::setFieldValues($values); if ($_POST && !empty($this->db_adapter)) { // If not SQLite, check the DB parameters if (stripos($this->db_adapter, 'sqlite') === false) { $this->getElement('db_name')->addValidator(new Validator\NotEmpty(null, 'The database name is required.')); $this->getElement('db_username')->addValidator(new Validator\NotEmpty(null, 'The database username is required.')); $this->getElement('db_password')->addValidator(new Validator\NotEmpty(null, 'The database password is required.')); $this->getElement('db_host')->addValidator(new Validator\NotEmpty(null, 'The database host is required.')); } // Check the content path if (!$this->checkContentPath()) { $this->getElement('content_path')->addValidator(new Validator\NotEqual($this->content_path, wordwrap('The content directory (or subdirectories) either do not exist or are not writable.', 50, '<br />'))); } // Check the database credentials if ($this->isValid() && stripos($this->db_adapter, 'sqlite') === false) { if (stripos($this->db_adapter, 'pdo_') !== false) { $adapter = 'Pdo'; $type = str_replace('pdo_', '', strtolower($this->db_adapter)); } else { $adapter = ucfirst(strtolower($this->db_adapter)); $type = null; } $oldError = ini_get('error_reporting'); error_reporting(E_ERROR); $creds = ['database' => $this->db_name, 'username' => $this->db_username, 'password' => $this->db_password, 'host' => $this->db_host, 'type' => $type]; $dbCheck = Db::check($creds, $adapter); // If there is a DB error if (null != $dbCheck) { $this->getElement('db_adapter')->addValidator(new Validator\NotEqual($this->db_adapter, wordwrap($dbCheck, 50, '<br />'))); } else { $db = Db::connect($adapter, $creds); $version = $db->version(); $version = substr($version, strrpos($version, ' ') + 1); if (strpos($version, '-') !== false) { $version = substr($version, 0, strpos($version, '-')); } if (stripos($this->db_adapter, 'mysql') !== false && version_compare($version, '5.0') < 0) { $this->getElement('db_adapter')->addValidator(new Validator\NotEqual($this->db_adapter, 'The MySQL version must be 5.0 or greater.')); } else { if (stripos($this->db_adapter, 'pgsql') !== false && version_compare($version, '9.0') < 0) { $this->getElement('db_adapter')->addValidator(new Validator\NotEqual($this->db_adapter, 'The PostgreSQL version must be 9.0 or greater.')); } } } error_reporting($oldError); } } return $this; }
/** * Install Profile * * @param string $sql * @return void */ public function installProfile($sql) { Db::install($sql, ['database' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASS, 'host' => DB_HOST, 'prefix' => DB_PREFIX, 'type' => DB_TYPE], ucfirst(strtolower(DB_INTERFACE))); }
public function testDelete() { $s = new Sql(Db::factory('Sqlite', array('database' => __DIR__ . '/../tmp/test.sqlite')), 'users'); $s->delete()->orderBy('id')->limit(1); $this->assertEquals('DELETE FROM "users" ORDER BY "id" ASC LIMIT 1', $s->render(true)); }
public function testIsPdo() { $d = Db::factory('Pdo', array('database' => __DIR__ . '/../tmp/test.sqlite', 'type' => 'sqlite')); $this->assertTrue($d->isPdo()); }
/** * Composer install method * * @param \Composer\Script\Event $event * @throws \Pop\Db\Exception * @return void */ public static function install($event) { $console = new Console(100, ' '); if (!file_exists(__DIR__ . '/../../data')) { mkdir(__DIR__ . '/../../data'); } chmod(__DIR__ . '/../../data', 0777); if (!file_exists(__DIR__ . '/../../app/config/application.php')) { $console->write(); $console->write($console->colorize('A configuration file was not detected.', Console::BOLD_YELLOW)); $console->write(); $createConfig = $console->prompt('Would you like to create one and install the database? [Y/N] ', ['y', 'n']); if (strtolower($createConfig) == 'y') { $console->write(); // Configure application database $dbName = ''; $dbUser = ''; $dbPass = ''; $dbHost = ''; $dbPrefix = ''; $dbAdapters = self::getDbAdapters(); $adapters = array_keys($dbAdapters); $dbChoices = []; $dsn = null; $i = 1; foreach ($dbAdapters as $a) { $console->write($i . ': ' . $a); $dbChoices[] = $i; $i++; } $console->write(); $adapter = $console->prompt('Please select one of the above database adapters: ', $dbChoices); $console->write(); // If PDO if (strpos($adapters[$adapter - 1], 'pdo') !== false) { $console->write('1: mysql'); $console->write('2: pgsql'); $console->write('3: sqlite'); $console->write(); $dsn = $console->prompt('Please select the PDO DSN: ', [1, 2, 3]); $dbInterface = 'Pdo'; $dbType = str_replace('pdo_', '', strtolower($adapters[$adapter - 1])); $console->write(); } else { $dbInterface = ucfirst(strtolower($adapters[$adapter - 1])); $dbType = null; } // If SQLite if ($dsn == 3 || $adapters[$adapter - 1] == 'sqlite') { if (!file_exists(__DIR__ . '/../../data/.htpop.sqlite')) { touch(__DIR__ . '/../../data/.htpop.sqlite'); chmod(__DIR__ . '/../../data/.htpop.sqlite', 0777); } $dbName = __DIR__ . '/../../data/.htpop.sqlite'; $realDbName = "__DIR__ . '/../../data/.htpop.sqlite'"; $dbPrefix = $console->prompt('DB Table Prefix: [pop_] '); $console->write(); } else { $dbCheck = 1; while (null !== $dbCheck) { $dbName = $console->prompt('DB Name: '); $dbUser = $console->prompt('DB User: '******'DB Password: '******'DB Host: [localhost] '); $dbPrefix = $console->prompt('DB Table Prefix: [pop_] '); if ($dbHost == '') { $dbHost = 'localhost'; } $dbCheck = Db::check($dbInterface, ['database' => $dbName, 'username' => $dbUser, 'password' => $dbPass, 'host' => $dbHost, 'type' => $dbType]); if (null !== $dbCheck) { $console->write(); $console->write($console->colorize('Database configuration test failed. Please try again.', Console::BOLD_RED)); } else { $realDbName = "'" . $dbName . "'"; $console->write(); $console->write($console->colorize('Database configuration test passed.', Console::BOLD_GREEN)); } $console->write(); } } // Install database $sql = stripos($dbInterface, 'pdo') !== false ? __DIR__ . '/../data/pop.' . strtolower($dbType) . '.sql' : __DIR__ . '/../data/pop.' . strtolower($dbInterface) . '.sql'; if ($dbPrefix == '') { $dbPrefix = 'pop_'; } Db::install($sql, ['database' => $dbName, 'username' => $dbUser, 'password' => $dbPass, 'host' => $dbHost, 'prefix' => $dbPrefix, 'type' => $dbType], $dbInterface); // Write config file $config = str_replace(["define('DB_PREFIX', '');", "'adapter' => '',", "'database' => '',", "'username' => '',", "'password' => '',", "'host' => '',", "'type' => null"], ["define('DB_PREFIX', '" . $dbPrefix . "');", "'adapter' => '" . strtolower($dbInterface) . "',", "'database' => " . $realDbName . ",", "'username' => '" . $dbUser . "',", "'password' => '" . $dbPass . "',", "'host' => '" . $dbHost . "',", "'type' => '" . $dbType . "'"], file_get_contents(__DIR__ . '/../../app/config/application.orig.php')); file_put_contents(__DIR__ . '/../../app/config/application.php', $config); $console->write($console->colorize('Application configuration completed.', Console::BOLD_GREEN)); } } $console->write(); $console->write('Thank you for using Pop!'); $console->write(); }
public function testLoadRouter() { $p = new Project(new Config(array('databases' => array('testdb' => Db::factory('Sqlite', array('database' => __DIR__ . '/../tmp/test.sqlite'))), 'defaultDb' => 'testdb')), array('Test' => new Config(array('some' => 'thing')))); $p->loadRouter(new Router(array('Pop\\Mvc\\Controller' => new Controller()))); $this->assertInstanceOf('Pop\\Mvc\\Router', $p->router()); }
<?php /** * Phire CMS 2.0 Project Config File */ $config = array('base' => realpath(__DIR__ . '/../'), 'docroot' => realpath($_SERVER['DOCUMENT_ROOT'])); if (DB_INTERFACE != '' && DB_NAME != '') { $config['databases'] = array(DB_NAME => \Pop\Db\Db::factory(DB_INTERFACE, array('type' => DB_TYPE, 'database' => DB_NAME, 'host' => DB_HOST, 'username' => DB_USER, 'password' => DB_PASS))); $config['defaultDb'] = DB_NAME; // Merge any overriding project config values if (file_exists($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/extensions/modules/config/project.php')) { $cfg = (include $_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/extensions/modules/config/project.php'); if (is_array($cfg) && count($cfg) > 0) { $config = array_merge($config, $cfg); } } } return new \Pop\Config($config);
/** * Install command * * @return void */ protected function install() { if (!is_writable(PH_CLI_ROOT . '/config.php')) { echo ' The configuration file is not writable. Please make it writable before continuing.' . PHP_EOL . PHP_EOL; } else { // Install config file and database $input = array('language' => null, 'db_adapter' => null, 'db_name' => null, 'db_username' => null, 'db_password' => null, 'db_host' => defined('DB_HOST') && DB_HOST != '' ? DB_HOST : 'localhost', 'db_prefix' => defined('DB_PREFIX') && DB_HOST != '' ? DB_PREFIX : 'ph_', 'app_uri' => defined('APP_URI') ? APP_URI : '/phire', 'content_path' => defined('CONTENT_PATH') ? CONTENT_PATH : '/phire-content', 'password_encryption' => 4); $langs = \Pop\I18n\I18n::getLanguages(); $langKeys = array_keys($langs); $langsList = null; $i = 1; foreach ($langs as $key => $value) { $num = $i < 10 ? ' ' . $i : $i; $langsList .= ' ' . $num . ' : [' . $key . '] ' . $value . PHP_EOL; $i++; } $db = array('Mysqli', 'Pdo\\Mysql', 'Pdo\\Pgsql', 'Pdo\\Sqlite', 'Pgsql', 'Sqlite'); echo 'Installation' . PHP_EOL; echo '------------' . PHP_EOL; echo PHP_EOL; echo ' Select Language:' . PHP_EOL . PHP_EOL; echo $langsList . PHP_EOL; echo PHP_EOL; $inputLang = -1; while (!isset($langKeys[$inputLang])) { $inputLang = self::cliInput(' Enter Language # (Enter for English): '); if (empty($inputLang)) { $inputLang = 3; } else { $inputLang--; } } $input['language'] = $langKeys[$inputLang]; echo PHP_EOL . ' Select DB Adapter:' . PHP_EOL . PHP_EOL; foreach ($db as $key => $value) { echo ' ' . ($key + 1) . ' : ' . $value . PHP_EOL; } echo PHP_EOL; $inputDb = -1; while (!isset($db[$inputDb])) { $inputDb = self::cliInput(' Enter DB Adapter #: '); $inputDb--; } $input['db_adapter'] = $db[$inputDb]; if (stripos($input['db_adapter'], 'sqlite') === false) { $input['db_name'] = self::cliInput(' DB Name: '); $input['db_username'] = self::cliInput(' DB Username: '******'db_password'] = self::cliInput(' DB Password: '******' DB Host (Enter for \'' . $input['db_host'] . '\'): '); $input['db_host'] = empty($inputHost) ? 'localhost' : $inputHost; } $inputPrefix = self::cliInput(' DB Prefix (Enter for \'' . $input['db_prefix'] . '\'): '); $input['db_prefix'] = empty($inputPrefix) ? $input['db_prefix'] : $inputPrefix; $inputAppUri = self::cliInput(' Application URI (Enter for \'' . $input['app_uri'] . '\'): '); $input['app_uri'] = empty($inputAppUri) ? $input['app_uri'] : $inputAppUri; $inputContentPath = self::cliInput(' Content Path (Enter for \'' . $input['content_path'] . '\'): '); $input['content_path'] = empty($inputContentPath) ? $input['content_path'] : $inputContentPath; // Check the content directory if (!file_exists(PH_CLI_ROOT . $input['content_path'])) { echo PHP_EOL . ' The content directory does not exist.' . PHP_EOL . PHP_EOL; exit; } else { $checkDirs = Project::checkDirs(PH_CLI_ROOT . $input['content_path'], true); if (count($checkDirs) > 0) { echo PHP_EOL . ' The content directory (or subdirectories) are not writable.' . PHP_EOL . PHP_EOL; exit; } } echo PHP_EOL . ' ...Checking Database...'; if (stripos($input['db_adapter'], 'sqlite') === false) { $oldError = ini_get('error_reporting'); error_reporting(E_ERROR); $dbCheck = \Pop\Project\Install\Dbs::check(array('database' => $input['db_name'], 'username' => $input['db_username'], 'password' => $input['db_password'], 'host' => $input['db_host'], 'type' => str_replace('\\', '_', $input['db_adapter']))); error_reporting($oldError); if (null != $dbCheck) { echo PHP_EOL . PHP_EOL . ' ' . wordwrap($dbCheck, 70, PHP_EOL . ' ') . PHP_EOL . PHP_EOL; echo ' Please try again.' . PHP_EOL . PHP_EOL; exit; } } echo '..OK!' . PHP_EOL . ' ...Installing Database...'; $install = $install = new Model\Install(); $install->config(new \ArrayObject($input, \ArrayObject::ARRAY_AS_PROPS), realpath(PH_CLI_ROOT)); // Install initial user echo 'OK!' . PHP_EOL . PHP_EOL . ' Initial User Setup:' . PHP_EOL . PHP_EOL; $user = array('email' => null, 'username' => null, 'password' => null); $email = ''; $username = ''; $password = ''; $emailValidator = new \Pop\Validator\Email(); $usernameValidator = new \Pop\Validator\AlphaNumeric(); while (!$emailValidator->evaluate($email)) { $email = self::cliInput(' Enter User Email: '); } while (strlen($username) < 4 || !$usernameValidator->evaluate($username)) { $username = self::cliInput(' Enter Username (> 4 characters): '); } while (strlen($password) < 6) { $password = self::cliInput(' Enter Password (> 6 characters): '); } $user['email'] = $email; $user['username'] = $username; $user['password'] = $password; echo PHP_EOL . ' ...Saving Initial User...' . PHP_EOL . PHP_EOL; if (stripos($input['db_adapter'], 'Pdo') !== false) { $dbInterface = 'Pdo'; $dbType = substr($input['db_adapter'], strpos($input['db_adapter'], '\\') + 1); } else { $dbInterface = $input['db_adapter']; $dbType = null; } if (stripos($input['db_adapter'], 'sqlite') !== false) { $input['db_name'] = PH_CLI_ROOT . $input['content_path'] . '/.htphire.sqlite'; chmod(realpath(PH_CLI_ROOT . $input['content_path'] . '/.htphire.sqlite'), 0777); } $db = \Pop\Db\Db::factory($dbInterface, array('type' => $dbType, 'database' => $input['db_name'], 'host' => $input['db_host'], 'username' => $input['db_username'], 'password' => $input['db_password'])); $db->adapter()->query("INSERT INTO " . $input['db_prefix'] . "users (type_id, role_id, username, password, email, verified, failed_attempts, site_ids, created) VALUES (2001, 3001, '" . $user['username'] . "', '" . Model\User::encryptPassword($user['password'], 4) . "', '" . $user['email'] . "', 1, 0, '" . serialize(array(0)) . "', '" . date('Y-m-d H:i:s') . "')"); $db->adapter()->query('UPDATE ' . $input['db_prefix'] . 'config SET value = \'' . $user['email'] . '\' WHERE setting = \'system_email\''); } }
<?php /* * 2015 Lace Cart * * @author LaceCart Dev <*****@*****.**> * @copyright 2015 LaceCart Team * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of LaceCart Team */ use Pop\Db\Db as DB; use Pop\Db\Record as Adapter; return ['services' => ['session' => ['call' => 'Pop\\Web\\Session::getInstance'], 'db' => ['call' => function () use($config) { Adapter::setDb(DB::connect($config->database->adapter, ['database' => $config->database->database, 'username' => $config->database->username, 'password' => $config->database->password, 'host' => $config->database->host])); }], 'config' => ['call' => function () use($config) { return $config; }], 'nav' => ['call' => function () use($nav) { return $nav; }]]];
use Pop\Loader\Autoloader; use Pop\Auth\Auth; use Pop\Auth\Role; use Pop\Auth\Adapter\File; use Pop\Auth\Adapter\Table; use Pop\Db\Db; use Pop\Db\Record; // Require the library's autoloader. require_once __DIR__ . '/../../../src/Pop/Loader/Autoloader.php'; // Call the autoloader's bootstrap function. Autoloader::factory()->splAutoloadRegister(); // Test table class class Users extends Record { } Users::setDb(Db::factory('Sqlite', array('database' => __DIR__ . '/../tmp/test.sqlite'))); class AuthTest extends \PHPUnit_Framework_TestCase { public function testConstructor() { $this->assertInstanceOf('Pop\\Auth\\Auth', new Auth(new File(__DIR__ . '/../tmp/access.txt'))); $this->assertInstanceOf('Pop\\Auth\\Auth', Auth::factory(new File(__DIR__ . '/../tmp/access.txt'))); } public function testBadFile() { $this->setExpectedException('Pop\\Auth\\Adapter\\Exception'); $a = new Auth(new File(__DIR__ . '/../tmp/badaccess.txt')); } public function testIsValidWithFile() { $a = new Auth(new File(__DIR__ . '/../tmp/access.txt'));
/** * Constructor * * Instantiate the cache db object * * @param string $db * @param string $table * @param boolean $pdo * @throws Exception * @return \Pop\Cache\Adapter\Sqlite */ public function __construct($db, $table = 'pop_cache', $pdo = false) { $this->db = $db; $this->table = $table; $dir = dirname($this->db); // If the database file doesn't exist, create it. if (!file_exists($this->db)) { if (is_writable($dir)) { touch($db); } else { throw new Exception('Error: That cache db file and/or directory is not writable.'); } } // Make it writable. chmod($this->db, 0777); // Check the permissions, access the database and check for the cache table. if (!is_writable($dir) || !is_writable($this->db)) { throw new Exception('Error: That cache db file and/or directory is not writable.'); } $pdoDrivers = class_exists('Pdo') ? \PDO::getAvailableDrivers() : array(); if (!class_exists('Sqlite3') && !in_array('sqlite', $pdoDrivers)) { throw new Exception('Error: SQLite is not available.'); } else { if ($pdo && !in_array('sqlite', $pdoDrivers)) { $pdo = false; } else { if (!$pdo && !class_exists('Sqlite3')) { $pdo = true; } } } if ($pdo) { $this->sqlite = new \Pop\Db\Sql(\Pop\Db\Db::factory('Pdo', array('type' => 'sqlite', 'database' => $this->db)), $table); } else { $this->sqlite = new \Pop\Db\Sql(\Pop\Db\Db::factory('Sqlite', array('database' => $this->db)), $table); } // If the cache table doesn't exist, create it. if (!in_array($this->table, $this->sqlite->adapter()->getTables())) { $this->sqlite->adapter()->query('CREATE TABLE IF NOT EXISTS "' . $this->table . '" ("id" VARCHAR PRIMARY KEY NOT NULL UNIQUE, "value" BLOB, "time" INTEGER)'); } }
/** * Finalize module install * * @param string $module * @param string $folder * @param string $modulesPath * @param \Pop\Service\Locator $services * @return void */ protected function finalizeInstall($module, $folder, $modulesPath, $services) { // Get module config and module info from config file $config = (include $modulesPath . '/' . $folder . '/config/module.php'); $info = $this->getInfo(file_get_contents($modulesPath . '/' . $folder . '/config/module.php')); $name = key($config); $descName = ''; if (isset($info['name'])) { $descName = $info['name']; } else { if (isset($info['Name'])) { $descName = $info['Name']; } else { if (isset($info['NAME'])) { $descName = $info['NAME']; } else { if (isset($info['module name'])) { $descName = $info['module name']; } else { if (isset($info['Module Name'])) { $descName = $info['Module Name']; } else { if (isset($info['MODULE NAME'])) { $descName = $info['MODULE NAME']; } } } } } } $info['Desc Name'] = $descName; if (isset($info['version'])) { $version = $info['version']; } else { if (isset($info['Version'])) { $version = $info['Version']; } else { if (isset($info['VERSION'])) { $version = $info['VERSION']; } else { $version = 'N/A'; } } } // Get SQL, if exists $sqlType = strtolower(DB_INTERFACE == 'pdo' ? DB_TYPE : DB_INTERFACE); $sqlFile = $modulesPath . '/' . $folder . '/data/' . $name . '.' . $sqlType . '.sql'; if (!file_exists($sqlFile)) { $sqlFile = null; } $tables = null !== $sqlFile ? $this->getTables(file_get_contents($sqlFile)) : []; // Save module in the database $mod = new Table\Modules(['file' => $module, 'folder' => $folder, 'name' => $name, 'prefix' => isset($config[$name]['prefix']) ? $config[$name]['prefix'] : '', 'version' => $version, 'active' => 1, 'order' => (int) Table\Modules::findAll()->count() + 1, 'assets' => serialize(['tables' => $tables, 'info' => $info]), 'installed_on' => date('Y-m-d H:i:s')]); $mod->save(); $this->sendStats($name, $version); // Execute any SQL that came with the module if (null !== $sqlFile) { Db::install($sqlFile, ['database' => DB_NAME, 'username' => DB_USER, 'password' => DB_PASS, 'host' => DB_HOST, 'prefix' => DB_PREFIX, 'type' => DB_TYPE], ucfirst(strtolower(DB_INTERFACE))); } // Run any install functions if (isset($config[$name]) && isset($config[$name]['install']) && !empty($config[$name]['install'])) { call_user_func_array($config[$name]['install'], [$services]); } }
/** * Install the database * * @param string $dbname * @param array $db * @param string $dir * @param mixed $install * @param boolean $suppress * @param boolean $clear * @throws Exception * @return 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; }
/** * Set the field values * * @param array $values * @param array $filters * @return \Pop\Form\Form */ public function setFieldValues(array $values = null, $filters = null) { parent::setFieldValues($values, $filters); if ($_POST) { // Check the content directory if (!file_exists($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $this->content_path)) { $this->getElement('content_path')->addValidator(new Validator\NotEqual($this->content_path, $this->i18n->__('The content directory does not exist.'))); } else { $checkDirs = \Phire\Project::checkDirs($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . $this->content_path, true); if (count($checkDirs) > 0) { $this->getElement('content_path')->addValidator(new Validator\NotEqual($this->content_path, $this->i18n->__('The content directory (or subdirectories) are not writable.'))); } } // If not SQLite, check the DB parameters if (strpos($this->db_adapter, 'Sqlite') === false) { $this->getElement('db_name')->addValidator(new Validator\NotEmpty(null, $this->i18n->__('The database name is required.'))); $this->getElement('db_username')->addValidator(new Validator\NotEmpty(null, $this->i18n->__('The database username is required.'))); $this->getElement('db_password')->addValidator(new Validator\NotEmpty(null, $this->i18n->__('The database password is required.'))); $this->getElement('db_host')->addValidator(new Validator\NotEmpty(null, $this->i18n->__('The database host is required.'))); } // Check the database credentials if ($this->isValid()) { $oldError = ini_get('error_reporting'); error_reporting(E_ERROR); $dbCheck = Dbs::check(array('database' => $this->db_name, 'username' => $this->db_username, 'password' => $this->db_password, 'host' => $this->db_host, 'type' => str_replace('\\', '_', $this->db_adapter))); // If there is a DB error if (null != $dbCheck) { $this->getElement('db_adapter')->addValidator(new Validator\NotEqual($this->db_adapter, wordwrap($dbCheck, 50, '<br />'))); } else { // Check the database version if (strpos($this->db_adapter, 'Sqlite') === false) { $adapter = stripos($this->db_adapter, 'Pdo\\') !== false ? str_replace('Pdo\\', '', $this->db_adapter) : $this->db_adapter; $db = Db::factory($adapter, array('database' => $this->db_name, 'username' => $this->db_username, 'password' => $this->db_password, 'host' => $this->db_host, 'type' => strtolower(str_replace('Pdo\\', '', $this->db_adapter)))); $version = $db->adapter()->version(); $version = substr($version, strrpos($version, ' ') + 1); if (strpos($version, '-') !== false) { $version = substr($version, 0, strpos($version, '-')); } if (stripos($this->db_adapter, 'Mysql') !== false) { $dbVerKey = 'Mysql'; } else { if (stripos($this->db_adapter, 'Pgsql') !== false) { $dbVerKey = 'Pgsql'; } else { $dbVerKey = null; } } if (null !== $dbVerKey && version_compare($version, self::$dbVersions[$dbVerKey]) < 0) { $this->getElement('db_adapter')->addValidator(new Validator\NotEqual($this->db_adapter, wordwrap($this->i18n->__('The %1 database version must be %2 or greater. (%3 detected.)', array($dbVerKey, self::$dbVersions[$dbVerKey], $version)), 45, '<br />'))); } } } error_reporting($oldError); } } return $this; }
<?php require_once '../../bootstrap.php'; use Pop\Db\Db; use Pop\Db\Sql; try { // Define DB credentials $creds = array('database' => 'helloworld', 'host' => 'localhost', 'username' => 'hello', 'password' => '12world34'); $db = Db::factory('Mysqli', $creds); // Create a non-prepared statement, escaping the value $sql = new Sql($db, 'users'); $sql->select()->where()->greaterThanOrEqualTo('id', $db->adapter()->escape(5)); $sql->select()->limit(4)->offset(1); echo $sql . '<br />' . PHP_EOL; $db->adapter()->query($sql); while ($row = $db->adapter()->fetch()) { print_r($row); } } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL . PHP_EOL; }
public function testGetDefaultDb() { Record::setDb(Db::factory('Sqlite', array('database' => __DIR__ . '/../tmp/test.sqlite')), true); $this->assertInstanceOf('Pop\\Db\\Db', Record::getDb()); }
<?php require_once '../../bootstrap.php'; use Pop\Db; /* * Placing a class here is highly unorthodox. * This is just for example purposes only. */ class Users extends Db\Record { } try { // Define DB credentials $db = Db\Db::factory('Mysqli', array('database' => 'helloworld', 'host' => 'localhost', 'username' => 'hello', 'password' => '12world34')); Users::setDb($db); $fields = array('username' => 'newuser2', 'password' => '123456', 'email' => '*****@*****.**', 'access' => 'editor'); $user = new Users($fields); $user->save(); print_r($user); } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL . PHP_EOL; }
public function testIsNotNull() { $p = new Predicate(Sql::factory(Db::factory('Sqlite', array('database' => __DIR__ . '/../tmp/test.sqlite')), 'users')); $p->isNotNull('email'); $this->assertEquals('("email" IS NOT NULL)', (string) $p); }
/** * 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"); }
<?php require_once '../../bootstrap.php'; use Pop\Db\Db; use Pop\Db\Record; use Pop\Log; use Pop\Log\Writer; class Logs extends Record { } Logs::setDb(Db::factory('Sqlite', array('database' => '../tmp/log.sqlite'))); try { $logger = new Log\Logger(new Writer\Db(new Logs())); $logger->addWriter(new Writer\File('../tmp/app.log')); $logger->emerg('Yo stuff is whack man!')->info("Here's some, yo, you know, info stuff"); echo 'Done.'; } catch (\Exception $e) { echo $e->getMessage(); }