public function login($f3, $args)
 {
     self::check_configuration();
     $params = json_decode($f3->get('BODY'));
     if ($params->username && $params->password) {
         $login = new DB\Jig\Mapper($this->db, 'users.json');
         $temp = $login->find(array('(isset(@userName) && @userName == ?)', $params->username));
         if ($temp) {
             $first = __::first($temp);
             if (password_verify($params->password, $first['password'])) {
                 $date = new DateTime();
                 $date->add(new DateInterval('PT' . F3::get('custom.TTL') . 'H'));
                 $out = array('username' => $first['userName'], 'userid' => $first['_id'], 'ttl' => $date->format('Y-m-d H:i:s'), 'roles' => self::get_roles($first['_id']));
                 $jwt = JWT::encode($out, F3::get('custom.SUPER-KEY'));
                 echo json_encode(array('token' => $jwt, 'data' => array('firstName' => $first['firstName'], 'lastName' => $first['lastName'], 'userName' => $first['userName'])));
             } else {
                 self::wrong_login();
             }
         } else {
             self::wrong_login();
         }
     } else {
         self::wrong_login();
     }
 }
 public function testHasAccessToStrMethods()
 {
     $string1 = Strings::limit('foo', 1);
     $string2 = Underscore::from('foo')->limit(1)->obtain();
     $this->assertEquals('f...', $string1);
     $this->assertEquals('f...', $string2);
 }
Esempio n. 3
0
 /**
  * Slugify a string
  *
  * Simplified slugify that only passes in alphanumeric characters, and replaces runs of others with dashes.
  * Also only allows alphanumeric characters on start and end.
  * The result is usable as a part of DNS domain name.
  */
 public static function slugify($string, $maxLength = 255, $hashLength = 6)
 {
     mb_regex_encoding('UTF-8');
     $hash = mb_substr(hash('sha256', $string), 0, (int) $hashLength);
     $sanitized = static::sanitize($string);
     $sanitized = static::maxLength($sanitized, (int) $maxLength - ($hashLength ? (int) $hashLength + 1 : 0));
     $sanitized = static::trimNonAlnumEnds($sanitized);
     // Add partial hash in order to prevent empty or duplicate slugs
     $sanitized = implode('-', _::filter([$sanitized, $hash]));
     return $sanitized;
 }
 public function testWrapAndUnwrap()
 {
     $collection = new TestCollection(['a', 'b', 'c']);
     // Wrap and unwrap the collection
     $unwrapped = Underscore::from($collection)->collection();
     // The collection should a clone
     $this->assertNotSame($collection, $unwrapped);
     // But should be the same type
     $this->assertInstanceOf(get_class($collection), $unwrapped);
     // And have the same values
     $this->assertSame($collection->toArray(), $unwrapped->toArray());
 }
 public function check_permissions($operation, $table, $token)
 {
     $basic_tables = array('forms', 'dictionaries', 'users', 'roles', 'permissions');
     //TODO: tablas basicas -> roles, users, etc   --- forms siempre lo puede leer
     $error_message = 'Operation not permited by permissions';
     if (in_array($table, array('forms', 'permissions', 'dictionaries')) && $operation == 'R') {
         // anyone can read the 'forms','permissions','dictionaries'
         return true;
     } else {
         if (in_array($table, $basic_tables)) {
             // echo "uname ".$token->username;
             if ($token->username == 'admin') {
                 // only the admin can do any operation on the admin tables, TODO: other admin users
                 return true;
             } else {
                 self::show_error($error_message, 403);
             }
         } else {
             $forms = new DB\Jig\Mapper($this->db, 'forms.json');
             $forms_list = $forms->find(array('(isset(@uniqId) && @uniqId == ?)', $table));
             $form_id = $forms_list[0]['_id'];
             if ($form_id) {
                 $permissions_table = new DB\Jig\Mapper($this->db, 'permissions.json');
                 $permissions = $permissions_table->find();
                 $first_row = __::first($permissions);
                 $matrix = json_decode($first_row['matrix']);
                 if (count($matrix)) {
                     foreach ($matrix as $v1) {
                         foreach ($v1 as $v2) {
                             foreach ($v2 as $v3) {
                                 if ($v3->s && $v3->o == $operation && in_array($v3->r, $token->roles) && $v3->f == $form_id) {
                                     $valid = true;
                                 }
                             }
                         }
                     }
                 } else {
                     self::show_error($error_message, 403);
                 }
                 if (!$valid) {
                     self::show_error($error_message, 403);
                 }
             } else {
                 // TODO: Table not found
                 // self::show_error('Table not found',404);
             }
         }
     }
 }
function _forge($classname)
{
    return Underscore::forge($classname);
}
Esempio n. 7
0
 public function testThrowsErrorIfIncorrectMethod()
 {
     $this->setExpectedException('BadMethodCallException');
     Underscore::invalid('foo');
 }
Esempio n. 8
0
 public function testCanCreateChainableObject()
 {
     $under = Underscore::from($this->arrayNumbers);
     $under = $under->get(1);
     $this->assertEquals(2, $under);
 }
 public function testUnderscoreFindsRightClassToCall()
 {
     $numbers = array(3, 4, 5);
     $product = Underscore::reduce($numbers, function ($w, $v) {
         return $w * $v;
     }, 1);
     $this->assertEquals(60, $product);
 }
 private function filterModels($filter)
 {
     if (is_array($filter)) {
         foreach ($filter as $key => $keyValue) {
             if (is_array($keyValue)) {
                 if ($keyValue[0] == 'strict') {
                     $this->allModels = Arrays::filter($this->allModels, function ($value) use($key, $keyValue) {
                         return $value[$key] == $keyValue[1];
                     });
                 }
             } elseif (is_bool($keyValue)) {
                 $this->allModels = Arrays::filterBy($this->allModels, $key, $keyValue);
             } else {
                 // todo: Optimize filter with param for "like" and "equal" filtering
                 if ($key === 'slug') {
                     $this->allModels = Arrays::filterBy($this->allModels, $key, $keyValue);
                 } else {
                     $this->allModels = Arrays::filter($this->allModels, function ($value) use($key, $keyValue) {
                         if (!empty($value[$key]) && is_array($value[$key])) {
                             $value[$key] = Arrays::implode($value[$key], "||");
                         } elseif (strpos($key, "|") !== false) {
                             $key = str_replace("|", ".", $key);
                         }
                         $array = new Underscore($value);
                         return stripos($array->get($key), html_entity_decode($keyValue)) !== false;
                     });
                 }
             }
         }
     }
 }
Esempio n. 11
0
function _getParameters(ReflectionMethod $method)
{
    return _::chain($method->getParameters())->map(function ($parameter) {
        return (object) ['name' => $parameter->name, 'isReference' => $parameter->isPassedByReference(), 'hasDefaultValue' => $parameter->isDefaultValueAvailable(), 'default' => $parameter->isDefaultValueAvailable() ? _valueToString($parameter->getDefaultValue()) : null, 'type' => '', 'description' => '', 'reflect' => $parameter];
    })->invoke(function () {
        $this->asStringNoRefNoValue = "\${$this->name}";
        $this->asStringNoRef = "\${$this->name}" . ($this->hasDefaultValue ? "={$this->default}" : '');
        $this->asString = ($this->isReference ? '&' : '') . "\${$this->name}" . ($this->hasDefaultValue ? "={$this->default}" : '');
    })->indexBy('name')->value();
}
Esempio n. 12
0
 public function get_last($f3, $args)
 {
     $filter = json_decode(explode('=', $args[0])[1], true);
     // json -> array
     if ($filter['table']) {
         $table = new \DB\Jig\Mapper($this->db, $filter['table'] . '.json');
         echo json_encode(array(__::last(self::query_builder($filter, $table))));
     } else {
         Common::show_error('Table name required', 500);
     }
 }
Esempio n. 13
0
 public function __construct($method, $url)
 {
     if (!count(self::$directories)) {
         throw new \Exception('No controller directories have been registered! (Use Controller::registerDirectory(...))');
     }
     $this->method = strtoupper($method);
     $url = parse_url($url);
     $this->scheme = !empty($url['scheme']) ? $url['scheme'] : (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http');
     $this->host = !empty($url['host']) ? $url['host'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
     $this->port = !empty($url['port']) ? $url['port'] : (isset($_SERVER['HTTP_PORT']) ? $_SERVER['HTTP_PORT'] : '');
     $this->path = !empty($url['path']) ? trim($url['path'], '/') : '';
     $this->query = !empty($url['query']) ? $url['query'] : '';
     $sep = DIRECTORY_SEPARATOR;
     $this->segments = Controller::cleanPath($this->path);
     $max = null;
     foreach (self::$directories as $dir) {
         $info = ['dir' => $dir, 'args' => [], 'file' => $this->segments, 'extension' => ''];
         if ($dir['prefix']) {
             $prefix = Controller::cleanPath($dir['prefix']);
             if ($prefix == (array) _::first($this->segments, count($prefix))) {
                 $info['file'] = (array) _::rest($this->segments, count($prefix));
             }
         }
         if ($dir['extensions']) {
             if ($dir['extensions'] && count($info['file']) > 0) {
                 $lastIndex = count($info['file']) - 1;
                 $fileParts = explode('.', $info['file'][$lastIndex], 2);
                 if (count($fileParts) == 2) {
                     if (is_string($dir['extensions'])) {
                         $dir['extensions'] = [$dir['extensions']];
                     }
                     if (!is_array($dir['extensions']) || is_array($dir['extensions']) && count(array_filter($dir['extensions'], function ($prefix) {
                         return strpos($this->path, $prefix . '/') === 0 || strpos($this->path, $prefix . '.') === 0 || trim($prefix, '/') === $this->path;
                     }))) {
                         $info['extension'] = $fileParts[1];
                         $info['file'][$lastIndex] = $fileParts[0];
                     }
                 }
             }
         }
         do {
             $file = implode($sep, $info['file']);
             if (is_file("{$info['dir']['path']}{$sep}{$file}{$sep}_default.php") && ($info['file'][] = '_default')) {
                 break;
             }
             if (is_file("{$info['dir']['path']}{$sep}{$file}.php")) {
                 break;
             }
             array_unshift($info['args'], $slug = array_pop($info['file']));
         } while ($slug);
         if (!$max || count(_::reject($info['file'], function ($f) {
             return $f == '_default';
         })) > count(_::reject($max['file'], function ($f) {
             return $f == '_default';
         }))) {
             $max = $info;
         }
     }
     if (!$max || !$max['file']) {
         throw new \Exception('Invalid controller path. Maybe you don\'t have a _default.php file.');
     }
     $this->dir = $max['dir'];
     $this->args = $max['args'];
     $this->file = $max['file'];
     $this->extension = $max['extension'];
     $this->responseHeaders = new HttpHeaders();
 }
Esempio n. 14
0
 /**
  * @tags forgery
  */
 public function testForge()
 {
     _::forge('stdClass\\with\\Traits\\A\\with\\Traits\\B\\with\\Traits\\C');
     $this->boolean(class_exists('stdClass\\with\\Traits\\A\\with\\Traits\\B\\with\\Traits\\C', false))->isTrue();
     // it doesn't create intermediary classes
     $this->boolean(class_exists('stdClass\\widh\\tA', false))->isFalse();
     $object = new \stdClass\with\Traits\A\with\Traits\B\with\Traits\C();
     $this->integer($object->fnC())->isEqualTo(3);
 }
Esempio n. 15
0
 public function testShuffle()
 {
     $original = $this->getDummy3();
     $values = Underscore::from($original)->shuffle()->toArray();
     // Not necessarily the same, but contains the same values.
     // We cannot check the sorting of the keys because it is entirely
     // possible that keys were not randomized at all!
     $this->assertEquals($original, $values);
 }