/** * Connects to a database. * @return void * @throws DibiException */ public function connect(array &$config) { DibiConnection::alias($config, 'database', 'file'); $this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U'; $this->fmtDateTime = isset($config['formatDateTime']) ? $config['formatDateTime'] : 'U'; if (isset($config['resource']) && $config['resource'] instanceof SQLite3) { $this->connection = $config['resource']; } else { try { $this->connection = new SQLite3($config['database']); } catch (Exception $e) { throw new DibiDriverException($e->getMessage(), $e->getCode()); } } $this->dbcharset = empty($config['dbcharset']) ? 'UTF-8' : $config['dbcharset']; $this->charset = empty($config['charset']) ? 'UTF-8' : $config['charset']; if (strcasecmp($this->dbcharset, $this->charset) === 0) { $this->dbcharset = $this->charset = NULL; } // enable foreign keys support (defaultly disabled; if disabled then foreign key constraints are not enforced) $version = SQLite3::version(); if ($version['versionNumber'] >= '3006019') { $this->query("PRAGMA foreign_keys = ON"); } }
protected function createComponentGrid($name) { $grid = new Grid($this, $name); $fluent = $this->database->select('u.*, c.title AS country')->from('[user] u')->join('[country] c')->on('u.country_code = c.code'); $grid->model = $fluent; $grid->addColumnText('firstname', 'Firstname')->setFilterText()->setSuggestion(); $grid->addColumnText('surname', 'Surname')->setSortable()->setFilterText()->setSuggestion(); $grid->addColumnText('gender', 'Gender')->setSortable()->cellPrototype->class[] = 'center'; $grid->addColumnDate('birthday', 'Birthday', \Grido\Components\Columns\Date::FORMAT_TEXT)->setSortable()->setFilterDate()->setCondition($grid->birthdayFilterCondition); $grid->getColumn('birthday')->cellPrototype->class[] = 'center'; $customRender = function ($item) { $baseUri = $this->getBaseUri(); $img = Html::el('img')->src("{$baseUri}/img/flags/{$item->country_code}.gif"); return "{$img} {$item->country}"; }; $grid->addColumnText('country', 'Country')->setSortable()->setCustomRender($customRender)->setFilterText()->setColumn('c.title')->setSuggestion('title'); $grid->addColumnText('card', 'Card')->setSortable()->setColumn('cctype')->setReplacement(array('MasterCard' => Html::el('b')->setText('MasterCard')))->cellPrototype->class[] = 'center'; $grid->addColumnEmail('emailaddress', 'Email')->setSortable()->setFilterText(); $grid->getColumn('emailaddress')->cellPrototype->class[] = 'center'; $grid->addColumnText('centimeters', 'Height')->setSortable()->setFilterNumber(); $grid->getColumn('centimeters')->cellPrototype->class[] = 'center'; $grid->addFilterSelect('gender', 'Gender', array('' => '', 'female' => 'female', 'male' => 'male')); $grid->addFilterSelect('card', 'Card', array('' => '', 'MasterCard' => 'MasterCard', 'Visa' => 'Visa'))->setColumn('cctype'); $grid->addFilterCheck('preferred', 'Only preferred girls :)')->setCondition(array(TRUE => array(array('gender', 'AND', 'centimeters'), array('= ?', '>= ?'), array('female', 170)))); $grid->addActionHref('edit', 'Edit')->setIcon('pencil'); $grid->addActionHref('delete', 'Delete')->setIcon('trash')->setConfirm(function ($item) { return "Are you sure you want to delete {$item->firstname} {$item->surname}?"; }); $operation = array('print' => 'Print', 'delete' => 'Delete'); $grid->setOperation($operation, $this->handleOperations)->setConfirm('delete', 'Are you sure you want to delete %i items?'); $grid->filterRenderType = $this->filterRenderType; $grid->setExport(); return $grid; }
public function testLazyHasValue() { $id = $this->db->select("max(id)")->from("pages")->fetchSingle(); $page = new Page($id); $this->assertTrue($page->hasValue("name")); $this->assertFalse($page->hasValue("nesmysl")); }
/** * @return int */ public function count() { if ($this->count === NULL) { $this->count = $this->connection->query(' SELECT COUNT(*) FROM', $this->sql)->fetchSingle(); } return $this->count; }
/** * @param string $username * @param string $password * @param string $databaseName */ public function createDatabase($username, $password, $databaseName) { //exit(var_dump('GRANT ALL PRIVILEGES ON '.$databaseName.'.* TO "'.$username.'"@"%" IDENTIFIED BY "'.$password.'" WITH GRANT OPTION')); $this->connection->nativeQuery('GRANT ALL PRIVILEGES ON *.* TO "' . $username . '"@"%" IDENTIFIED BY "' . $password . '" WITH GRANT OPTION'); $this->connection->nativeQuery('CREATE DATABASE ' . $databaseName); $this->connection->nativeQuery("GRANT ALL PRIVILEGES ON " . $databaseName . ".* TO '" . $username . "'@'%' IDENTIFIED BY '" . $password . "' WITH GRANT OPTION"); //TODO use $this->connection->driver->escape() }
/** * Get valid refresh token * @param string $refreshToken * @return IRefreshToken|NULL */ public function getValidRefreshToken($refreshToken) { $row = $this->context->select('*')->from($this->getTable())->where('refresh_token = %s', $refreshToken)->where('TIMEDIFF(expires_at, NOW()) >= 0')->fetch(); if (!$row) { return NULL; } return new RefreshToken($row['refresh_token'], new \DateTime($row['expires_at']), $row['client_id'], $row['user_id']); }
/** * Can client use given grant type * @param string $clientId * @param string $grantType * @return bool */ public function canUseGrantType($clientId, $grantType) { $result = $this->context->query(' SELECT g.name FROM oauth_client_grant AS cg RIGHT JOIN oauth_grant AS g ON cg.grant_id = cg.grant_id AND g.name = %s WHERE cg.client_id = %i ', $grantType, $clientId); return (bool) $result->fetch(); }
/** * Validate authorization code * @param string $authorizationCode * @return IAuthorizationCode */ public function getValidAuthorizationCode($authorizationCode) { /** @var ActiveRow $row */ $row = $this->context->select('*')->from($this->getTable())->where('authorization_code = %s', $authorizationCode)->where('TIMEDIFF(expires_at, NOW()) >= 0')->fetch(); if (!$row) { return NULL; } $scopes = $this->context->select('*')->from($this->getScopeTable())->where('authorization_code = %s', $authorizationCode)->fetchPairs('scope_name'); return new AuthorizationCode($row['authorization_code'], new \DateTime($row['expires_at']), $row['client_id'], $row['user_id'], array_keys($scopes)); }
public function __construct(\DibiConnection $db) { //static roles $this->addRole('guest'); $this->addRole('authenticated', 'guest'); $this->addRole('manager', 'authenticated'); $this->addRole('administrator', 'manager'); $this->addRole('student', 'authenticated'); $this->addRole('teacher', 'authenticated'); //dynamic roles $groups = $db->query("SELECT * FROM `group`")->fetchAll(); foreach ($groups as $group) { if (!$this->hasRole($group->role_name)) { $this->addRole($group->role_name, 'authenticated'); } } // resources $this->addResource('Front:Homepage'); $this->addResource('Front:Files'); $this->addResource('Service:Sign'); $this->addResource('Service:Error'); $this->addResource('Dashboard:Homepage'); $this->addResource('Dashboard:Users'); $this->addResource('Dashboard:Groups'); $this->addResource('Dashboard:My'); $this->addResource('Dashboard:Files'); $this->addResource('Works:Homepage'); $this->addResource('Works:Sets'); $this->addResource('Works:Ideas'); $this->addResource('Works:Assignments'); $this->addResource('School:Homepage'); $this->addResource('School:Classes'); $this->addResource('School:Students'); $this->addResource('School:Teachers'); $this->addResource('School:Subjects'); $this->addResource('School:Groups'); $this->addResource('School:Import'); $this->addResource('Delivery:Homepage'); $this->addResource('Practice:Homepage'); $this->addResource('Activity:Homepage'); // privileges $this->allow('guest', array('Front:Homepage', 'Service:Sign', "Service:Error"), Permission::ALL); $this->allow('authenticated', array('Dashboard:My'), Permission::ALL); $this->allow('authenticated', array('Dashboard:Groups'), Permission::ALL); $this->allow('authenticated', array('Dashboard:Files'), Permission::ALL); $this->allow('authenticated', array('Dashboard:Homepage'), array('default')); $this->allow('student', array('Works:Homepage'), array('default')); $this->allow('teacher', array('Works:Homepage'), Permission::ALL); $this->allow('student', array('Works:Ideas'), array('default', 'add', 'id', 'edit', 'delete', 'clone')); $this->allow('teacher', array('Works:Ideas'), Permission::ALL); $this->allow('student', array('Works:Assignments'), array('default', 'application')); $this->allow('teacher', array('Works:Assignments'), array('default', 'add', 'id', 'edit', 'delete', 'print')); $this->allow('teacher', array('School:Homepage', 'School:Teachers', 'School:Classes', 'School:Students', 'School:Subjects', 'School:Groups'), Permission::ALL); $this->allow('administrator', Permission::ALL, Permission::ALL); }
public static function createConnection(DI\Container $container) { $dibiConnection = new \DibiConnection($container->params['database']); $dibiConnection->query('SET NAMES UTF8'); $substitutions = array('core' => 'cms_', 'vd' => 'cms_vd_', 'c' => 'cgf_', 'media' => 'media_'); foreach ($substitutions as $sub => $prefix) { $dibiConnection->getSubstitutes()->{$sub} = $prefix; } // $profiler = new \DibiProfiler(); // $dibiConnection->setProfiler($profiler); // $dibiConnection->setFile(APP_DIR.'/../log/dibi.log'); return $dibiConnection; }
public function testInsert() { $page = new Page(array("name" => "Insert test", "description" => "Insert record", "text" => "Insert record into database")); $page->allowed = true; $this->assertEquals(Ormion\Record::STATE_NEW, $page->getState()); $this->object->insert($page); $this->assertEquals(Ormion\Record::STATE_EXISTING, $page->getState()); $this->assertType("int", $page->id); $res = $this->db->select("*")->from("pages")->where("id = %i", $page->id)->fetch(); $this->assertEquals("Insert test", $res->name); $this->assertEquals("Insert record", $res->description); $this->assertEquals(array(), $page->getModified()); }
protected function setup() { parent::setup(); // Load from DB $rules = $this->db->query("SELECT * FROM %n", $this->tableName); foreach ($rules as $rule) { // If querying the compound name, ensure it exists if ($rule->type == 'allow') { $this->allow($rule->role, $rule->resource, $rule->privilege); } else { $this->deny($rule->role, $rule->resource, $rule->privilege); } } }
/** * @inheritDoc */ public function authenticate($clientId, $clientSecret = NULL) { $clientData = $this->dbConnection->query("SELECT * FROM %n", $this->tableName, "WHERE [clientId] = %s", $clientId)->fetch(); if ($clientData === FALSE) { return FALSE; } // Check client secret if ($clientData->secret !== NULL || $clientSecret !== NULL) { if (!$this->hasher->checkPassword($clientSecret, $clientData->secret)) { return FALSE; } } return new Client($clientData->clientId); }
/** * Constractor creates connection and checks/creates tables stucture */ public function __construct() { $dibiConfig = dibi::getConnection()->getConfig(); $dbname = isset($dibiConfig['dbname']) ? $dibiConfig['dbname'] : $dibiConfig['database']; $config = array('driver' => 'sqlite', 'profiler' => Environment::getConfig('perform')->storage_profiler, 'database' => realpath(Environment::getConfig('perform')->modelCache) . '/' . $dbname . '-storage.sdb'); parent::__construct($config, 'storage'); if (!$this->getDatabaseInfo()->hasTable('fields')) { $this->query('CREATE TABLE [fields] ([id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL, [table] VARCHAR(50) NOT NULL, [hash] VARCHAR(32) NOT NULL, [type] VARCHAR(50)); CREATE UNIQUE INDEX [fields_idx] on [fields] ( [name], [table]);'); } if (!$this->getDatabaseInfo()->hasTable('tables')) { $this->query('CREATE TABLE [tables] ( [id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL UNIQUE, [hash] VARCHAR(32) NOT NULL);'); } if (!$this->getDatabaseInfo()->hasTable('views')) { $this->query('CREATE TABLE [views] ( [id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL UNIQUE, [hash] VARCHAR(32) NOT NULL);'); } if (!$this->getDatabaseInfo()->hasTable('indexes')) { $this->query('CREATE TABLE [indexes] ([id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL, [table] VARCHAR(50) NOT NULL, [hash] VARCHAR(32) NOT NULL, [unique] BOOLEAN); CREATE UNIQUE INDEX [indexes_idx] on [indexes] ( [name], [table]);'); } }
/** * Connects to a database. * @return void * @throws DibiException */ public function connect(array &$config) { DibiConnection::alias($config, 'database', 'file'); $this->fmtDate = isset($config['formatDate']) ? $config['formatDate'] : 'U'; $this->fmtDateTime = isset($config['formatDateTime']) ? $config['formatDateTime'] : 'U'; $errorMsg = ''; if (isset($config['resource'])) { $this->connection = $config['resource']; } elseif (empty($config['persistent'])) { $this->connection = @sqlite_open($config['database'], 0666, $errorMsg); // intentionally @ } else { $this->connection = @sqlite_popen($config['database'], 0666, $errorMsg); // intentionally @ } if (!$this->connection) { throw new DibiDriverException($errorMsg); } $this->buffered = empty($config['unbuffered']); $this->dbcharset = empty($config['dbcharset']) ? 'UTF-8' : $config['dbcharset']; $this->charset = empty($config['charset']) ? 'UTF-8' : $config['charset']; if (strcasecmp($this->dbcharset, $this->charset) === 0) { $this->dbcharset = $this->charset = NULL; } }
/** * Connects to a database. * @return void * @throws DibiException */ public function connect(array &$config) { DibiConnection::alias($config, 'options'); DibiConnection::alias($config, 'database'); if (isset($config['resource'])) { $this->connection = $config['resource']; } else { // default values if (!isset($config['username'])) { $config['username'] = ini_get('mysqli.default_user'); } if (!isset($config['password'])) { $config['password'] = ini_get('mysqli.default_pw'); } if (!isset($config['socket'])) { $config['socket'] = ini_get('mysqli.default_socket'); } if (!isset($config['port'])) { $config['port'] = NULL; } if (!isset($config['host'])) { $host = ini_get('mysqli.default_host'); if ($host) { $config['host'] = $host; $config['port'] = ini_get('mysqli.default_port'); } else { $config['host'] = NULL; $config['port'] = NULL; } } $this->connection = mysqli_init(); @mysqli_real_connect($this->connection, $config['host'], $config['username'], $config['password'], $config['database'], $config['port'], $config['socket'], $config['options']); // intentionally @ if ($errno = mysqli_connect_errno()) { throw new DibiDriverException(mysqli_connect_error(), $errno); } } if (isset($config['charset'])) { $ok = FALSE; if (version_compare(PHP_VERSION, '5.1.5', '>=')) { // affects the character set used by mysql_real_escape_string() (was added in MySQL 5.0.7 and PHP 5.0.5, fixed in PHP 5.1.5) $ok = @mysqli_set_charset($this->connection, $config['charset']); // intentionally @ } if (!$ok) { $ok = @mysqli_query($this->connection, "SET NAMES '{$config['charset']}'"); // intentionally @ if (!$ok) { throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection)); } } } if (isset($config['sqlmode'])) { if (!@mysqli_query($this->connection, "SET sql_mode='{$config['sqlmode']}'")) { // intentionally @ throw new DibiDriverException(mysqli_error($this->connection), mysqli_errno($this->connection)); } } $this->buffered = empty($config['unbuffered']); }
/** * Returns the number of rows in a given data source. * @return int */ public function getTotalCount() { if ($this->totalCount === NULL) { $this->totalCount = (int) $this->connection->nativeQuery('SELECT COUNT(*) FROM ' . $this->sql)->fetchSingle(); } return $this->totalCount; }
/** * Run after smoke test * * Drop test database. * * @return NULL */ private function finishSmokeTest() { if (!$this->smokeTest) { return; } $this->dibi->query('DROP DATABASE IF EXISTS %n;', $this->databaseName); }
/** * Connects to a database. * @return void * @throws DibiException */ public function connect(array &$config) { DibiConnection::alias($config, 'username', 'user'); DibiConnection::alias($config, 'password', 'pass'); if (isset($config['resource'])) { $this->connection = $config['resource']; } else { // default values if (!isset($config['username'])) { $config['username'] = ini_get('odbc.default_user'); } if (!isset($config['password'])) { $config['password'] = ini_get('odbc.default_pw'); } if (!isset($config['dsn'])) { $config['dsn'] = ini_get('odbc.default_db'); } if (empty($config['persistent'])) { $this->connection = @odbc_connect($config['dsn'], $config['username'], $config['password']); // intentionally @ } else { $this->connection = @odbc_pconnect($config['dsn'], $config['username'], $config['password']); // intentionally @ } } if (!is_resource($this->connection)) { throw new DibiDriverException(odbc_errormsg() . ' ' . odbc_error()); } }
/** * Returns SQL query. * @return string */ public final function __toString() { try { return $this->connection->translate($this->_export()); } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_ERROR); } }
public function match(\Nette\Http\IRequest $request) { /** * @var $appRequest \Nette\Application\Request */ $appRequest = parent::match($request); if (!isset($appRequest->parameters['id'])) { return NULL; } if (!is_numeric($appRequest->parameters['id'])) { $page = $this->database->query("SELECT contentId FROM route WHERE url = ?", $appRequest->parameters['id'])->fetch(); if ($page == NULL) { return NULL; } $appRequest->parameters['id'] = $page->contentId; } return $appRequest; }
public function addContact($contact) { try { $this->database->query('INSERT INTO [' . self::TABLE_NAME_CONTACT . ']', [self::COLUMN_ID => $contact['id'], self::COLUMN_EMAIL => $contact['email']]); return $this->database->getInsertId(); } catch (Nette\Database\DriverException $e) { throw new \Nette\Database\DriverException(); } }
public function testSet() { $page = Page::findByName("Clanek"); $tags = Tag::findAll(); $page->Tags = $tags; $page->save(); $tagIds = array_map(function ($record) { return $record->id; }, $tags->toArray()); $q = $this->db->select("*")->from("connections")->execute(); $q->detectTypes(); $conn = $q->fetchAll(); $this->assertSame(3, count($conn)); foreach ($conn as $row) { $this->assertSame($page->id, $row->pageId); $this->assertTrue(in_array($row->tagId, $tagIds)); } }
/** * Helper function for easy overriding of DB query * * @return DibiRow|FALSE */ protected function fetchUserData(array $credentials) { $ds = $this->db->select('*')->from($this->tableName); if (Strings::contains($credentials[self::USERNAME], '@')) { $ds->where('%n = %s', $this->fieldName[self::EMAIL], $credentials[self::USERNAME]); } else { $ds->where('%n = %s', $this->fieldName[self::USERNAME], $credentials[self::USERNAME]); } return $ds->fetch(); }
public function createUpdateOne($table, $primaryColumn, $primaryValue, array $values) { $type = is_object($primaryValue) ? get_class($primaryValue) : gettype($primaryValue); $query = new Query($this->connection->update($table, $values)); $query->fluent->where("%n = " . $query->getModificators()[$type], $primaryColumn, $primaryValue); $query->resultCallback = function (Query $query) { $query->fluent->execute(); return $this->connection->getAffectedRows() === 0 ? false : true; }; return $query; }
/** * Apply substitutions to indentifier and delimites it. * @param string indentifier * @return string * @internal */ public function delimite($value) { $value = $this->connection->substitute($value); $parts = explode('.', $value); foreach ($parts as &$v) { if ($v !== '*') { $v = $this->driver->escape($v, dibi::IDENTIFIER); } } return implode('.', $parts); }
/** * Performs an authentication against e.g. database. * and returns IIdentity on success or throws AuthenticationException * @return IIdentity * @throws AuthenticationException */ function authenticate(array $credentials) { list($username, $password) = $credentials; $result = $this->database->select('*') ->from(self::TABLE) ->where('username = %s',$username) ->fetch(); $count = $result->count(); if ($count < 1) { throw new NS\AuthenticationException('User not found.'); } if (!NS\Passwords::verify($password, $result->password)) { throw new NS\AuthenticationException('Invalid password.'); } return new NS\Identity($result->id, $result->role, array('username' => $result->username)); }
/** * Returns a blank row (not fetched from database). * @return array|object */ public function createBlank() { $row = $this->blankRow; $row[$this->primary] = NULL; if ($class = $this->connection->getConfig('result:objects')) { if ($class === TRUE) { $row = (object) $row; } else { $row = new $class($row); } } return $row; }
/** * Connects to a database. * * @return void * @throws DibiException */ public function connect(array &$config) { DibiConnection::alias($config, 'username', 'user'); DibiConnection::alias($config, 'password', 'pass'); DibiConnection::alias($config, 'database', 'db'); DibiConnection::alias($config, 'charset'); $this->connection = @oci_new_connect($config['username'], $config['password'], $config['database'], $config['charset']); // intentionally @ if (!$this->connection) { $err = oci_error(); throw new DibiDriverException($err['message'], $err['code']); } }
/** * Only columns and operations. * @param string $name * @return Grid */ private function baseGrid($name) { $grid = new Grid($this, $name); $grid->translator->lang = 'cs'; $grid->defaultPerPage = 4; $fluent = $this->database->select('u.*, c.title AS country')->from('[user] u')->join('[country] c')->on('u.country_code = c.code'); $grid->model = $fluent; $grid->addColumnText('firstname', 'Firstname')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('firstname')->cellPrototype->class[] = 'center'; $grid->addColumnText('surname', 'Surname')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('surname')->cellPrototype->class[] = 'center'; $grid->addColumnText('gender', 'Gender')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('gender')->cellPrototype->class[] = 'center'; $grid->addColumnDate('birthday', 'Birthday', \Grido\Components\Columns\Date::FORMAT_TEXT)->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('birthday')->cellPrototype->class[] = 'center'; $grid->addColumnText('country', 'Country')->setSortable()->setCustomRender(function ($item) { $baseUri = $this->getBaseUri(); $img = Html::el('img')->src("{$baseUri}/img/flags/{$item->country_code}.gif"); return "{$img} {$item->country}"; })->headerPrototype->class[] = 'center'; $grid->getColumn('country')->cellPrototype->class[] = 'center'; $grid->addColumnText('city', 'City')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('city')->cellPrototype->class[] = 'center'; $grid->addColumnText('zip', 'ZIP')->setColumn('zipcode')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('zip')->cellPrototype->class[] = 'center'; $grid->addColumnText('phone', 'Phone')->setColumn('telephonenumber')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('phone')->cellPrototype->class[] = 'center'; $grid->addColumnEmail('email', 'Email')->setColumn('emailaddress')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('email')->cellPrototype->class[] = 'center'; $grid->addColumnText('card', 'Card')->setSortable()->setColumn('cctype')->setReplacement(array('MasterCard' => Html::el('b')->setText('MasterCard')))->headerPrototype->class[] = 'center'; $grid->getColumn('card')->cellPrototype->class[] = 'center'; $grid->addColumnText('height', 'Height')->setColumn('centimeters')->setSortable()->headerPrototype->class[] = 'center'; $grid->getColumn('height')->cellPrototype->class[] = 'center'; $operation = array('print' => 'Print', 'delete' => 'Delete'); $grid->setOperation($operation, $this->handleOperations)->setConfirm('delete', 'Are you sure you want to delete %i items?'); $grid->setExport(); return $grid; }