Example #1
0
 protected function loadMigrated()
 {
     $db = $this->db;
     isset($this->sql[$sqlKey = 'load_migrated']) or $this->sql[$sqlKey] = strtr('SELECT * FROM `table`', ['`table`' => $db->escapeIdentifier($this->table)]);
     $this->rawMigrated = $this->db->fetchAll($this->sql[$sqlKey]);
     foreach ($this->rawMigrated as $row) {
         $this->migrated[$row['file']] = $row['run_at'];
     }
     return $this;
 }
Example #2
0
 /**
  * Executes the uniqueness validation
  *
  * @param  \Phalcon\Validation $validator
  * @param  string              $attribute
  * @return boolean
  */
 public function validate(Validation $validator, $attribute)
 {
     $table = $this->getOption('table');
     $column = $this->getOption('column');
     $result = $this->db->fetchOne(sprintf('SELECT COUNT(*) as count FROM %s WHERE %s = ?', $table, $column), Db::FETCH_ASSOC, array($validator->getValue($attribute)));
     if ($result['count']) {
         $message = $this->getOption('message');
         if (null === $message) {
             $message = 'Already taken. Choose another!';
         }
         $validator->appendMessage(new Message($message, $attribute, 'Uniqueness'));
         return false;
     }
     return true;
 }
Example #3
0
 /**
  * This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor.
  * Call it when you need to restore a database connection.
  *
  * @param array|null $descriptor
  * @return boolean
  * @throws Exception
  */
 public function connect($descriptor = null)
 {
     if (is_null($descriptor) === true) {
         $descriptor = $this->_descriptor;
     } elseif (is_array($descriptor) === false) {
         throw new Exception('Invalid parameter type.');
     }
     if (isset($descriptor['dbname']) === false) {
         throw new Exception('dbname must be specified');
     }
     $descriptor['dns'] = $descriptor['dbname'];
     parent::connect($descriptor);
 }
Example #4
0
 /**
  * This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor.
  * Call it when you need to restore a database connection.
  *
  * @param array|null $descriptor
  * @return boolean
  * @throws Exception
  */
 public function connect($descriptor = null)
 {
     if (is_array($descriptor) === false) {
         $descriptor = $this->_descriptor;
     }
     //Connect
     parent::__construct($descriptor);
     //Database session settings initiated with each HTTP request. Pracle behaviour
     //depends on particular NLS* parameter. Check if the developer has defined custom
     //startup or create one from scratch
     if (isset($descriptor['startup']) === true && is_array($descriptor['starup']) === true) {
         foreach ($descriptor['startup'] as $value) {
             $this->execute($value);
         }
     }
 }
Example #5
0
 /**
  * This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor.
  * Call it when you need to restore a database connection.
  *
  * @param array $descriptor
  * @return bool
  */
 public function connect(array $descriptor = null)
 {
     if (empty($descriptor)) {
         $descriptor = $this->_descriptor;
     }
     $status = parent::connect($descriptor);
     if (isset($descriptor['startup']) && $descriptor['startup']) {
         $startup = $descriptor['startup'];
         if (!is_array($startup)) {
             $startup = [$startup];
         }
         foreach ($startup as $value) {
             $this->execute($value);
         }
     }
     return $status;
 }
Example #6
0
 /**
  * Executes the uniqueness validation
  *
  * @param  \Phalcon\Validation $validator
  * @param  string $attribute
  * @return boolean
  */
 public function validate(Validation $validator, $attribute)
 {
     $table = $this->db->escapeIdentifier($this->getOption('table'));
     $column = $this->db->escapeIdentifier($this->getOption('column'));
     if ($this->hasOption('exclude')) {
         $exclude = $this->getOption('exclude');
         $result = $this->db->fetchOne(sprintf('SELECT COUNT(*) AS count FROM %s WHERE %s = ? AND %s != ?', $table, $column, $this->db->escapeIdentifier($exclude['column'])), Db::FETCH_ASSOC, [$validator->getValue($attribute), $exclude['value']]);
     } else {
         $result = $this->db->fetchOne(sprintf('SELECT COUNT(*) AS count FROM %s WHERE %s = ?', $table, $column), Db::FETCH_ASSOC, [$validator->getValue($attribute)]);
     }
     if ($result['count']) {
         $message = $this->getOption('message', 'Already taken. Choose another!');
         $validator->appendMessage(new Message($message, $attribute, 'Uniqueness'));
         return false;
     }
     return true;
 }
Example #7
0
 /**
  * This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor.
  * Call it when you need to restore a database connection.
  *
  * Support set search_path after connectted if schema is specified in config.
  *
  * @param array|null $descriptor
  * @return boolean
  * @throws Exception
  */
 public function connect($descriptor = null)
 {
     if (is_null($descriptor) === true) {
         $descriptor = $this->_descriptor;
     } elseif (is_array($descriptor) === false) {
         throw new Exception('Invalid parameter type.');
     }
     if (isset($descriptor['schema']) === true) {
         $schema = $descriptor['schema'];
         unset($descriptor['schema']);
     } else {
         $schema = null;
     }
     parent::connect($descriptor);
     //Execute the search path in the after connect
     if (is_string($schema) === true) {
         $this->execute("SET search_path TO '" . $schema . "'");
     }
 }
Example #8
0
 /**
  * Initialize migrations log storage
  *
  * @param array $options Applications options
  * @throws DbException
  */
 private static function connectionSetup($options)
 {
     if (self::$_storage) {
         return;
     }
     if (isset($options['migrationsInDb']) && (bool) $options['migrationsInDb']) {
         /** @var Config $database */
         $database = $options['config']['database'];
         if (!isset($database->adapter)) {
             throw new DbException('Unspecified database Adapter in your configuration!');
         }
         $adapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $database->adapter;
         if (!class_exists($adapter)) {
             throw new DbException('Invalid database Adapter!');
         }
         $configArray = $database->toArray();
         unset($configArray['adapter']);
         self::$_storage = new $adapter($configArray);
         if ($database->adapter === 'Mysql') {
             self::$_storage->query('SET FOREIGN_KEY_CHECKS=0');
         }
         if (!self::$_storage->tableExists(self::MIGRATION_LOG_TABLE)) {
             self::$_storage->createTable(self::MIGRATION_LOG_TABLE, null, ['columns' => [new Column('version', ['type' => Column::TYPE_VARCHAR, 'size' => 255, 'notNull' => true]), new Column('start_time', ['type' => Column::TYPE_TIMESTAMP, 'notNull' => true, 'default' => 'CURRENT_TIMESTAMP']), new Column('end_time', ['type' => 'TIMESTAMP NOT NULL DEFAULT NOW()'])], 'indexes' => [new Index('idx_' . self::MIGRATION_LOG_TABLE . '_version', ['version'])]]);
         }
     } else {
         $path = $options['directory'];
         if (is_file($path . '.phalcon')) {
             unlink($path . '.phalcon');
             mkdir($path . '.phalcon');
             chmod($path . '.phalcon', 0775);
         } elseif (!is_dir($path . '.phalcon')) {
             mkdir($path . '.phalcon');
             chmod($path . '.phalcon', 0775);
         }
         self::$_storage = $path . '.phalcon/migration-version';
         if (!file_exists(self::$_storage)) {
             touch(self::$_storage);
         }
     }
 }
Example #9
0
 public function query($sql, $bindParams = null, $bindTypes = null)
 {
     if (is_string($sql)) {
         //check sql server keyword
         if (!strpos($sql, '[rowcount]')) {
             $sql = str_replace('rowcount', '[rowcount]', $sql);
             //sql server keywords
         }
         //case 1. select count(query builder)
         $countString = 'SELECT COUNT(*)';
         if (strpos($sql, $countString)) {
             $sql = str_replace('"', '', $sql);
             return parent::query($sql, $bindParams, $bindTypes);
         }
         //case 2. subquery need alais name (model find)
         $countString = 'SELECT COUNT(*) "numrows"';
         if (strpos($sql, $countString) !== false) {
             $sql .= ' dt ';
             //subquery need TOP
             if (strpos($sql, 'TOP') === false) {
                 if (strpos($sql, 'ORDER') !== false) {
                     $offset = count($countString);
                     $pos = strpos($sql, 'SELECT', $offset) + 7;
                     //'SELECT ';
                     $sql = substr($sql, 0, $pos) . 'TOP 100 PERCENT ' . substr($sql, $pos);
                 }
             }
         }
         //sql server(dblib) does not accept " as escaper
         $sql = str_replace('"', '', $sql);
     }
     return parent::query($sql, $bindParams, $bindTypes);
 }
Example #10
0
 /**
  * Log a failed job into storage.
  *
  * @param  string $connection
  * @param  string $queue
  * @param  string $payload
  * @return void
  */
 public function log($connection, $queue, $payload)
 {
     $failed_at = date(DateTime::MYSQL_DATETIME);
     $this->db->insertAsDict($this->table, compact('connection', 'queue', 'payload', 'failed_at'));
 }
Example #11
0
 /**
  * Check whether a role is allowed to access an action from a resource
  *
  * <code>
  * //Does Andres have access to the customers resource to create?
  * $acl->isAllowed('Andres', 'Products', 'create');
  *
  * //Do guests have access to any resource to edit?
  * $acl->isAllowed('guests', '*', 'edit');
  * </code>
  *
  * @param  string $roleName
  * @param  string $resourceName
  * @param  mixed $accessName
  * @return boolean
  */
 public function isAllowed($roleName, $resourceName, $accessName)
 {
     $exists = $this->_db->fetchOne('SELECT id FROM ' . $this->_options['roles'] . " WHERE name = ?", null, [$roleName]);
     if (!array_key_exists(0, $exists)) {
         throw new \Engine\Exception("Role '" . $roleName . "' does not exist in ACL");
     }
     $roleId = $exists[0];
     $exists = $this->_db->fetchOne('SELECT id FROM ' . $this->_options['resources'] . " WHERE name = ?", null, [$resourceName]);
     if (!$exists[0]) {
         throw new \Engine\Exception("Resource '" . $resourceName . "' does not exist in ACL");
     }
     $resourceId = $exists[0];
     $sql = 'SELECT id FROM ' . $this->_options['resourcesAccesses'] . " WHERE resource_id = ? AND name = ?";
     $exists = $this->_db->fetchOne($sql, null, [$resourceId, $accessName]);
     if (!$exists[0]) {
         throw new \Engine\Exception("Access '" . $accessName . "' does not exist in resource '" . $resourceName . "' in ACL");
     }
     $accessId = $exists[0];
     $sql = 'SELECT id FROM ' . $this->_options['resourcesAccesses'] . " WHERE resource_id = ? AND name = ?";
     $exists = $this->_db->fetchOne($sql, null, [$resourceId, '*']);
     if (!$exists[0]) {
         throw new \Engine\Exception("Access '*' does not exist in resource '" . $resourceName . "' in ACL");
     }
     $accessIdZero = $exists[0];
     /**
      * Check if there is a specific rule for that resource/access
      */
     $sql = 'SELECT allowed FROM ' . $this->_options['accessList'] . " WHERE role_id = ? AND resource_id = ? AND access_id = ?";
     $allowed = $this->_db->fetchOne($sql, \Phalcon\Db::FETCH_NUM, [$roleId, $resourceId, $accessId]);
     if (is_array($allowed)) {
         return (int) $allowed[0];
     }
     /**
      * Check if there is an common rule for that resource
      */
     /*$sql = 'SELECT COUNT(*) FROM '.$this->_options['accessList']." WHERE role_id = ? AND resource_id = ? AND access_id = ?";
     		$allowed = $this->_db->fetchOne($sql, \Phalcon\Db::FETCH_NUM, [$roleId, $resourceId, $accessIdZero]);
     		if (is_array($allowed)) {
     			return (int) $allowed[0];
     		}*/
     $sql = 'SELECT inherit_role_id FROM ' . $this->_options['rolesInherits'] . ' WHERE role_id = ?';
     $inheritedRoles = $this->_db->fetchAll($sql, \Phalcon\Db::FETCH_NUM, [$roleId]);
     /**
      * Check inherited roles for a specific rule
      */
     foreach ($inheritedRoles as $row) {
         $sql = 'SELECT allowed FROM ' . $this->_options['accessList'] . " WHERE role_id = ? AND resource_id = ? AND access_id = ?";
         $allowed = $this->_db->fetchOne($sql, \Phalcon\Db::FETCH_NUM, [$row[0], $resourceId, $accessId]);
         if (is_array($allowed)) {
             return (int) $allowed[0];
         }
     }
     /**
      * Check if there is a common rule for that access
      */
     $exists = $this->_db->fetchOne('SELECT id FROM ' . $this->_options['resources'] . " WHERE name = ?", null, ['*']);
     if (!$exists[0]) {
         throw new \Engine\Exception("Resource '*' does not exist in ACL");
     }
     $resourceIdZero = $exists[0];
     $sql = 'SELECT allowed FROM ' . $this->_options['accessList'] . " WHERE role_id = ? AND resource_id = ? AND access_id = ?";
     $allowed = $this->_db->fetchOne($sql, \Phalcon\Db::FETCH_NUM, [$roleId, $resourceIdZero, $accessId]);
     if (is_array($allowed)) {
         return (int) $allowed[0];
     }
     /**
      * Return the default access action
      */
     return $this->_defaultAccess;
 }
 /**
  * @param Event $event
  * @param Pdo   $connection
  */
 public function beforeQuery($event, $connection)
 {
     $this->_profiler->startProfile($connection->getRealSQLStatement(), $connection->getSQLVariables(), $connection->getSQLBindTypes());
 }