Example #1
0
 /**
  * Inserts/Updates a permission in the access list
  *
  * @param  string                 $roleName
  * @param  string                 $resourceName
  * @param  string                 $accessName
  * @param  integer                $action
  * @return boolean
  * @throws \Phalcon\Acl\Exception
  */
 protected function insertOrUpdateAccess($roleName, $resourceName, $accessName, $action)
 {
     /**
      * Check if the access is valid in the resource
      */
     $sql = "SELECT COUNT(*) FROM {$this->resourcesAccesses} WHERE resources_name = ? AND access_name = ?";
     $exists = $this->connection->fetchOne($sql, null, [$resourceName, $accessName]);
     if (!$exists[0]) {
         throw new Exception("Access '{$accessName}' does not exist in resource '{$resourceName}' in ACL");
     }
     /**
      * Update the access in access_list
      */
     $sql = "SELECT COUNT(*) FROM {$this->accessList} " . " WHERE roles_name = ? AND resources_name = ? AND access_name = ?";
     $exists = $this->connection->fetchOne($sql, null, [$roleName, $resourceName, $accessName]);
     if (!$exists[0]) {
         $sql = "INSERT INTO {$this->accessList} VALUES (?, ?, ?, ?)";
         $params = [$roleName, $resourceName, $accessName, $action];
     } else {
         $sql = "UPDATE {$this->accessList} SET allowed = ? " . "WHERE roles_name = ? AND resources_name = ? AND access_name = ?";
         $params = [$action, $roleName, $resourceName, $accessName];
     }
     $this->connection->execute($sql, $params);
     /**
      * Update the access '*' in access_list
      */
     $sql = "SELECT COUNT(*) FROM {$this->accessList} " . "WHERE roles_name = ? AND resources_name = ? AND access_name = ?";
     $exists = $this->connection->fetchOne($sql, null, [$roleName, $resourceName, '*']);
     if (!$exists[0]) {
         $sql = "INSERT INTO {$this->accessList} VALUES (?, ?, ?, ?)";
         $this->connection->execute($sql, [$roleName, $resourceName, '*', $this->_defaultAccess]);
     }
     return true;
 }
Example #2
0
 /**
  * @param  array $attributes
  * @param  array $whiteList
  *
  * @return boolean
  * @throws Exception
  */
 private function makeRoot($attributes, $whiteList)
 {
     $owner = $this->getOwner();
     $owner->{$this->rootAttribute} = 0;
     $owner->{$this->leftAttribute} = 1;
     $owner->{$this->rightAttribute} = 2;
     $owner->{$this->levelAttribute} = 1;
     if ($this->hasManyRoots) {
         $this->db->begin();
         $this->ignoreEvent = true;
         if ($owner->create($attributes, $whiteList) == false) {
             $this->db->rollback();
             $this->ignoreEvent = false;
             return false;
         }
         $pk = $owner->{$this->rootAttribute} = $owner->{$this->primaryKey};
         $owner::findFirst($pk)->update([$this->rootAttribute => $pk]);
         $this->ignoreEvent = false;
         $this->db->commit();
     } else {
         if (count($owner->roots())) {
             throw new Exception('Cannot create more than one root in single root mode.');
         }
         if ($owner->create($attributes, $whiteList) == false) {
             return false;
         }
     }
     return true;
 }
Example #3
0
 /**
  * Gets number of rows returned by a resulset
  *
  *<code>
  *  $result = $connection->query("SELECT * FROM robots ORDER BY name");
  *  echo 'There are ', $result->numRows(), ' rows in the resulset';
  *</code>
  *
  * @return int
  */
 public function numRows()
 {
     $rowCount = $this->_rowCount;
     if ($rowCount === false) {
         switch ($this->_connection->getType()) {
             case 'mysql':
                 $rowCount = $this->_pdoStatement->rowCount();
                 break;
             case 'pgsql':
                 $rowCount = $this->_pdoStatement->rowCount();
                 break;
         }
         if ($rowCount === false) {
             //SQLite/Oracle/SQLServer returns resultsets that to the client eyes (PDO) has an
             //arbitrary number of rows, so we need to perform an extra count to know that
             $sqlStatement = $this->_sqlStatement;
             //If the sql_statement starts with SELECT COUNT(*) we don't make the count
             if (strpos($sqlStatement, 'SELECT COUNT(*) ') !== 0) {
                 $bindParams = $this->_bindParams;
                 $bindTypes = $this->_bindTypes;
                 $matches = null;
                 if (preg_match("/^SELECT\\s+(.*)\$/i", $sqlStatement, $matches) == true) {
                     $rowCount = $this->_connection->query("SELECT COUNT(*) \"numrows\" FROM (SELECT " . $matches[0] . ')', $bindParams, $bindTypes)->fetch()->numRows();
                 }
             } else {
                 $rowCount = 1;
             }
         }
         //Update the value to avoid further calculations
         $this->_rowCount = $rowCount;
     }
     return $rowCount;
 }
Example #4
0
 /**
  * (PHP 5 &gt;= 5.0.0)<br/>
  * Return the current element
  * @link http://php.net/manual/en/iterator.current.php
  * @return mixed Can return any type.
  */
 public function current()
 {
     $limit_start = $this->position * $this->perSize;
     $this->dbConnection->connect();
     $result = $this->dbConnection->query($this->sql . " LIMIT {$limit_start},{$this->perSize}");
     $result->setFetchMode(Db::FETCH_ASSOC);
     return $result->fetchAll();
 }
Example #5
0
 /**
  * @param Event $event
  * @param DbAdapterInterface $connection
  */
 public function afterQuery(Event $event, DbAdapterInterface $connection)
 {
     $this->_profiler->stopProfile();
     $sqlVariables = $connection->getSQLVariables() ?: [];
     foreach ($sqlVariables as $key => $value) {
         if ($key[0] !== ':') {
             unset($sqlVariables[$key]);
             $key = ':' . $key;
         }
         $sqlVariables[$key] = !is_array($value) ? $connection->escapeString((string) $value) : array_map(function ($v) use($connection) {
             return $connection->escapeString((string) $v);
             // important
         }, $value);
     }
     $statement = strtr($connection->getRealSQLStatement(), $sqlVariables);
     $time = $this->_profiler->getTotalElapsedSeconds() - $this->_previousTotalExecutionTime;
     $this->_previousTotalExecutionTime = $this->_profiler->getTotalElapsedSeconds();
     $this->_logger->log(sprintf('%s [Execution time: %.4f sec.]', $statement, round($time, 4)), $this->_priority);
 }
 public static function setCurrentVersion($lastVersion, $currentVersion)
 {
     if (is_null(self::$_connection)) {
         self::connSetup(self::$_config->get('database'));
     }
     if (!is_null(self::$_config->get('migrationsLog')) && 'database' == self::$_config->get('migrationsLog')) {
         self::$_connection->execute('UPDATE `phalcon_migrations` SET `version`="' . (string) $currentVersion . '" WHERE `version`="' . (string) $lastVersion . '" LIMIT 1;');
     } else {
         file_put_contents(self::$_migrationFid, (string) $currentVersion);
     }
 }
 /**
  * Find if entity with those constraint is exist
  *
  * @return bool true if exist
  */
 private function isEntityExist(array $field, $withField = [])
 {
     if (!$this->getOption('table')) {
         throw new Exception("table option is required");
     }
     $query = "SELECT id FROM {$this->getOption('table')} WHERE {$field['id']} = '{$field['value']}'";
     if (sizeof($withField) > 0) {
         $query .= "AND {$withField['id']} = '{$withField['value']}'";
     }
     $result = $this->db->fetchOne($query);
     // Check is it itself
     // If yess, pass
     $entity = $this->getOption('entity');
     if ($entity) {
         if (!property_exists($entity, 'id')) {
             throw new Exception('Entity must have public id property');
         }
         // In datastore is itself, so pass
         if ((int) $result['id'] === (int) $entity->id) {
             return false;
         }
     }
     return (bool) $result;
 }
Example #8
0
 /**
  * Delete the migration datasets from the table
  *
  * @param string $tableName
  */
 public function batchDelete($tableName)
 {
     $migrationData = self::$_migrationPath . $this->_version . '/' . $tableName . '.dat';
     if (!file_exists($migrationData)) {
         return;
         // nothing to do
     }
     self::$_connection->begin();
     self::$_connection->delete($tableName);
     $batchHandler = fopen($migrationData, 'r');
     while (($line = fgets($batchHandler)) !== false) {
         $data = explode('|', rtrim($line), 2);
         self::$_connection->delete($tableName, 'id=?', [$data[0]]);
         unset($line);
     }
     fclose($batchHandler);
     self::$_connection->commit();
 }
Example #9
0
 /**
  * {@inheritdoc}
  *
  * @return bool
  */
 public function flush()
 {
     $this->db->execute("DELETE FROM {$this->table}");
     return true;
 }
Example #10
0
 /**
  * Rollback transaction
  * (happens automatically if commit never reached)
  *
  * @return $this
  */
 public function rollback()
 {
     $this->db->rollback();
     return $this;
 }
Example #11
0
 /**
  * {@inheritdoc}
  *
  * @return boolean
  */
 public function flush()
 {
     $this->db->execute('DELETE FROM ' . $this->table);
     return true;
 }
Example #12
0
 /**
  * @param Event              $event
  * @param DbAdapterInterface $db
  */
 public function beforeQuery(Event $event, DbAdapterInterface $db, $data)
 {
     $this->logger->debug($db->getSQLStatement());
 }
Example #13
0
 protected function assertProtectedPropertyEquals($propertyName, $tableName, DbAdapter $connection, Database $adapter)
 {
     $property = new ReflectionProperty(self::ADAPTER_CLASS, $propertyName);
     $property->setAccessible(true);
     $this->assertEquals($connection->escapeIdentifier($tableName), $property->getValue($adapter));
 }
Example #14
0
 /**
  * {@inheritdoc}
  * @param  integer $maxlifetime
  *
  * @return boolean
  */
 public function gc($maxlifetime)
 {
     $options = $this->getOptions();
     return $this->connection->execute(sprintf('DELETE FROM %s WHERE COALESCE(%s, %s) + %d < ?', $this->connection->escapeIdentifier($options['table']), $this->connection->escapeIdentifier($options['column_modified_at']), $this->connection->escapeIdentifier($options['column_created_at']), $maxlifetime), [time()]);
 }
Example #15
0
 /**
  * Checks whether internal connection is under an active transaction
  *
  * @return boolean
  */
 public function isValid()
 {
     return $this->_connection->isUnderTransaction();
 }
Example #16
0
 /**
  * Allows to executes the statement again. Some database systems don't support scrollable cursors,
  * So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining
  * @return mixed
  */
 public function execute()
 {
     $this->_connection->setConsistency($this->_consistency);
     return $this->_connection->query($this->_clqStatement, $this->_bindParams, $this->_bindTypes);
 }