/** * Generate a random slug * * @param integer $slugLength * @param string $slugChars * @return string */ public static function generateRandomSlug($slugLength = 10, $slugChars = null) { if (!$slugChars) { $slugChars = 'abcdefghijklmnopqrstuvwxyz'; } return Rand::getString($slugLength, $slugChars, true); }
public function indexAction() { $this->requireLogin(); $keyRepo = $this->getEntityManager()->getRepository('Frontend\\Api\\Entity\\Key'); $userKey = $keyRepo->findOneBy(array('user' => $this->identity())); if ($this->getRequest()->getQuery('getKey') == 1 && !$userKey) { // add to api $keyChars = array_merge(range(0, 9), range('A', 'Z'), range('a', 'z')); $apiKey = Rand::getString(50, implode('', $keyChars)); $userKey = new Key(); $userKey->setKey($apiKey); $userKey->setLimit($userKey->getDefaultRateLimit()); $userKey->setUser($this->getEntityManager()->getReference('Auth\\Entity\\Benutzer', $this->identity()->getId())); $userKey->setRequests(0); $userKey->setStatus(1); try { $this->getEntityManager()->persist($userKey); $this->getEntityManager()->flush(); $this->flashMessenger()->addSuccessMessage('Nice! Subscribe to API successfully. Can\'t wait to hear about your application'); } catch (\Exception $e) { $this->flashMessenger()->addErrorMessage('Balls...something went wrong :/'); } } $viewModel = new ViewModel(); $viewModel->setTemplate('/api/index.phtml'); $viewModel->setVariable('userKey', $userKey); return $viewModel; }
/** * Add acl resources * * @param array $resources * @param boolean $createConnections * @param integer $userRole */ protected function addAclResources($resources, $createConnections = true, $userRole = AclModelBase::DEFAULT_ROLE_MEMBER) { // create a test user $userData = ['nick_name' => Rand::getString(32), 'email' => Rand::getString(32), 'role' => $userRole]; // add member $query = $this->aclModelBase->insert()->into('user_list')->values($userData); $statement = $this->aclModelBase->prepareStatementForSqlObject($query); $statement->execute(); $this->userId = $this->aclModelBase->getAdapter()->getDriver()->getLastGeneratedValue(); // create new resources foreach ($resources as $resource) { // add new test resource $query = $this->aclModelBase->insert()->into('acl_resource')->values(['resource' => $resource, 'module' => 1, 'description' => '']); $statement = $this->aclModelBase->prepareStatementForSqlObject($query); $statement->execute(); $resourceId = $this->aclModelBase->getAdapter()->getDriver()->getLastGeneratedValue(); $this->aclResourcesIds[] = $resourceId; if ($createConnections) { $query = $this->aclModelBase->insert()->into('acl_resource_connection')->values(['role' => $userRole, 'resource' => $resourceId]); $statement = $this->aclModelBase->prepareStatementForSqlObject($query); $statement->execute(); $this->aclResourcesConnections[] = $this->aclModelBase->getAdapter()->getDriver()->getLastGeneratedValue(); } } }
/** * @return array */ public function provider() { $dateTime = new \DateTime(); $dateStart = $dateTime->sub(new \DateInterval('P1Y')); $dateEnd = $dateTime->add(new \DateInterval('P4Y')); $dateTime = new \DateTime(); $dateStartActual = $dateTime->sub(new \DateInterval('P6M')); $dateEndActual = $dateTime->add(new \DateInterval('P3Y')); $contactTest = new ContactTest(); $callTest = new CallTest(); $project = new Project(); $project->setCall($callTest->provider()[0][0]); $project->setDateStart($dateStart); $project->setDateEnd($dateEnd); $project->setDateStartActual($dateStartActual); $project->setDateEndActual($dateEndActual); $project->setNumber(Rand::getString(4)); $project->setContact($contactTest->provider()[0][0]); $project->setSummary('This is the summary'); $project->setDescription('This is the description'); $versionType = new Type(); $versionType->setType('Type'); $versionType->setId(1); return [[$project, $versionType]]; }
/** * */ public function createAction() { $isPublic = (bool) ($this->params('public') ?: $this->showPrompt('public')); $description = $this->params('description') ?: $this->showPrompt('description'); $grantTypes = $this->params('grant-types') ?: $this->showPrompt('grant-types'); $redirectUri = $this->params('redirect-uri') ?: $this->showPrompt('redirect-uri'); $secret = null; $encryptedSecret = null; if (!$isPublic) { $secret = Rand::getString(32); $encryptedSecret = $this->password->create($secret); } if ($grantTypes) { $grantTypes = explode(',', $grantTypes); array_walk($grantTypes, function (&$grant) { $grant = trim($grant); }); } $client = new Client(null, $encryptedSecret, null, $grantTypes, $redirectUri, $description); $this->clientMapper->save($client); $this->getConsole()->writeLine(); $this->getConsole()->writeLine('* Client created *', Color::GREEN); if (!$isPublic) { $this->getConsole()->writeLine('The client secret was auto-generated and encrypted. Please store it safely.'); $this->getConsole()->writeLine("Don't ever disclose the client secret publicly", Color::YELLOW); $this->getConsole()->writeLine(); } $this->getConsole()->writeLine("UUID: \t\t" . $client->getUuid()); if (!$isPublic) { $this->getConsole()->writeLine("Secret: \t" . $secret); } $this->getConsole()->writeLine("Grant types: \t" . implode(', ', $client->getGrantTypes())); $this->getConsole()->writeLine("Description: \t" . $client->getDescription()); $this->getConsole()->writeLine("Redirect URI: \t" . $client->getRedirectUri()); }
public function passwordAction() { $request = $this->getRequest(); // Make sure that we are running in a console and the user has not // tricked our // application into running this action from a public web server. if (!$request instanceof ConsoleRequest) { throw new \RuntimeException('You can only use this action from a console!'); } // Get user email from console and check if the user used --verbose or // -v flag $userEmail = $request->getParam('userEmail'); $verbose = $request->getParam('verbose'); // reset new password $newPassword = Rand::getString(16); $console = Console::getInstance(); if (Confirm::prompt('Is this the correct answer? [y/n]', 'y', 'n')) { $console->write("You chose YES\n"); } else { $console->write("You chose NO\n"); } if (!$verbose) { return "Done! {$userEmail} has received an email with his new password.\n"; } else { return "Done! New password for user {$userEmail} is '{$newPassword}'. It has also been emailed to him. \n"; } }
/** * Test role synchronisation */ public function testRoleSynchronisation() { // create a first test ACL role $query = $this->model->insert()->into('acl_role')->values(['name' => 'test role 1']); $statement = $this->model->prepareStatementForSqlObject($query); $statement->execute(); $this->aclRolesIds[] = $this->model->getAdapter()->getDriver()->getLastGeneratedValue(); // create a test user $query = $this->model->insert()->into('user_list')->values(['nick_name' => Rand::getString(32), 'email' => Rand::getString(32), 'role' => $this->aclRolesIds[0]]); $statement = $this->model->prepareStatementForSqlObject($query); $statement->execute(); $this->usersIds[] = $this->model->getAdapter()->getDriver()->getLastGeneratedValue(); // delete the created ACL role $query = $this->model->delete()->from('acl_role')->where(['id' => $this->aclRolesIds[0]]); $statement = $this->model->prepareStatementForSqlObject($query); $statement->execute(); // fire the delete ACL role event AclEvent::fireDeleteAclRoleEvent($this->aclRolesIds[0]); // check the created test user's role $select = $this->model->select(); $select->from('user_list')->columns(['role'])->where(['user_id' => $this->usersIds[0]]); $statement = $this->model->prepareStatementForSqlObject($select); $resultSet = new ResultSet(); $result = $resultSet->initialize($statement->execute()); // user must be a default member $this->assertEquals($result->current()['role'], AclBaseModel::DEFAULT_ROLE_MEMBER); }
/** * Bcrypt * * @param string $password * @throws Exception\RuntimeException * @return string */ public function create($password) { if (empty($this->salt)) { $salt = Rand::getBytes(self::MIN_SALT_SIZE); } else { $salt = $this->salt; } $salt64 = substr(str_replace('+', '.', base64_encode($salt)), 0, 22); /** * Check for security flaw in the bcrypt implementation used by crypt() * @see http://php.net/security/crypt_blowfish.php */ if (PHP_VERSION_ID >= 50307 && !$this->backwardCompatibility) { $prefix = '$2y$'; } else { $prefix = '$2a$'; // check if the password contains 8-bit character if (preg_match('/[\\x80-\\xFF]/', $password)) { throw new Exception\RuntimeException('The bcrypt implementation used by PHP can contain a security flaw ' . 'using password with 8-bit character. ' . 'We suggest to upgrade to PHP 5.3.7+ or use passwords with only 7-bit characters'); } } $hash = crypt($password, $prefix . $this->cost . '$' . $salt64); if (strlen($hash) < 13) { throw new Exception\RuntimeException('Error during the bcrypt generation'); } return $hash; }
public function export() { $path = __DIR__ . '/../../../../../../public/xls/'; if (!is_dir($path)) { throw new \Exception("Please make sure that 'public/xls' directory exists"); } $fileName = str_replace("/", ".", base64_encode(Rand::getBytes(6, true)) . '_' . date("Y-m-d-H:i:s") . '.xls'); $file = fopen($path . $fileName, "w"); $count = 0; $html = null; $html .= "<table>"; $html .= "<tr>"; foreach ($this->headers as $headers) { $html .= "<th>{$headers}</th>"; } $html .= "</tr>"; foreach ($this->resultFormatedData as $data) { foreach ($data as $colunas) { $count++; if ($count == 0) { $html .= "<tr>"; } $html .= "<td>{$colunas}</td>"; if ($count == count($this->headers)) { $html .= "</tr>"; $count = 0; } } } fputs($file, utf8_decode($html)); fclose($file); return '/xls/' . $fileName; }
public function runAction() { $em = $this->getEntityManager(); $console = $this->getServiceLocator()->get('console'); $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em); $console->writeLine('建立資料表中, 請稍待!!', ColorInterface::GREEN); $classes = $em->getMetadataFactory()->getAllMetadata(); if ($this->params()->fromRoute('re-create-database')) { $schemaTool->dropSchema($classes); } $schemaTool->createSchema($classes); // 安裝預設管理人員及選單 $username = '******'; $password = \Zend\Math\Rand::getString(8, null, true); $user = new \Base\Entity\User(); $user->setUsername($username); $user->setPassword(\Zend\Ldap\Attribute::createPassword($password)); $user->setDisplayName('管理者'); $user->setRole('admin'); $em->persist($user); $em->flush(); $menu = new \Base\Entity\Menu(); $menu->setName('首頁'); $menu->setUser($user); $params = ['max_records' => 10, 'order_kind' => 'desc', 'term' => '']; $menu->setParams(serialize($params)); $em->persist($menu); $em->flush(); $console->writeLine('建立完成!!', ColorInterface::GREEN); $console->writeLine('預設帳號 ' . $username . ', 密碼 ' . $password, ColorInterface::GREEN); }
/** * @param array $options */ public function __construct(array $options = []) { (new Hydrator\ClassMethods())->hydrate($options, $this); $this->updatedAt = new \DateTime('now'); $this->createdAt = new \DateTime('now'); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); }
/** * @return array */ public function provider() { $gender = new Gender(); $gender->setName(Rand::getString(4)); $gender->setAttention('attention:' . Rand::getString(4)); $gender->setSalutation('This is the salutation'); return [[$gender]]; }
/** * @return array */ public function provider() { $title = new Title(); $title->setName(Rand::getString(4)); $title->setAttention('attention:' . Rand::getString(4)); $title->setSalutation('This is the salutation'); return [[$title]]; }
/** * @param int $len * @return string * @throws \InvalidArgumentException */ public static function generate($len = 32) { if ($len > 255) { throw new \InvalidArgumentException(sprintf("assoc handle len must be lower or equal to 255(%d)", $len)); } $new_assoc_handle = Rand::getString($len, self::PrintableNonWhitespaceCharacters, true); return $new_assoc_handle; }
/** * @return array */ public function provider() { $contentType = new ContentType(); $contentType->setContentType('test/' . Rand::getString(12)); $contentType->setDescription('This is the description ' . Rand::getString(12)); $contentType->setExtension(Rand::getString(4)); return [[$contentType]]; }
public function __construct(array $options = array()) { (new Hydrator\ClassMethods())->hydrate($options, $this); $this->created = new \DateTime("now"); $this->modified = new \DateTime("now"); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activekey = md5($this->email . $this->salt); }
/** * Get the base name of the persistently stored file. * * @return string */ public function getStorageBaseName() { if (isset($this->storageBaseName)) { return $this->storageBaseName; } $this->storageBaseName = bin2hex(Rand::getBytes(20)); return $this->storageBaseName; }
/** * Get guest id * * @return string */ public function getGuestId() { $container = new SessionContainer('comment'); // generate custom guest id if (empty($container->guestId)) { $container->guestId = Rand::getString(self::COMMENT_GUEST_ID_LENGTH, 'abcdefghijklmnopqrstuvwxyz', true); } return $container->guestId; }
public function create($password) { if (empty($this->salt)) { $salt = $this->salt = Rand::getBytes(self::MIN_SALT_SIZE); } else { $salt = $this->salt; } return parent::create($password); }
public function formBigInteger() { $bigInt = BigInteger::factory('bcmath'); $x = Rand::getString(100, '0123456789'); $y = Rand::getString(100, '0123456789'); $sum = $bigInt->add($x, $y); $len = strlen($sum); $this->data->bigint = "{$x} + {$y} = {$sum}"; $this->render(); }
/** * PostIdを生成する * @param $cmd saltとして使用する文字列(通常はプラグイン名) * @return string */ public static function generate($cmd = '') { global $session; $idstring = md5($cmd . Rand::getFloat()); // PostIDの値の中身は、ホストを入力 $session->offsetSet(self::POSTID_SESSION_PREFIX . $idstring, REMOTE_ADDR); // 有効期限を設定 $session->setExpirationSeconds(self::POSTID_SESSION_EXPIRE, self::POSTID_SESSION_PREFIX . $idstring); return $idstring; }
public function saveOrder(Order $order) { $order->id = Rand::getInteger(100000, 999999); $this->getEventManager()->trigger('preOrder', __CLASS__); $filePath = realpath(BIG5_ROOT . '/data/order') . '/'; $fileName = $filePath . $order->id . '.txt'; file_put_contents($fileName, serialize($order)); echo "Save order " . $order->id . "<br />"; $this->getEventManager()->trigger('postOrder', __CLASS__); }
/** * Bcrypt * * @param string $password * @throws Exception\RuntimeException * @return string */ public function create($password) { $options = ['cost' => (int) $this->cost]; if (PHP_VERSION_ID < 70000) { // salt is deprecated from PHP 7.0 $salt = $this->salt ?: Rand::getBytes(self::MIN_SALT_SIZE); $options['salt'] = $salt; } return password_hash($password, PASSWORD_BCRYPT, $options); }
/** * Create an unique token for a Squad * * @param \Frontend\Squads\Entity\Squad $squad * @return bool */ public function createUniqueToken(\Frontend\Squads\Entity\Squad &$squad) { $chars = array_merge(range(0, 9), range('A', 'Z'), range('a', 'z')); $token = Rand::getString(32, implode('', $chars), true); if ($this->checkUniqueTokenExists($token)) { $this->createUniqueToken($squad); return true; } $squad->setPrivateID($token); return true; }
function __construct(array $options = array()) { // Preencher automático os valores no objeto // $hydrator = new Hydrator\ClassMethods; // $hydrator->hydrate($options, $this); (new Hydrator\ClassMethods())->hydrate($options, $this); $this->createdAt = new \DateTime('now', new \DateTimeZone('America/Sao_Paulo')); $this->updatedAt = new \DateTime('now', new \DateTimeZone('America/Sao_Paulo')); $this->salt = base64_encode(Rand::getBytes(8, true)); $this->activationKey = md5($this->email . $this->salt); }
public function onBootstrap($e) { $app = $e->getApplication(); $events = $app->getEventManager(); $shared = $events->getSharedManager(); // Create a sha1-like identifier. $shared->attach('ZF\\Apigility\\Example\\V1\\Rest\\Status\\StatusResource', 'create', function ($e) { $data = $e->getParam('data'); $data['id'] = Rand::getString(32, 'abcdef0123456789'); }, 100); }
public function createApplicationFromArray(AccountInterface $account, array $data) { $clientSecret = Rand::getString(64, 'abcdefghijklmnopqrstuvwxyz0123456789'); $oauthApplication = new OAuthApplication($data['name'], $data['homepage']); $oauthApplication->setAccount($account); $oauthApplication->setClientSecret($this->crypter->create($clientSecret)); $oauthApplication->setDescription($data['description']); $oauthApplication->setRedirectUri($data['redirectUri']); $this->persistApplication($oauthApplication); return $clientSecret; }
/** * Generate random salt for an algo-type * * @param int $algo * @return string * @throws \InvalidArgumentException */ public static function salt($algo = null) { if (empty($algo)) { $algo = self::ALGO_DEFAULT; } switch ($algo) { case self::ALGO_BCRYPT: return Rand::getString(22, './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', true); default: throw new \InvalidArgumentException(sprintf('%s: algorithm #%d not supported', __METHOD__, $algo)); } }
private function populatePerson(PersonEntity $person) { $genders = [0, 1, 2, 9]; $gender = $genders[Rand::getInteger(0, count($genders) - 1)]; $person->setGender($gender); $person->setJobTitle('Software Engineer'); $person->setDepartment('Department'); if ($gender === 2) { $person->setMaidenName('Maiden name'); } $person->setNickname('Nickname'); }
public function __construct(array $options = array()) { /* $hydrator = new Hydrator\ClassMethods(); $hydrator->hydrate($options, $this); */ (new Hydrator\ClassMethods())->hydrate($options, $this); $this->createdAt = new \DateTime("now"); $this->updateAt = new \DateTime("now"); $this->salt = base64_encode(Rand::getBytes(8, TRUE)); $this->activationKey = md5($this->email . $this->salt); }