Ejemplo n.º 1
1
 public function setUp()
 {
     date_default_timezone_set('UTC');
     if (DB_DRIVER === 'mysql') {
         $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME);
         $pdo = null;
     } elseif (DB_DRIVER === 'postgres') {
         $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
         $pdo = null;
     }
     $this->container = new Pimple\Container();
     $this->container->register(new Kanboard\ServiceProvider\DatabaseProvider());
     $this->container->register(new Kanboard\ServiceProvider\ClassProvider());
     $this->container['dispatcher'] = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
     $this->container['db']->logQueries = true;
     $this->container['logger'] = new Logger();
     $this->container['logger']->setLogger(new File('/dev/null'));
     $this->container['httpClient'] = new FakeHttpClient();
     $this->container['emailClient'] = $this->getMockBuilder('EmailClient')->setMethods(array('send'))->getMock();
     $this->container['userNotificationType'] = $this->getMockBuilder('\\Kanboard\\Model\\UserNotificationType')->setConstructorArgs(array($this->container))->setMethods(array('getType'))->getMock();
 }
    public function initTables()
    {
        try {
            $this->con->exec('DROP TABLE [book]');
            $this->con->exec('DROP TABLE [author]');
        } catch (PDOException $e) {
            // do nothing - the tables probably don't exist yet
        }
        $this->con->exec('CREATE TABLE [book]
		(
			[id] INTEGER  NOT NULL PRIMARY KEY,
			[title] VARCHAR(255)  NOT NULL,
			[isbn] VARCHAR(24)  NOT NULL,
			[price] FLOAT,
			[author_id] INTEGER,
			FOREIGN KEY (author_id) REFERENCES author(id)
		)');
        $this->con->exec('CREATE TABLE [author]
		(
			[id] INTEGER  NOT NULL PRIMARY KEY,
			[first_name] VARCHAR(128)  NOT NULL,
			[last_name] VARCHAR(128)  NOT NULL,
			[email] VARCHAR(128)
		)');
    }
Ejemplo n.º 3
0
 /**
  * Create a database connection.
  *
  * @return PDO  The database connection.
  */
 private function connect()
 {
     try {
         $db = new PDO($this->dsn, $this->username, $this->password);
     } catch (PDOException $e) {
         throw new Exception('Failed to connect to \'' . $this->dsn . '\': ' . $e->getMessage());
     }
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     /* Ensure that we are operating with UTF-8 encoding.
      * This command is for MySQL. Other databases may need different commands.
      */
     $driver = explode(':', $this->dsn, 2);
     $driver = strtolower($driver[0]);
     /* Driver specific initialization. */
     switch ($driver) {
         case 'mysql':
             /* Use UTF-8. */
             $db->exec("SET NAMES 'utf8'");
             break;
         case 'pgsql':
             /* Use UTF-8. */
             $db->exec("SET NAMES 'UTF8'");
             break;
     }
     return $db;
 }
Ejemplo n.º 4
0
function formthrottle_too_many_submissions($ip)
{
    $tooManySubmissions = false;
    try {
        if (in_array("sqlite", PDO::getAvailableDrivers(), TRUE)) {
            $db = new PDO('sqlite:muse-throttle-db.sqlite3');
        } else {
            if (function_exists("sqlite_open")) {
                $db = new PDO('sqlite2:muse-throttle-db');
            }
        }
    } catch (PDOException $Exception) {
        return $tooManySubmissions;
    }
    if ($db) {
        $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
        if (!$res or $res->fetchColumn() == 0) {
            $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
        }
        $db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')");
        $stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))");
        $stmt->bindParam(':ip', $ip);
        $stmt->execute();
        $stmt->closeCursor();
        $stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;");
        $stmt->bindParam(':ip', $ip);
        $stmt->execute();
        if ($stmt->fetchColumn() > 25) {
            $tooManySubmissions = true;
        }
        // Close file db connection
        $db = null;
    }
    return $tooManySubmissions;
}
Ejemplo n.º 5
0
    /**
     * Connect to local sqlite db
     *
     * @param string $locking_mode        	
     * @return \PDO
     */
    private function cache_local_connect($locking_mode = 'NORMAL')
    {
        try {
            $table = <<<EOD
CREATE TABLE "cachedb" (
"itemid"  INTEGER PRIMARY KEY AUTOINCREMENT,
"title"  TEXT,
"link"  TEXT,
"stemmed"  TEXT,
"metaphone"  TEXT,
"ts"  DATETIME DEFAULT (datetime( 'now', 'utc'))
);
EOD;
            $cachelocal = new \PDO('sqlite::memory:');
            $cachelocal->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $cachelocal->setAttribute(\PDO::ATTR_TIMEOUT, 20);
            $cachelocal->exec("PRAGMA locking_mode = {$locking_mode}");
            $cachelocal->exec($table);
            // Create custom function for similar titles
            $cachelocal->sqliteCreateFunction('similarity', array('Rss\\Util\\Cache\\FeedCache\\FeedCache', 'SIMILARITY'), 2);
            // Create custom function for all terms in a title included in a published one.
            $cachelocal->sqliteCreateFunction('allterms', array('Rss\\Util\\Cache\\FeedCache\\FeedCache', 'ALLTERMS'), 2);
            return $cachelocal;
        } catch (\Exception $e) {
            $m = 'Error connecting to sqlite ' . $e->getCode() . ' ' . $e->getMessage();
            $this->fail($m);
        }
    }
Ejemplo n.º 6
0
    /**
     * Update statistics
     * @return mixed false on failure, number of affected rows otherwise
     */
    public function run()
    {
        $whereAccount = null !== $this->accountID ? 'WHERE `eqp`.`accountid` = ' . $this->accountID : '';
        $result = $this->PDO->exec('UPDATE `' . PREFIX . 'equipment`
			CROSS JOIN(
				SELECT
					`eqp`.`id` AS `eqpid`,
					SUM(`tr`.`distance`) AS `km`,
					SUM(`tr`.`s`) AS `s` 
				FROM `' . PREFIX . 'equipment` AS `eqp` 
				LEFT JOIN `' . PREFIX . 'activity_equipment` AS `aeqp` ON `eqp`.`id` = `aeqp`.`equipmentid` 
				LEFT JOIN `' . PREFIX . 'training` AS `tr` ON `aeqp`.`activityid` = `tr`.`id`
				' . $whereAccount . '
				GROUP BY `eqp`.`id`
			) AS `new`
			SET
				`distance` = IFNULL(`new`.`km`, 0),
				`time` = IFNULL(`new`.`s`, 0)
			WHERE `id` = `new`.`eqpid`');
        if ($result !== false) {
            $Factory = new \Runalyze\Model\Factory($this->accountID);
            $Factory->clearCache('equipment');
        }
        return $result;
    }
 function pdoConnect($dbs = null)
 {
     if ($dbs) {
         $dbname = $this->_strDBSName;
         $dbuser = $this->_strDBSUser;
         $dbpass = $this->_strDBSPassword;
     } else {
         $dbname = $this->_strDBName;
         $dbuser = $this->_strDBUser;
         $dbpass = $this->_strDBPassword;
     }
     try {
         ini_set('max_execution_time', 300);
         $dsn = "mysql:host=" . $this->_strDBHost . ";dbname=" . $dbname;
         $db = new PDO($dsn, "{$dbuser}", "{$dbpass}");
         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
         $db->exec("SET names utf8");
         $db->exec("SET time_zone = 'your timezone'");
     } catch (PDOException $e) {
         print "Error!: " . $e->getMessage() . "<br/>";
         die;
     }
     return $db;
 }
Ejemplo n.º 8
0
 /**
  * Changes current database
  * @param  string  $database database name
  * @return boolean true on success, false - otherwise
  */
 public function changeDb($database)
 {
     if ($this->conn->exec('USE ' . $database) !== false) {
         return true;
     }
     return false;
 }
Ejemplo n.º 9
0
 public function testEmptySpecificKeys()
 {
     $this->PDO->exec('INSERT INTO `' . PREFIX . 'table` (`key`, `foo`, `bar`) VALUES ("1", "", "")');
     $Updater = new UpdaterForObject_MockTester($this->PDO);
     $Updater->update(new UpdaterObject_MockTester(array('foo' => 'test', 'bar' => 'test')), array());
     $this->assertEquals(array('key' => '1', 'foo' => '', 'bar' => ''), $this->PDO->query('SELECT `key`, `foo`, `bar` FROM `' . PREFIX . 'table`')->fetch(PDO::FETCH_ASSOC));
 }
    /**
     * Create the database tables
     *
     * @param  PDO $pdo
     */
    private function createSchema($pdo)
    {
        // create author table
        $pdo->exec(<<<SQL
CREATE TABLE IF NOT EXISTS author (
  id VARCHAR(36) NOT NULL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  biography TEXT
);
SQL
);
        // create book table
        $pdo->exec(<<<SQL
CREATE TABLE IF NOT EXISTS book (
  id VARCHAR(36) NOT NULL PRIMARY KEY,
  author_id VARCHAR(36) NOT NULL,
  title VARCHAR(100) NOT NULL,
  isbn VARCHAR(13),
  date_published DATE,

  FOREIGN KEY (author_id) REFERENCES author (id)
);
SQL
);
    }
Ejemplo n.º 11
0
function db_connect($url, $persistent = true)
{
    global $db_conn, $db_scheme;
    $url = parse_url($url);
    $scheme = $url['scheme'];
    $host = urldecode($url['host']);
    if (isset($url['port'])) {
        $host = $host . ':' . $url['port'];
    }
    $user = urldecode($url['user']);
    $pass = isset($url['pass']) ? urldecode($url['pass']) : '';
    $path = urldecode($url['path']);
    if ($path[0] == '/') {
        $path = substr($path, 1);
    }
    $dsn = "{$scheme}:host={$host};dbname={$path}";
    $options = array(PDO::ATTR_PERSISTENT => $persistent ? true : false);
    try {
        $db_conn = new PDO($dsn, $user, $pass, $options);
        $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db_conn->exec("SET NAMES 'utf8'");
        if ($scheme == 'mysql') {
            $db_conn->exec("SET SQL_MODE='ANSI_QUOTES'");
        }
        $db_scheme = $scheme;
    } catch (PDOException $e) {
        die($e->getMessage());
    }
    return $db_conn;
}
Ejemplo n.º 12
0
 public static function setUpBeforeClass()
 {
     if (DB_DRIVER === 'sqlite') {
         @unlink(DB_FILENAME);
         $pdo = new PDO('sqlite:' . DB_FILENAME);
     } else {
         if (DB_DRIVER === 'mysql') {
             $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
             $pdo->exec('DROP DATABASE ' . DB_NAME);
             $pdo->exec('CREATE DATABASE ' . DB_NAME);
             $pdo = new PDO('mysql:host=' . DB_HOSTNAME . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
         } else {
             if (DB_DRIVER === 'postgres') {
                 $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
                 $pdo->exec('DROP DATABASE ' . DB_NAME);
                 $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
                 $pdo = new PDO('pgsql:host=' . DB_HOSTNAME . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
             }
         }
     }
     $service = new ServiceProvider\Database();
     $service->getInstance();
     $pdo->exec("UPDATE settings SET value='" . API_KEY . "' WHERE option='api_token'");
     $pdo->exec("UPDATE settings SET value='Europe/Paris' WHERE option='application_timezone'");
     $pdo = null;
 }
Ejemplo n.º 13
0
 /**
  * Get database connection object
  *
  * @throws \Ip\Exception\Db
  * @return \PDO
  */
 public function getConnection()
 {
     if ($this->pdoConnection) {
         return $this->pdoConnection;
     }
     $dbConfig = ipConfig()->get('db');
     ipConfig()->set('db', null);
     if (empty($dbConfig)) {
         throw new \Ip\Exception\Db("Can't connect to database. No connection config found or \\Ip\\Db::disconnect() has been used.");
     }
     try {
         if (array_key_exists('driver', $dbConfig) && $dbConfig['driver'] == 'sqlite') {
             $dsn = 'sqlite:' . $dbConfig['database'];
             $this->pdoConnection = new \PDO($dsn);
             $this->pdoConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
         } else {
             $dsn = 'mysql:host=' . str_replace(':', ';port=', $dbConfig['hostname']);
             if (!empty($dbConfig['database'])) {
                 $dsn .= ';dbname=' . $dbConfig['database'];
             }
             $this->pdoConnection = new \PDO($dsn, $dbConfig['username'], $dbConfig['password']);
             $this->pdoConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
             $dt = new \DateTime();
             $offset = $dt->format("P");
             $this->pdoConnection->exec("SET time_zone='{$offset}';");
             $this->pdoConnection->exec("SET CHARACTER SET " . $dbConfig['charset']);
         }
     } catch (\PDOException $e) {
         throw new \Ip\Exception\Db("Can't connect to database. Stack trace hidden for security reasons");
         //PHP traces all details of error including DB password. This could be a disaster on live server. So we hide that data.
     }
     $this->tablePrefix = $dbConfig['tablePrefix'];
     return $this->pdoConnection;
 }
Ejemplo n.º 14
0
 public function exec($query)
 {
     if (is_null($this->_pdo)) {
         return;
     }
     return $this->_pdo->exec($query);
 }
Ejemplo n.º 15
0
    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     * @group mysql
     */
    public static function setUpBeforeClass()
    {
        $database = MYSQL_DSN;
        $pdo = new \PDO(MYSQL_DSN, MYSQL_USER, MYSQL_PASSWORD);
        $pdo->exec('drop table if exists user');
        $pdo->exec('drop table if exists item');
        $create = <<<SQL
CREATE TABLE `user` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `name` varchar(45) DEFAULT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
SQL;
        $pdo->exec($create);
        $create2 = <<<SQL
CREATE TABLE `item` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `name` varchar(45) DEFAULT NULL,
   `created_at` timestamp,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
SQL;
        $r = $pdo->exec($create2);
        $insert = <<<SQL
insert into user values(1, 'sato');
insert into user values(2, 'suzuki');
insert into user values(3, 'takahashi');
insert into user values(4, 'tanaka');
insert into user values(5, 'ito');
SQL;
        $pdo->exec($insert);
        $pdo = null;
    }
Ejemplo n.º 16
0
 public function setUp()
 {
     if (DB_DRIVER === 'mysql') {
         $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME);
         $pdo = null;
     } else {
         if (DB_DRIVER === 'postgres') {
             $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
             $pdo->exec('DROP DATABASE ' . DB_NAME);
             $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
             $pdo = null;
         }
     }
     $this->container = new Pimple\Container();
     $this->container->register(new ServiceProvider\DatabaseProvider());
     $this->container->register(new ServiceProvider\ClassProvider());
     $this->container['dispatcher'] = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
     $this->container['db']->logQueries = true;
     $this->container['logger'] = new Logger();
     $this->container['logger']->setLogger(new File('/dev/null'));
     $this->container['httpClient'] = new FakeHttpClient();
     $this->container['emailClient'] = $this->getMockBuilder('EmailClient')->setMethods(array('send'))->getMock();
 }
Ejemplo n.º 17
0
 public function __construct()
 {
     parent::__construct();
     $pdo = new PDO('sqlite::memory:');
     $artists = [['name' => 'The Smashing Pumpkins', 'albums' => [['name' => 'Siamese Dream', 'year' => 1993, 'songs' => ['Hummer', 'Disarm', 'Soma', 'Mayonaise']], ['name' => 'Pisces Iscariot', 'year' => 1994, 'songs' => ['Plume', 'Whir', 'Landslide']]]], ['name' => 'Placebo', 'albums' => [['name' => 'Without You I\'m Nothing', 'year' => 1998, 'songs' => ['Pure Morning', 'Brick Shithouse', 'You Don\'t Care About Us', 'Allergic (to Thoughts of Mother Earth)', 'Every You Every Me']], ['name' => 'Black Market Music', 'year' => 2000, 'songs' => ['Taste in Men', 'Special K', 'Spice & Malice', 'Black-Eyed', 'Peeping Tom']], ['name' => 'Sleeping With Ghosts', 'year' => 2002, 'songs' => ['English Summer Rain', 'This Picture', 'Special Needs', 'Second Sight', 'Centrefolds']]]], ['name' => 'The Who', 'albums' => [['name' => 'Who\'s Next', 'year' => 1971, 'songs' => ['Baba O\'Riley', 'My Wife', 'Going Mobile', 'Behind Blue Eyes']]]]];
     $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     $pdo->exec("CREATE TABLE artists (id INTEGER PRIMARY KEY, name TEXT)");
     $pdo->exec("CREATE TABLE albums  (id INTEGER PRIMARY KEY, name TEXT, year INTEGER, artist_id INTEGER)");
     $pdo->exec("CREATE TABLE songs   (id INTEGER PRIMARY KEY, name TEXT, track_number INTEGER, album_id INTEGER)");
     $insert_artist = $pdo->prepare("INSERT INTO artists (name) VALUES (?)");
     $insert_album = $pdo->prepare("INSERT INTO albums (name, year, artist_id) VALUES (?, ?, ?)");
     $insert_song = $pdo->prepare("INSERT INTO songs (name, track_number, album_id) VALUES (?, ?, ?)");
     $pdo->beginTransaction();
     foreach ($artists as $artist) {
         $insert_artist->execute([$artist['name']]);
         $artist_id = $pdo->lastInsertId();
         foreach ($artist['albums'] as $album) {
             $insert_album->execute([$album['name'], $album['year'], $artist_id]);
             $album_id = $pdo->lastInsertId();
             foreach ($album['songs'] as $track_number => $song) {
                 $insert_song->execute([$song, $track_number + 1, $album_id]);
             }
         }
     }
     $this->pdo = $pdo;
 }
Ejemplo n.º 18
0
 /**
 	Database install
 */
 private static function install_schema()
 {
     $data = $_SESSION;
     $sql = str_replace('[[now]]', time(), file_get_contents('assets/sql/anchor.sql'));
     $dsn = 'mysql:dbname=' . $data['db']['name'] . ';host=' . $data['db']['host'] . ';port=' . $data['db']['port'];
     $dbh = new PDO($dsn, $data['db']['user'], $data['db']['pass']);
     try {
         $dbh->beginTransaction();
         $dbh->exec('SET NAMES `utf8`');
         $dbh->exec($sql);
         // create metadata
         $sql = "INSERT INTO `meta` (`key`, `value`) VALUES ('sitename', ?), ('description', ?), ('theme', ?);";
         $statement = $dbh->prepare($sql);
         $statement->execute(array($data['site']['site_name'], $data['site']['site_description'], $data['site']['theme']));
         // create user account
         $sql = "INSERT INTO `users` (`username`, `password`, `email`, `real_name`, `bio`, `status`, `role`) VALUES (?, ?, ?, 'Administrator', 'Default account for Anchor.', 'active', 'administrator');";
         $statement = $dbh->prepare($sql);
         $statement->execute(array($data['user']['username'], crypt($data['user']['password'], $_SESSION['key']), $data['user']['email']));
         $dbh->commit();
     } catch (PDOException $e) {
         Messages::add($e->getMessage());
         // rollback any changes
         if ($dbh->inTransaction()) {
             $dbh->rollBack();
         }
     }
 }
function try_buffer_size($offset, $buffer_size)
{
    try {
        $dsn = MySQLPDOTest::getDSN();
        $user = PDO_MYSQL_TEST_USER;
        $pass = PDO_MYSQL_TEST_PASS;
        /* unsigned overflow possible ? */
        $db = new PDO($dsn, $user, $pass, array(PDO::MYSQL_ATTR_MAX_BUFFER_SIZE => $buffer_size, PDO::MYSQL_ATTR_DIRECT_QUERY => 0, PDO::ATTR_EMULATE_PREPARES => 0));
        $db->exec('DROP TABLE IF EXISTS test');
        $db->exec(sprintf('CREATE TABLE test(id INT, val LONGBLOB) ENGINE = %s', PDO_MYSQL_TEST_ENGINE));
        // 10 * (10 * 1024) = 10 * (10 * 1k) = 100k
        $db->exec('INSERT INTO test(id, val) VALUES (1, REPEAT("01234567890", 10240))');
        $stmt = $db->prepare('SELECT id, val FROM test');
        $stmt->execute();
        $id = $val = NULL;
        $stmt->bindColumn(1, $id);
        $stmt->bindColumn(2, $val);
        while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
            printf("[%03d] id = %d, val = %s... (length: %d)\n", $offset, $id, substr($val, 0, 10), strlen($val));
        }
        $db->exec('DROP TABLE IF EXISTS test');
    } catch (PDOException $e) {
        printf("[%03d] %s, [%s] %s\n", $offset, $e->getMessage(), is_object($db) ? $db->errorCode() : 'n/a', is_object($db) ? implode(' ', $db->errorInfo()) : 'n/a');
    }
}
Ejemplo n.º 20
0
 public function setUp()
 {
     date_default_timezone_set('UTC');
     if (DB_DRIVER === 'mysql') {
         $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME);
         $pdo = null;
     } elseif (DB_DRIVER === 'postgres') {
         $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
         $pdo->exec('DROP DATABASE ' . DB_NAME);
         $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
         $pdo = null;
     }
     $this->container = new Pimple\Container();
     $this->container->register(new Kanboard\ServiceProvider\HelperProvider());
     $this->container->register(new Kanboard\ServiceProvider\AuthenticationProvider());
     $this->container->register(new Kanboard\ServiceProvider\DatabaseProvider());
     $this->container->register(new Kanboard\ServiceProvider\ClassProvider());
     $this->container->register(new Kanboard\ServiceProvider\NotificationProvider());
     $this->container->register(new Kanboard\ServiceProvider\RouteProvider());
     $this->container['dispatcher'] = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
     $this->container['db']->logQueries = true;
     $this->container['logger'] = new Logger();
     $this->container['logger']->setLogger(new File($this->isWindows() ? 'NUL' : '/dev/null'));
     $this->container['httpClient'] = $this->getMockBuilder('\\Kanboard\\Core\\Http\\Client')->setConstructorArgs(array($this->container))->setMethods(array('get', 'getJson', 'postJson', 'postForm'))->getMock();
     $this->container['emailClient'] = $this->getMockBuilder('\\Kanboard\\Core\\Mail\\Client')->setConstructorArgs(array($this->container))->setMethods(array('send'))->getMock();
     $this->container['userNotificationType'] = $this->getMockBuilder('\\Kanboard\\Model\\UserNotificationType')->setConstructorArgs(array($this->container))->setMethods(array('getType', 'getSelectedTypes'))->getMock();
     $this->container['objectStorage'] = $this->getMockBuilder('\\Kanboard\\Core\\ObjectStorage\\FileStorage')->setConstructorArgs(array($this->container))->setMethods(array('put', 'moveFile', 'remove', 'moveUploadedFile'))->getMock();
     $this->container['sessionStorage'] = new SessionStorage();
     $this->container->register(new ActionProvider());
     $this->container['flash'] = function ($c) {
         return new FlashMessage($c);
     };
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     if ($input->getOption("password")) {
         $password = $input->getOption("password");
     } else {
         $question = new Question('Password: '******'question');
         $password = $helper->ask($input, $output, $question);
     }
     $server = new Server\Database\Mysql();
     $server->setHostname($input->getArgument("host"));
     $server->setUser("provisioning");
     $server->setPassword($this->createPassword());
     $server->setDatabase("provisioning");
     $server->setMode($input->getArgument("mode"));
     $server->setType($input->getArgument("type"));
     $server->setActive(false);
     // convert errors to PDOExceptions
     $options = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
     $dsn = sprintf("mysql:host=%s;port=%s;charset=utf8", $server->getHostname(), 3306);
     $pdo = new \PDO($dsn, $input->getArgument("user"), $password, $options);
     $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
     $pdo->exec("SET NAMES utf8;");
     $pdo->exec("CREATE USER '{$server->getUser()}'@'%' IDENTIFIED BY '{$server->getPassword()}';");
     $pdo->exec("GRANT CREATE, DROP, GRANT OPTION, LOCK TABLES, REFERENCES, EVENT, ALTER, DELETE, INDEX, INSERT, SELECT, UPDATE, CREATE TEMPORARY TABLES, TRIGGER, CREATE VIEW, SHOW VIEW, ALTER ROUTINE, CREATE ROUTINE, EXECUTE, CREATE USER, PROCESS, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHOW DATABASES, USAGE ON *.* TO '{$server->getUser()}' WITH GRANT OPTION;");
     $pdo->exec("CREATE DATABASE {$server->getDatabase()} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;");
     // Write to DB
     $entityManager = $this->getProvisioningServer("mysql")->getEntityManager();
     $entityManager->persist($server);
     $entityManager->flush();
     $table = $this->getMySqlServersTable([$server], $output);
     $table->render();
 }
Ejemplo n.º 22
0
 protected function tearDown()
 {
     $this->PDO->exec('TRUNCATE TABLE `' . PREFIX . 'training`');
     $this->PDO->exec('TRUNCATE TABLE `' . PREFIX . 'sport`');
     $this->PDO->exec('TRUNCATE TABLE `' . PREFIX . 'shoe`');
     \Cache::clean();
 }
 /**
  * Destroy the application.
  *
  * @return array
  **/
 public function tearDown()
 {
     $this->app = null;
     $this->pdo->exec('DELETE * FROM books');
     $this->pdo->exec('DROP TABLE books');
     $this->pdo = null;
 }
Ejemplo n.º 24
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     $this->db_file = tempnam(sys_get_temp_dir(), 'test.sqlite');
     file_put_contents($this->db_file, '');
     $db = new PDO('sqlite:' . $this->db_file);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $db->exec("CREATE TABLE fairies(id INT PRIMARY_KEY,name VARCHAR(255),password VARCHAR(255))");
     $db->exec("INSERT INTO fairies(id,name,password) VALUES(1,'Trixie','\$1\$YedTmYOS\$Hduvs.m2BTctZOskn6QkC1')");
     // old crypt() passwords
     $db->exec("INSERT INTO fairies(id,name,password) VALUES(1,'Vixie','\$2y\$10\$usesomesillystringforeQa5FME91Ofn.gNX7VH5DFkYkpDXFsbG')");
     // new password_hash passwords
     $db = null;
     $pixie = $this->pixie = new \PHPixie\Pixie();
     $this->pixie->app_namespace = 'PasswordCryptTest\\';
     $pixie->db = new \PHPixie\DB($pixie);
     $pixie->orm = new \PHPixie\ORM($pixie);
     $this->pixie->auth = new \PHPixie\Auth($pixie);
     $pixie->config->set('db.default.connection', 'sqlite:' . $this->db_file);
     $pixie->config->set('db.default.driver', 'PDO');
     $pixie->config->set('auth.default.model', 'Fairy');
     $pixie->config->set('auth.default.login.password.login_field', 'name');
     $pixie->config->set('auth.default.login.password.password_field', 'password');
     $pixie->config->set('auth.default.login.password.hash_method', 'crypt');
     $this->session_array = array();
     $pixie->session = new \AuthStub\Session($this->session_array);
     $this->object = $this->pixie->auth->provider('password');
 }
Ejemplo n.º 25
0
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     $this->db_file = tempnam(sys_get_temp_dir(), 'test.sqlite');
     file_put_contents($this->db_file, '');
     $db = new PDO('sqlite:' . $this->db_file);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $db->exec("CREATE TABLE fairies(id INT PRIMARY_KEY,name VARCHAR(255),password VARCHAR(255), token VARCHAR(255))");
     $db->exec("INSERT INTO fairies(id,name,password, token) VALUES(1,'Trixie','53de0be73c461405f0953cf1c33806b8:26165517952a3e16d4', NULL)");
     $db = null;
     $pixie = $this->pixie = new \PHPixie\Pixie();
     $this->pixie->app_namespace = 'PasswordTokenTest\\';
     $pixie->db = new \PHPixie\DB($pixie);
     $pixie->orm = new \PHPixie\ORM($pixie);
     $this->pixie->auth = new \PHPixie\Auth($pixie);
     $pixie->config->set('db.default.connection', 'sqlite:' . $this->db_file);
     $pixie->config->set('db.default.driver', 'PDO');
     $pixie->config->set('auth.default.model', 'Fairy');
     $pixie->config->set('auth.default.login.password.login_field', 'name');
     $pixie->config->set('auth.default.login.password.password_field', 'password');
     $pixie->config->set('auth.default.login.password.hash_method', 'md5');
     $pixie->config->set('auth.default.login.password.login_token_field', 'token');
     $pixie->config->set('auth.default.login.password.login_token_lifetime', 1);
     $this->session_array = array();
     $pixie->session = new \AuthStub\Session($this->session_array);
     $this->object = $this->pixie->auth->provider('password');
 }
Ejemplo n.º 26
0
 /**
  * Connect to a database via FS_PDO
  *
  * @param mixed $dsn data source for database connection (array or string)
  * @param       $login
  * @param       $password
  */
 public function connect_db($dsn, $login, $password)
 {
     try {
         $this->db = new PDO($dsn, $login, $password);
     } catch (PDOException $e) {
         $this->debug($e->getMessage());
         $this->file_not_found();
         //program terminates in function file_not_found()
     }
     $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
     $driver = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME);
     $this->debug("our driver is {$driver}");
     switch ($driver) {
         case 'mysql':
             $quoter = '`';
             break;
         case 'pgsql':
             if (DEFAULT_DSN_SCHEMA) {
                 $this->db->exec('SET SEARCH_PATH=' . DEFAULT_DSN_SCHEMA);
             }
             $quoter = '"';
             break;
         default:
             $quoter = '';
             break;
     }
     define('DB_FIELD_QUOTE', $quoter);
 }
Ejemplo n.º 27
0
function assignRoles($gameid)
{
    $servername = "localhost";
    $username = "******";
    $password = "";
    $dbname = "mafia";
    try {
        $conn = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM mafia WHERE gameid = '{$gameid}'";
        $cnt = 0;
        foreach ($conn->query($sql) as $row) {
            $role = rand(0, 5);
            $u = $row['uuid'];
            $sql = "UPDATE mafia SET role = '{$role}' WHERE uuid = '{$u}'";
            $conn->exec($sql);
            $cnt++;
        }
        $rand = rand(0, $cnt);
        $cnt2 = 0;
        foreach ($conn->query($sql) as $row) {
            if ($cnt2 == $rand) {
                $u = $row['uuid'];
                $sql = "UPDATE mafia SET role = '1' WHERE uuid = '{$u}'";
                $conn->exec($sql);
            }
            $cnt2++;
        }
    } catch (PDOException $e) {
        //echo $sql . "<br>" . $e->getMessage();
    }
    $conn = null;
}
Ejemplo n.º 28
0
 public static function create_database($root, $root_pass, $user, $pass, $db, $db_type, $host)
 {
     $root = filter_var($root, FILTER_SANITIZE_STRING);
     $root_pass = filter_var($root_pass, FILTER_SANITIZE_STRING);
     $user = filter_var($user, FILTER_SANITIZE_STRING);
     $password = filter_var($pass, FILTER_SANITIZE_STRING);
     $db = filter_var($db, FILTER_SANITIZE_STRING);
     $db_type = filter_var($db_type, FILTER_SANITIZE_STRING);
     $host = filter_var($host, FILTER_SANITIZE_STRING);
     // Dirty hack
     if ($host != 'localhost' || $host != '127.0.0.1') {
         $grantright = $_SERVER['SERVER_ADDR'];
     } else {
         $grantright = $host;
     }
     try {
         $dbh = new PDO($db_type . ':host=' . $host, $root, $root_pass);
         if ($db_type == 'mysql') {
             $dbh->exec("CREATE DATABASE IF NOT EXISTS `" . $db . "`;\n\t\t\t\t\tGRANT ALL ON `" . $db . "`.* TO '" . $user . "'@'" . $grantright . "' IDENTIFIED BY '" . $password . "';\n\t\t\t\t\tFLUSH PRIVILEGES;");
         } else {
             if ($db_type == 'pgsql') {
                 $dbh->exec("CREATE DATABASE " . $db . ";\n\t\t\t\t\tCREATE USER " . $user . " WITH PASSWORD '" . $password . "';\n\t\t\t\t\tGRANT ALL PRIVILEGES ON DATABASE " . $db . " TO " . $user . ";");
             }
         }
         //		or return($dbh->errorInfo());
     } catch (PDOException $e) {
         return "error : " . $e->getMessage();
     }
     return true;
 }
Ejemplo n.º 29
0
 public static function setUpBeforeClass()
 {
     if (DB_DRIVER === 'sqlite') {
         @unlink(DB_FILENAME);
     } else {
         if (DB_DRIVER === 'mysql') {
             $pdo = new PDO('mysql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
             $pdo->exec('DROP DATABASE ' . DB_NAME);
             $pdo->exec('CREATE DATABASE ' . DB_NAME);
             $pdo = null;
         } else {
             if (DB_DRIVER === 'postgres') {
                 $pdo = new PDO('pgsql:host=' . DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);
                 $pdo->exec('DROP DATABASE ' . DB_NAME);
                 $pdo->exec('CREATE DATABASE ' . DB_NAME . ' WITH OWNER ' . DB_USERNAME);
                 $pdo = null;
             }
         }
     }
     $service = new ServiceProvider\DatabaseProvider();
     $db = $service->getInstance();
     $db->table('settings')->eq('option', 'api_token')->update(array('value' => API_KEY));
     $db->table('settings')->eq('option', 'application_timezone')->update(array('value' => 'Europe/Paris'));
     $db->closeConnection();
 }
Ejemplo n.º 30
0
 public function __construct()
 {
     $dbh = new PDO('sqlite::memory:');
     $dbh->exec("CREATE TABLE playlist (id INTEGER PRIMARY KEY ASC, file TEXT)");
     $dbh->exec("CREATE TABLE match (id INTEGER PRIMARY KEY ASC, artist TEXT, track TEXT, match TEXT)");
     $this->dbh = $dbh;
 }