/**
  *
  */
 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());
 }
예제 #2
0
 /**
  * @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]];
 }
예제 #3
0
 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;
 }
예제 #4
0
 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";
     }
 }
예제 #5
0
 /**
  * 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);
 }
예제 #6
0
 /**
  * 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);
 }
예제 #7
0
파일: Contact.php 프로젝트: zource/zource
 private function populateGeneral(AbstractContact $contact)
 {
     $contact->setNotes('This is a note for this contact.');
     if (Rand::getFloat(true) < 0.8) {
         $contact->setDisplayName(Rand::getString(32));
     }
 }
예제 #8
0
 /**
  * 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();
         }
     }
 }
예제 #9
0
 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);
 }
예제 #10
0
 /**
  * @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]];
 }
예제 #11
0
 /**
  * @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;
 }
예제 #12
0
 /**
  * @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]];
 }
예제 #13
0
 /**
  * @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]];
 }
 /**
  * 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;
 }
예제 #15
0
 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();
 }
예제 #16
0
 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;
 }
예제 #17
0
 /**
  * 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;
 }
예제 #18
0
 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);
 }
예제 #19
0
파일: Password.php 프로젝트: gridguyz/zork
 /**
  * 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));
     }
 }
예제 #20
0
 public static function create(AccessToken $access_token, $lifetime = 0)
 {
     $instance = new self();
     $instance->value = Rand::getString($instance->len, OAuth2Protocol::VsChar, true);
     $instance->scope = $access_token->getScope();
     $instance->user_id = $access_token->getUserId();
     $instance->client_id = $access_token->getClientId();
     $instance->audience = $access_token->getAudience();
     $instance->from_ip = IPHelper::getUserIp();
     $instance->lifetime = intval($lifetime);
     $instance->is_hashed = false;
     return $instance;
 }
예제 #21
0
 public function provider()
 {
     $genderTest = new GenderTest();
     $titleTest = new TitleTest();
     $contact = new Contact();
     $contact->setFirstName('Jan');
     $contact->setMiddleName('van der');
     $contact->setLastName('Vliet');
     $contact->setEmail('info+' . Rand::getString(4) . '@example.com');
     $contact->setGender($genderTest->provider()[0][0]);
     $contact->setTitle($titleTest->provider()[0][0]);
     return [[$contact]];
 }
예제 #22
0
 /**
  * Test a correct slug generation
  */
 public function testCorrectSlugGeneration()
 {
     // generate a first test user
     $firstUserSlug = SlugUtility::slugify(Rand::getString(20));
     $firstUserData = ['nick_name' => Rand::getString(32), 'email' => Rand::getString(32), 'role' => AclModel::DEFAULT_ROLE_MEMBER, 'slug' => $firstUserSlug, 'api_key' => Rand::getString(32)];
     $query = $this->model->insert()->into('user_list')->values($firstUserData);
     $statement = $this->model->prepareStatementForSqlObject($query);
     $statement->execute();
     $userId = $this->userIds[] = $this->model->getAdapter()->getDriver()->getLastGeneratedValue();
     // generate slug for the second user
     $secondUserSlug = $firstUserSlug;
     $secondUserId = $userId + 1;
     $this->assertEquals($this->model->generateSlug($secondUserId, $secondUserSlug, 'user_list', 'user_id'), $secondUserId . '-' . $firstUserSlug);
 }
예제 #23
0
 public function testApcExtensionWorking()
 {
     if (extension_loaded('apc')) {
         echo 'APC EXTENSION: apc' . PHP_EOL;
     }
     if (extension_loaded('apcu')) {
         echo 'APC EXTENSION: apcu' . PHP_EOL;
     }
     $this->assertTrue(extension_loaded('apc') || extension_loaded('apcu'));
     $rand = Rand::getString(10, 'asdf');
     $addMethod = extension_loaded('apcu') ? 'apcu_add' : 'apc_add';
     $this->assertTrue($addMethod($rand, true, 100));
     $this->assertFalse($addMethod($rand, true, 100));
 }
예제 #24
0
 public function generate(UserInterface $user, $daysToLive = 1, $storeUser = true)
 {
     $tokenHash = Rand::getString(64, $this->charList);
     $dateStr = sprintf('+ %d day', $daysToLive);
     $expirationDate = new \Datetime($dateStr);
     /* @todo We should consider using the Prototype Design Pattern here. */
     $token = new Token();
     $token->setHash($tokenHash)->setExpirationDate($expirationDate);
     $user->getTokens()->add($token);
     if ($storeUser) {
         $this->repositoryService->store($user);
     }
     return $tokenHash;
 }
예제 #25
0
 public static function createFromRefreshToken(RefreshToken $refresh_token, $scope = null, $lifetime = 3600)
 {
     $instance = new self();
     $instance->value = Rand::getString($instance->len, OAuth2Protocol::VsChar, true);
     $instance->scope = $scope;
     $instance->from_ip = $refresh_token->getFromIp();
     $instance->user_id = $refresh_token->getUserId();
     $instance->client_id = $refresh_token->getClientId();
     $instance->auth_code = null;
     $instance->refresh_token = $refresh_token;
     $instance->audience = $refresh_token->getAudience();
     $instance->lifetime = intval($lifetime);
     $instance->is_hashed = false;
     return $instance;
 }
예제 #26
0
 /**
  * @param $user_id
  * @param $client_id
  * @param $scope
  * @param string $audience
  * @param null $redirect_uri
  * @param string $access_type
  * @param string $approval_prompt
  * @param bool $has_previous_user_consent
  * @param int $lifetime
  * @return AuthorizationCode
  */
 public static function create($user_id, $client_id, $scope, $audience = '', $redirect_uri = null, $access_type = OAuth2Protocol::OAuth2Protocol_AccessType_Online, $approval_prompt = OAuth2Protocol::OAuth2Protocol_Approval_Prompt_Auto, $has_previous_user_consent = false, $lifetime = 600)
 {
     $instance = new self();
     $instance->value = Rand::getString($instance->len, OAuth2Protocol::VsChar, true);
     $instance->scope = $scope;
     $instance->user_id = $user_id;
     $instance->redirect_uri = $redirect_uri;
     $instance->client_id = $client_id;
     $instance->lifetime = intval($lifetime);
     $instance->audience = $audience;
     $instance->is_hashed = false;
     $instance->from_ip = IPHelper::getUserIp();
     $instance->access_type = $access_type;
     $instance->approval_prompt = $approval_prompt;
     $instance->has_previous_user_consent = $has_previous_user_consent;
     return $instance;
 }
예제 #27
0
 /**
  * Test delete user home directory
  */
 public function testDeleteUserHomeDirectory()
 {
     // test user data
     $data = ['nick_name' => Rand::getString(32), 'email' => Rand::getString(32), 'api_key' => Rand::getString(32), 'role' => AclModelBase::DEFAULT_ROLE_MEMBER, 'language' => null];
     // create a test user
     $query = $this->userModel->insert()->into('user_list')->values($data);
     $statement = $this->userModel->prepareStatementForSqlObject($query);
     $statement->execute();
     $testUserId = $this->userModel->getAdapter()->getDriver()->getLastGeneratedValue();
     // create a test user's home directory
     $homeUserDirectory = FileManagerBaseModel::getUserBaseFilesDir($testUserId) . '/' . FileManagerBaseModel::getHomeDirectoryName();
     FileSystemUtility::createDir($homeUserDirectory);
     // fire the delete user event
     UserEvent::fireUserDeleteEvent($testUserId, $data);
     // delete the created user
     $query = $this->userModel->delete()->from('user_list')->where(['user_id' => $testUserId]);
     $statement = $this->userModel->prepareStatementForSqlObject($query);
     $statement->execute();
     // home directory must be deleted
     $this->assertFalse(file_exists($homeUserDirectory));
 }
예제 #28
0
 public function resetpasswordAction()
 {
     $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') || $request->getParam('v');
     // reset new password
     $newPassword = Rand::getString(16);
     //  Fetch the user and change his password, then email him ...
     // [...]
     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";
     }
 }
예제 #29
0
 public function nuevoAction()
 {
     $this->dbAdapter = $this->getServiceLocator()->get('Zend\\Db\\Adapter');
     $email = $this->request->getPost('email');
     $password = $this->request->getPost('password');
     $repeatPassword = $this->request->getPost('repeatPassword');
     $usuarios = $this->dbAdapter->query("SELECT * FROM usuario where email='{$email}' limit 1", Adapter::QUERY_MODE_EXECUTE);
     foreach ($usuarios as $user) {
         $email_exist = $user['email'];
     }
     if (!@ereg("^[a-zA-Z0-9_\\.\\-]+@[a-zA-Z0-9\\-]+\\.[a-zA-Z0-9\\-\\.]", $email)) {
         $mensaje = 'Tu correo electrónico es inválido.';
         $status = 0;
     } elseif ($password != $repeatPassword || strlen($password) < 5) {
         $mensaje = 'Tu contraseña no coincide o es muy corta';
         $status = 0;
     } elseif (@$email_exist == $email) {
         $mensaje = 'La cuenta de correo ya existe';
         $status = 0;
     } else {
         $add = new Usuario($this->dbAdapter);
         $string = Rand::getString(32, 'abcdefghijklmnopqrstuvwxyz', true);
         $datos = array('email' => $email, 'contrasena' => $password, 'verificado' => 'no', 'cod' => $string);
         $add->addUser($datos);
         $usuario = $add->getUserEmail($email);
         $mail = new Mail\Message();
         $base = base64_encode($email);
         $mail->setBody('¡Gracias por registrarte!. Para gozar de todos los beneficios es necesario que valides tu cuenta de correo electrónico en el siguiente enlace <a href="' . $this->getRequest()->getBaseUrl() . '/usuario/validar/' . $usuario[0]['id_usuario'] . '/' . $usuario[0]['cod'] . '">Validar Cuenta</a><br><br><img src="' . $this->getRequest()->getBaseUrl() . '/img/empresasveracruz2.png">');
         $mail->setFrom('*****@*****.**', 'Directorio EmpresasVeracruz');
         $mail->addTo($email);
         $mail->setSubject('Bienvenido a EmpresasVeracruz');
         $transport = new Mail\Transport\Sendmail();
         $transport->send($mail);
         $mensaje = "Registrado, por favor revisa tu bandeja de entrada para validar tu cuenta.";
         $status = 200;
     }
     $vista = new ViewModel(array('mensaje' => $mensaje, 'status' => $status));
     $this->layout('layout/ajax');
     return $vista;
 }
예제 #30
0
 public function test1Action()
 {
     $entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
     $repository = $entityManager->getRepository($this->getMyEntity());
     $adapter = new DoctrineAdapter(new ORMPaginator($repository->createQueryBuilder('user')->where('user.parentid = 1')));
     $paginator = new Paginator($adapter);
     $paginator->setDefaultItemCountPerPage(15);
     $page = (int) $this->params()->fromRoute('id', 1);
     if ($page) {
         $paginator->setCurrentPageNumber($page);
     }
     $viewmodel = new ViewModel();
     //disable layout if request by Ajax
     $request = $this->getRequest();
     $viewmodel->setTerminal($request->isXmlHttpRequest());
     $is_xmlhttprequest = 1;
     if (!$request->isXmlHttpRequest()) {
         $is_xmlhttprequest = 0;
     }
     $viewmodel->setVariables(array('data' => $paginator, 'page' => $id, 'is_xmlhttprequest' => $is_xmlhttprequest, 'w_id' => Rand::getString(32, 'abcdefghijklmnopqrstuvwxyz', true)));
     return $viewmodel;
 }