Exemple #1
0
 public static function filterSimplify(Context $context)
 {
     if ($context->value !== NULL) {
         $context->value = Strings::simplify($context->value);
     }
     return TRUE;
 }
Exemple #2
0
 /**
  * Returns parsed path components without escape characters.
  *
  * <code>
  * FileSystem::getPathComponents('a/b/c'); // returns array('a', 'b', 'c')
  * FileSystem::getPathComponents('a/b/c/'); // returns array('a', 'b', 'c')
  * FileSystem::getPathComponents('/a/b/c'); // returns array('', 'a', 'b', 'c')
  * </code>
  *
  * @see FileSystem::joinPathComponents()
  * @uses Strings::splitWithEscape()
  *
  * @param string path
  * @param char directory separator
  *
  * @return string
  */
 static function getPathComponents($path, $separator = DIRECTORY_SEPARATOR)
 {
     if ($path == '') {
         return array();
     }
     $tokens = Strings::splitWithEscape($path, $separator, $separator == '\\' ? '\\\\' : '\\', false);
     // We need to ignore all empty values except for first
     $components = array();
     foreach ($tokens as $t) {
         if ($t == '' && count($components)) {
             continue;
         }
         $components[] = $t;
     }
     return $components;
 }
 /**
  * Creates IIdentity object from obtained user data
  *
  * @param mixed user data
  * @param IAuthenticator authenticator
  *
  * @return IIdentity
  */
 public function createIdentity($userData, $authenticator)
 {
     $uid = NULL;
     $roles = array();
     $profile = array();
     // ---------------------------------------------------------------------
     // DB Password
     if ($authenticator instanceof Authenticators\DatabasePasswordAuthenticator) {
         $uid = (int) $userData->{$authenticator->getColumn($authenticator::ID)};
         $profile = $userData;
     } elseif ($authenticator instanceof Authenticators\LdapBindAuthenticator) {
         $ldapData = (array) $userData;
         $idCol = 'id';
         $tableName = 'security_users';
         // LDAP Binding
         // DB column name -> ldap array key (or callable)
         $binding = array(array('username' => function ($ldapData) use($authenticator) {
             return mb_substr($ldapData['dn'], mb_strlen($authenticator->getQueryPrefix()), 0 - mb_strlen($authenticator->getQuerySuffix()));
         }), array('name' => 'givenName', 'surname' => 'sn', 'email' => function ($ldapData) use(&$binding) {
             $username = $binding[0]['username']($ldapData);
             $tokens = Strings::splitWithEscape($ldapData['dn'], ',dc=');
             array_shift($tokens);
             return $username . '@' . implode($tokens, '.');
         }));
         // Prepare data based on LDAP binding
         $boundData = $this->bindValues($ldapData, $binding[0]);
         $this->db->query('LOCK TABLES %n WRITE', $tableName);
         $ds = $this->db->select('*')->from($tableName);
         foreach ($boundData as $key => $value) {
             $ds->where('%n = %s', $key, $value);
         }
         $profile = $ds->fetch();
         // If profile does not exist yet
         if ($profile === FALSE) {
             $boundData = array_merge($boundData, $this->bindValues($ldapData, $binding[1]));
             $this->db->insert($tableName, $boundData)->execute();
             $boundData[$idCol] = $uid = (int) $this->db->getInsertId();
             $profile = $boundData;
         } else {
             $uid = (int) $profile[$idCol];
         }
         $this->db->query('UNLOCK TABLES');
         // TODO: configurable
         $groupsDn = NULL;
         if ($groupsDn == NULL) {
             $dnTokens = array_reverse($userData->getParsedDn());
             foreach ($dnTokens as $k => $v) {
                 if (!Strings::startsWith($v, 'dc=')) {
                     array_splice($dnTokens, $k, count($dnTokens), array('ou=groups'));
                     break;
                 }
             }
             $groupDn = implode(array_reverse($dnTokens), ',');
         }
         $username = str_replace(array('\\', ')'), array('\\\\', '\\)'), $boundData['username']);
         $userGid = intval($userData->gidNumber);
         $filter = "(&(objectClass=posixGroup)(|(gidNumber={$userGid})(memberUid={$username})))";
         $result = $authenticator->ldapConnection->search($groupsDn, $filter);
         foreach ($result as $record) {
             $roles[] = $record->cn;
         }
     } elseif ($authenticator instanceof Authenticators\DatabasePSKAuthenticator) {
         $uid = Strings::intoParameterizedString('psk', array($userData->key));
         $roles[] = $uid;
         $profile = $userData;
         // Other authenticators
     } else {
         throw new Nette\NotSupportedException("Authenticator " . get_class($authenticator) . " not supported yet");
     }
     // ---------------------------------------------------------------------
     // Remove duplicit roles
     $roles = array_unique($roles);
     // Sanity check
     if (!is_scalar($uid) || $uid == "") {
         throw new Nette\InvalidStateException("User ID has to be non-empty string or number");
     }
     // ---------------------------------------------------------------------
     // Query roles from DB if it's not PSK (has user id)
     if (is_int($uid)) {
         $roles = array_merge($this->getUserRoles($uid), $roles);
     }
     // ---------------------------------------------------------------------
     // Identity
     $identity = new Nette\Security\Identity($uid, $roles, $profile);
     return $identity;
 }
Exemple #4
0
 public function parseContext(Context $context, $baseKey = array())
 {
     $success = TRUE;
     $oldBaseKey = $context->baseKey;
     $oldRule = $context->rule;
     $context->baseKey = $baseKey;
     $context->setRule();
     $keys = is_array($context->value) ? array_flip(array_keys($context->value)) : array();
     foreach ($this as $k => $rules) {
         unset($keys[$k]);
         if (!$rules->parse($context)) {
             $success = FALSE;
         }
     }
     foreach ($keys as $k => $v) {
         $success = FALSE;
         $key = $baseKey;
         $key[] = $k;
         $context->errors[] = array($key, Strings::sprintf('Unexpected parameter %key.', array('key' => $context->getPrintableKey($key))));
     }
     $context->baseKey = $oldBaseKey;
     $context->rule = $oldRule;
     return $success;
 }
Exemple #5
0
 public static function validateArrayOfStructure(Context $context, ArrayParser $nestedParser)
 {
     if (!is_array($context->value)) {
         return Strings::sprintf('Invalid value for parameter %key. Expected array.', array('key' => $context->printableKey));
     }
     $success = TRUE;
     foreach ($context->value as $k => $v) {
         $key = $context->absoluteKey;
         $key[] = $k;
         if (!$nestedParser->parseContext($context, $key)) {
             $success = FALSE;
         }
     }
     return $success;
 }
 /**
  * Sets page author
  *
  * @param string|false author's name
  * @return MetaDataProvider fluent
  */
 public function setAuthor($name)
 {
     $this->updating();
     if ($name === false) {
         $this->_author = false;
         return $this;
     }
     $this->_author = Strings::simplify($name);
     return $this;
 }
 /**
  * Translates URL to production
  * Example: test.mujweb.cz/12 -> www.mujweb.cz/12
  *
  * @param Nette\Http\Url test url
  * @return Nette\Http\Url|NULL production url or NULL if translation can't be derived
  */
 protected function translateUrl(Nette\Http\Url $url)
 {
     if ($matches = Strings::match($url->host, '#^(.+?\\.)?test\\.([^\\.]+\\.[^\\.]+)$#')) {
         $newHost = $matches[1] . $matches[2];
         $url = clone $url;
         $url->host = $newHost;
         return $url;
     }
     return NULL;
 }
Exemple #8
0
 /**
  * This method will be called when the component (or component's parent)
  * becomes attached to a monitored object. Do not call this method yourself.
  *
  * @param  Nette\ComponentModel\IComponent
  * @return void
  */
 protected function attached($parent)
 {
     parent::attached($parent);
     // Creates session storage for each instance of DataTable
     $context = $parent->getPresenter()->getContext();
     $sessionSection = $context->session->getSection(strtr(__CLASS__, '\\', '.'));
     $this->session =& $sessionSection->{$this->getUniqueId()};
     if ($this->session == NULL) {
         $this->session = new \StdClass();
     }
     // Creates unique authorization token (CSRF prevention)
     if (!isset($this->session->authToken)) {
         $this->session->authToken = vBuilder\Utils\Strings::randomHumanToken(8);
     }
 }
Exemple #9
0
// TODO: Podpora pro uziv. role
use vBuilder\Security\User, vBuilder\Utils\CliArgsParser, vBuilder\Utils\Strings, vBuilder\Security\IdentityFactory;
$container = (require __DIR__ . '/bootstrap.php');
// -----------------------------------------------------------------------------
// ARGUMENTS
// -----------------------------------------------------------------------------
$args = new CliArgsParser();
$args->addOption('password', 'secret', 'user password', NULL)->setNumRequiredArgs(1, 1)->setArgumentHelp('username');
if (!$args->parse()) {
    echo "\n" . $args->getErrorMsg() . "\n\n";
    $args->printUsage();
    echo "\n";
    exit;
}
list($user) = $args->getArguments();
$password = $args->get('password') !== FALSE ? $args->get('password') : Strings::randomHumanToken();
// -----------------------------------------------------------------------------
// INIT
// -----------------------------------------------------------------------------
$db = $container->getByType('DibiConnection');
$authn = $container->user->getAuthenticator(User::AUTHN_METHOD_PASSWORD, User::AUTHN_SOURCE_DATABASE);
$rolesTable = $authn->identityFactory->getTableName(IdentityFactory::TABLE_ROLES);
$roles = array('Administrator');
// -----------------------------------------------------------------------------
// DB
// -----------------------------------------------------------------------------
$data = array($authn->getColumn($authn::USERNAME) => $user, $authn->getColumn($authn::PASSWORD) => $authn->getPasswordHasher()->hashPassword($password));
try {
    $db->query("INSERT INTO %n", $authn->tableName, $data);
    $uid = $db->getInsertId();
    echo "ID noveho uzivatele: {$uid}\n";
Exemple #10
0
 /**
  * @param string $file path to a file or just filename
  */
 public static function isImage($file)
 {
     $extension = pathinfo($file, PATHINFO_EXTENSION);
     if (file_exists($file)) {
         $mime = static::getMimeType($file);
         $byMime = Strings::startsWith($mime, 'image');
     } else {
         if (!$extension) {
             return false;
         }
         // we only have the filename and therefore we can only use the extension.
         // we will not care about mime-type
         $byMime = true;
     }
     $byExtension = in_array(Strings::lower($extension), array('jpg', 'png', 'bmp', 'gif'));
     return $byMime && $byExtension;
 }
 /**
  * Performs a depth-first search of the Role DAG, starting at $role, in order to find a rule
  * allowing/denying $role access to a/all $privilege upon $resource.
  * @param  bool  all (true) or one?
  * @param  string
  * @param  string
  * @param  string  only for one
  * @return mixed  NULL if no applicable rule is found, otherwise returns ALLOW or DENY
  */
 private function searchRolePrivileges($all, $role, $resource, $privilege)
 {
     $dfs = array('visited' => array(), 'stack' => array($role));
     while (NULL !== ($role = array_pop($dfs['stack']))) {
         if (isset($dfs['visited'][$role])) {
             continue;
         }
         if ($all) {
             if ($rules = $this->getRules($resource, $role)) {
                 foreach ($rules['byPrivilege'] as $privilege2 => $rule) {
                     if (self::DENY === $this->getRuleType($resource, $role, $privilege2)) {
                         return self::DENY;
                     }
                 }
                 if (NULL !== ($type = $this->getRuleType($resource, $role, NULL))) {
                     return $type;
                 }
             }
         } else {
             if (NULL !== ($type = $this->getRuleType($resource, $role, $privilege))) {
                 return $type;
             } elseif (NULL !== ($type = $this->getRuleType($resource, $role, NULL))) {
                 return $type;
             }
         }
         $dfs['visited'][$role] = TRUE;
         if (isset($this->roles[$role])) {
             foreach ($this->roles[$role]['parents'] as $roleParent => $foo) {
                 $dfs['stack'][] = $roleParent;
             }
         } elseif ($this->isCompoundName($role)) {
             list($name, $params) = Strings::parseParametrizedString($role);
             $dfs['stack'][] = $name;
         } else {
             throw new Nette\InvalidStateException("Role '{$role}' does not exist.");
         }
     }
     return NULL;
 }
Exemple #12
0
 /**
  * Writes formatted string
  *
  * @param string
  */
 function writef($message, $arguments = array())
 {
     $allArguments = $arguments;
     foreach ($this->presets as $k => $v) {
         if (!array_key_exists($k, $allArguments)) {
             $allArguments[$k] = $this->flags & self::NO_COLORS ? '' : $v;
         }
     }
     return $this->write(Strings::sprintf($message, $allArguments));
 }
Exemple #13
0
 /**
  * Constructor.
  * Takes translator service and prepares URL for save requests
  */
 function __construct(vBuilder\Localization\Translator $translator, Nette\Http\Request $httpRequest, Nette\Http\Session $session, Nette\DI\Container $container)
 {
     $this->translator = $translator;
     $this->httpRequest = $httpRequest;
     $this->basePath = $container->parameters['wwwDir'] . '/..';
     if (!isset(self::$registeredRoute)) {
         throw new Nette\InvalidStateException(__CLASS__ . "::register not called?");
     }
     // Creates unique authorization token (basic CSRF prevention)
     $session = $session->getSection(strtr(__CLASS__, '\\', '.'));
     if (!isset($session->authToken)) {
         $session->authToken = vBuilder\Utils\Strings::randomHumanToken(8);
     }
     $this->authToken = $session->authToken;
 }
 /**
  * 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();
 }
Exemple #15
0
 /**
  * Finds all HTML tags
  *
  * @note Don't forget to call htmlspecialchars_decode() on attributes if necessary.
  *
  * @param string
  * @param string|string[]|NULL tag name, if NULL all tags will be matched
  * @param bool case sensitive?
  * @param bool capture attributes?
  *
  * @return array(array( start, length, tagName ))
  * @throws Nette\InvalidArgumentException if invalid tag name given
  */
 static function findAllTags($str, $tag = NULL, $caseSensitive = TRUE, $captureAttributes = FALSE)
 {
     if ($tag === NULL) {
         $re_name = '(/?[a-z0-9]+)';
     } elseif (is_array($tag) || $tag instanceof \Traversable) {
         $re_name = '';
         foreach ($tag as $name) {
             $re_name .= '|/?' . preg_quote($name, '#');
         }
         if (strlen($re_name) > 1) {
             $re_name = '(' . substr($re_name, 1) . ')';
         }
     } elseif (is_scalar($tag)) {
         $re_name = '(/?' . preg_quote($tag, '#') . ')';
     } else {
         throw new Nette\InvalidArgumentException("Invalid tag name");
     }
     if ($re_name == '') {
         return array();
     }
     $re_flags = '';
     if (!$caseSensitive) {
         $re_flags .= 'i';
     }
     $re_start = '<' . $re_name . '([^a-zA-Z0-9])';
     $re_end = '>';
     $re_s_dq = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
     // Double quotes string with escapes
     $re_s_sq = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
     // Single quotes string with escapes
     $matches = Strings::matchAll($str, "#{$re_start}|{$re_s_dq}|{$re_s_sq}|{$re_end}#sx{$re_flags}", PREG_OFFSET_CAPTURE);
     $info = NULL;
     $matched = array();
     foreach ($matches as $m) {
         // Start tag
         if (strncmp($m[0][0], '<', 1) === 0) {
             // Tag without arguments
             if ($m[2][0] == '>') {
                 $info = array($m[0][1], $m[2][1] - $m[0][1] + 1, $m[1][0]);
                 if ($captureAttributes) {
                     $info[] = array();
                 }
                 $matched[] = $info;
                 $info = NULL;
             } else {
                 $info = array($m[0][1], NULL, $m[1][0]);
             }
         }
         // End tag
         if (strncmp($m[0][0], '>', 1) === 0 && $info !== NULL) {
             $info[1] = $m[0][1] - $info[0] + 1;
             // length
             if ($captureAttributes) {
                 $attributes = array();
                 $attrStr = substr($str, $info[0] + 1, $info[1] - 2);
                 $attrStr = rtrim(substr($attrStr, strlen($info[2])), '/');
                 $attrMatches = Strings::matchAll($attrStr, "#\\s+([^=\\s]+)(=({$re_s_dq}|{$re_s_sq}|\\S+))?#sx");
                 foreach ($attrMatches as $curr) {
                     if (count($curr) == 4) {
                         if (strncmp($curr[3], '"', 1) === 0 || strncmp($curr[3], "'", 1) === 0) {
                             $value = substr($curr[3], 1, -1);
                         } else {
                             $value = $curr[3];
                         }
                     } else {
                         $value = "";
                     }
                     $attributes[$curr[1]] = $value;
                 }
                 $info[] = $attributes;
             }
             $matched[] = $info;
             $info = NULL;
         }
     }
     return $matched;
 }
 /**
  * Creates new preshared secret
  *
  * @param string|NULL note
  * @param DateTime|NULL expiration date
  * @return string[16]
  * @throws Nette\InvalidArgumentException if invalid expiration date
  */
 public function createPsk($expiration = NULL, $note = NULL)
 {
     if ($expiration !== NULL && !$expiration instanceof \DateTime) {
         throw new Nette\InvalidArgumentException("Expected NULL or DateTime instance");
     }
     while (true) {
         $psk = Strings::randomHumanToken(16);
         $values = array($this->fieldName[self::PSK] => $psk, $this->fieldName[self::EXPIRATION] => $expiration, $this->fieldName[self::NOTE] => $note);
         try {
             $this->db->insert($this->tableName, $values)->execute();
             break;
         } catch (\DibiException $e) {
             if ($e->getCode() != 1062) {
                 throw $e;
             }
         }
     }
     return $psk;
 }
Exemple #17
0
use vBuilder\Utils\Classinfo as ClassInfo, vBuilder\Utils\CliArgsParser, vBuilder\Utils\Strings, vBuilder\Orm\DdlHelper;
const ENTITY_CLASS = 'vBuilder\\Orm\\Entity';
$container = (require __DIR__ . '/bootstrap.php');
$db = $container->getByType('DibiConnection');
$args = new CliArgsParser();
$args->setNumRequiredArgs(1, 1);
$args->setArgumentHelp('entity name');
$entities = $container->classInfo->getAllChildrenOf(ENTITY_CLASS);
// -----------------------------------------------------------------------------
if ($args->parse()) {
    list($entityName) = $args->getArguments();
    // PHP >= 5.0.3
    if (!class_exists($entityName) || !is_subclass_of($entityName, ENTITY_CLASS)) {
        $matches = array();
        foreach ($entities as $curr) {
            if (Strings::endsWith($curr, '\\' . $entityName)) {
                $matches[] = $curr;
            }
        }
        if (count($matches) == 0) {
            echo "\n!!! ERROR !!! Entity {$entityName} does not exist.\nHalting.\n\n";
            exit(1);
        } elseif (count($matches) == 1) {
            list($entityName) = $matches;
        } else {
            echo "\n!!! ERROR !!! Given entity name {$entityName} is ambiguous.\n";
            $entities = $matches;
            $entityName = NULL;
        }
    }
    if (isset($entityName)) {