public function hello() { $users = User::getAll(); foreach ($users as $user) { print_r($user->UserEmail); } }
public function testRebuildDatabaseWithNonSuperAdminUser() { $steven = UserTestHelper::createBasicUser('Steven'); Yii::app()->user->userModel = $steven; $item = NamedSecurableItem::getByName('AccountsModule'); $this->assertEquals(Permission::NONE, $item->getEffectivePermissions($steven)); $accounts = Account::getAll(); $users = User::getAll(); $this->assertEquals(0, count($accounts)); $this->assertEquals(2, count($users)); $adapter = new ModelAttributesAdapter(new Account()); $adapter->resolveDatabaseSchemaForModel('Account'); //Confirm the counts of data are still correct $accounts = Account::getAll(); $users = User::getAll(); $this->assertEquals(0, count($accounts)); $this->assertEquals(2, count($users)); //Explicitly deny read, write, and deny Yii::app()->user->userModel = User::getByUsername('super'); $item->addPermissions($steven, Permission::READ_WRITE_DELETE, Permission::DENY); $this->assertTrue($item->save()); //Make sure steven has explicit deny $item = NamedSecurableItem::getByName('AccountsModule'); $this->assertEquals(Permission::NONE, $item->getEffectivePermissions($steven)); Yii::app()->user->userModel = $steven; $adapter = new ModelAttributesAdapter(new Account()); $adapter->resolveDatabaseSchemaForModel('Account'); //Confirm the counts of data are still correct $accounts = Account::getAll(); $users = User::getAll(); $this->assertEquals(0, count($accounts)); $this->assertEquals(2, count($users)); }
/** * Any user who has access to the scheduler module is added to receive a * notification. */ protected function loadUsers() { foreach (User::getAll() as $user) { if ($user->getEffectiveRight('JobsManagerModule', JobsManagerModule::RIGHT_ACCESS_JOBSMANAGER) == Right::ALLOW) { $this->addUser($user); } } }
/** * Any user who has access to the workflows module is added to receive a * notification. */ protected function loadUsers() { foreach (User::getAll() as $user) { if ($user->getEffectiveRight('WorkflowsModule', WorkflowsModule::RIGHT_ACCESS_WORKFLOWS) == Right::ALLOW) { $this->addUser($user); } } }
function test_save() { //Arrange $name = "Bob"; $email = "*****@*****.**"; $test_user = new User($name, $email); $test_user->save(); //Act $result = User::getAll(); //Assert $this->assertEquals([$test_user], $result); }
function testUpdateUser() { $name = "John Doe"; $password = "******"; $email = "*****@*****.**"; $signed_in = 0; $test_user = new User($name, $password, $email, $signed_in); $test_user->save(); $name2 = "Jane Boe"; $password2 = "wordpass"; $email2 = "*****@*****.**"; $test_user->updateUser($name2, $password2, $email2); $result = User::getAll(); $this->assertEquals($test_user, $result[0]); }
/** * Get from the database a list of the ranges of online users * @return array */ public static function getRanges() { if (OnlineRange::$ranges_cache) { return OnlineRange::$ranges_cache; } $startTime = microtime(true); $rows = OnlineRange::fetchAllRows(); OnlineRange::$users_cache = User::getAll(); $result = OnlineRange::$ranges_cache = OnlineRange::buildRanges($rows); $endTime = microtime(true); Logger::log(" OnlineRange::getRanges() -> ", $endTime - $startTime); $startTime = microtime(true); OnlineRange::saveRanges($result); $endTime = microtime(true); Logger::log(" OnlineRange::saveRanges() -> ", $endTime - $startTime); return $result; }
public function makeAll(&$demoDataHelper) { assert('$demoDataHelper instanceof DemoDataHelper'); assert('$demoDataHelper->isSetRange("User")'); foreach (User::getAll() as $user) { $gameScore = GameScore::resolveToGetByTypeAndPerson('LoginUser', $user); $gameScore->value = 10; $saved = $gameScore->save(); assert('$saved'); $gamePoint = GamePoint::resolveToGetByTypeAndPerson(GamePoint::TYPE_USER_ADOPTION, $user); $gamePoint->value = mt_rand(100, 300); $saved = $gamePoint->save(); assert('$saved'); $gameScore = GameScore::resolveToGetByTypeAndPerson('CreateAccount', $user); $gameScore->value = 10; $saved = $gameScore->save(); assert('$saved'); $gamePoint = GamePoint::resolveToGetByTypeAndPerson(GamePoint::TYPE_NEW_BUSINESS, $user); $gamePoint->value = 100; $saved = $gamePoint->save(); assert('$saved'); //Badges $gameBadge = new GameBadge(); $gameBadge->type = 'LoginUser'; $gameBadge->grade = 2; $gameBadge->person = $user; $saved = $gameBadge->save(); assert('$saved'); $gameBadge = new GameBadge(); $gameBadge->type = 'CreateAccount'; $gameBadge->grade = 3; $gameBadge->person = $user; $saved = $gameBadge->save(); assert('$saved'); //Levels $gameLevel = GameLevel::resolveByTypeAndPerson(GameLevel::TYPE_GENERAL, $user); $gameLevel->value = 1; $saved = $gameLevel->save(); assert('$saved'); $gameLevel = GameLevel::resolveByTypeAndPerson(GameLevel::TYPE_NEW_BUSINESS, $user); $gameLevel->value = 1; $saved = $gameLevel->save(); assert('$saved'); } }
function listUser() { global $lang; $page_lang = scandir('inc/lang/' . $_SESSION['language']); foreach ($page_lang as $file) { if ($file != '.' && $file != '..') { $parts = explode(".", $file); $page = $parts[0]; if ($page == 'user') { $page_file = $file; } } } include_once 'inc/lang/' . $_SESSION['language'] . '/' . $page_file; if ($_SESSION['access']->users > 0) { $results = array(); $gResults = array(); $data = User::getAll(); $gData = Group::getAll(); $results['users'] = $data['results']; $results['totalRows'] = $data['totalRows']; $results['pageTitle'] = "Admin User Management"; $gResults['groups'] = $gData['results']; $gResults['totalRows'] = $gData['totalRows']; if (isset($_GET['success'])) { if ($_GET['success'] == "userCreated") { $results['successMessage'] = "Your new admin user profile has been created successully."; } if ($_GET['success'] == "groupCreated") { $results['successMessage'] = "Your new admin group has been created successully."; } if ($_GET['success'] == "changesSaved") { $results['successMessage'] = "Your user profile changes have been saved successully."; } if ($_GET['success'] == "groupChangesSaved") { $results['successMessage'] = "Your group changes have been saved successully."; } } require "inc/layout/listUser.php"; } else { require "inc/layout/noAccess.php"; } }
/** * Walkthrough test for synchronous download */ public function testDownloadDefaultControllerActions() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $nobody = User::getByUsername('nobody'); $users = User::getAll(); if (count($users)) { foreach ($users as $user) { if ($user->id !== $super->id && $user->id !== $nobody->id) { $user->delete(); } } } $users = array(); for ($i = 0; $i <= ExportModule::$asynchronousThreshold - 3; $i++) { $users[] = UserTestHelper::createBasicUser('aUser' . $i); } // Check if access is denied if user doesn't have access privileges at all to export actions Yii::app()->user->userModel = User::getByUsername('nobody'); $nobody = $this->logoutCurrentUserLoginNewUserAndGetByUsername('nobody'); $this->runControllerShouldResultInAccessFailureAndGetContent('users/default/list'); // Check if user have access to module action, but not to export action // Now test peon with elevated rights to accounts $nobody->setRight('UsersModule', UsersModule::RIGHT_ACCESS_USERS); $nobody->setRight('ExportModule', ExportModule::RIGHT_ACCESS_EXPORT); $this->assertTrue($nobody->save()); // Check if access is denied if user doesn't have access privileges at all to export actions $nobody = $this->logoutCurrentUserLoginNewUserAndGetByUsername('nobody'); Yii::app()->user->userModel = User::getByUsername('nobody'); $this->runControllerWithNoExceptionsAndGetContent('users/default/list'); $this->setGetArray(array('User_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => '')); $response = $this->runControllerWithRedirectExceptionAndGetUrl('users/default/export'); $this->assertTrue(strstr($response, 'users/default/index') !== false); $this->setGetArray(array('UsersSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => ''), 'User_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => '')); $response = $this->runControllerWithExitExceptionAndGetContent('users/default/export'); $this->assertEquals('Testing download.', $response); $this->setGetArray(array('UsersSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => ''), 'User_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => "{$users[0]->id}, {$users[1]->id}")); $response = $this->runControllerWithExitExceptionAndGetContent('users/default/export'); $this->assertEquals('Testing download.', $response); // No mathces $this->setGetArray(array('UsersSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => 'missingOne'), 'User_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => '')); $response = $this->runControllerWithRedirectExceptionAndGetUrl('users/default/export'); $this->assertTrue(strstr($response, 'users/default/index') !== false); }
public function testSimpleUserImportWhereAllRowsSucceed() { Yii::app()->user->userModel = User::getByUsername('super'); $users = User::getAll(); $this->assertEquals(1, count($users)); $import = new Import(); $serializedData['importRulesType'] = 'User'; $serializedData['firstRowIsHeaderRow'] = true; $import->serializedData = serialize($serializedData); $this->assertTrue($import->save()); ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName(), Yii::getPathOfAlias('application.modules.users.tests.unit.files')); $this->assertEquals(11, ImportDatabaseUtil::getCount($import->getTempTableName())); // includes header rows. $mappingData = array('column_0' => array('attributeIndexOrDerivedType' => 'username', 'type' => 'importColumn', 'mappingRulesData' => array()), 'column_1' => array('attributeIndexOrDerivedType' => 'Password', 'type' => 'importColumn', 'mappingRulesData' => array('PasswordDefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => null))), 'column_2' => array('attributeIndexOrDerivedType' => 'UserStatus', 'type' => 'importColumn', 'mappingRulesData' => array('UserStatusDefaultValueMappingRuleForm' => array('defaultValue' => UserStatusUtil::ACTIVE))), 'column_3' => ImportMappingUtil::makeStringColumnMappingData('firstName'), 'column_4' => ImportMappingUtil::makeStringColumnMappingData('lastName')); $importRules = ImportRulesUtil::makeImportRulesByType('Users'); $page = 0; $config = array('pagination' => array('pageSize' => 50)); //This way all rows are processed. $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config); $dataProvider->getPagination()->setCurrentPage($page); $importResultsUtil = new ImportResultsUtil($import); $messageLogger = new ImportMessageLogger(); ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, new ExplicitReadWriteModelPermissions(), $messageLogger); $importResultsUtil->processStatusAndMessagesForEachRow(); //Confirm that 10 models where created. $users = User::getAll(); $this->assertEquals(11, count($users)); $activeUser = User::getByUsername('myusername7'); $userStatus = UserStatusUtil::makeByUser($activeUser); $this->assertTrue($userStatus->isActive()); $inactiveUser = User::getByUsername('myusername8'); $userStatus = UserStatusUtil::makeByUser($inactiveUser); $this->assertFalse($userStatus->isActive()); //Confirm 10 rows were processed as 'created'. $this->assertEquals(10, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::CREATED)); //Confirm that 0 rows were processed as 'updated'. $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::UPDATED)); //Confirm 2 rows were processed as 'errors'. $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR)); $beansWithErrors = ImportDatabaseUtil::getSubset($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR); $this->assertEquals(0, count($beansWithErrors)); }
//path to userhome for viewing current users and adding new $app->get("/userhome", function () use($app) { return $app['twig']->render('userhome.html.twig', array('users' => User::getAll())); }); //path to specific users account info and activity info $app->get("/updateuser/{id}", function () use($app) { return $app['twig']->render('updateuser.html.twig', array('user' => $user)); }); //Update user info $app->post("/userhome", function () use($app) { $user_name = $_POST['user_name']; $user_phone = $_POST['user_phone']; $user_email = $_POST['user_email']; $user = new User($user_name, $user_buy_quantity = null, $user_phone, $user_email, $activity_id = null, $id = null); $user->save(); return $app['twig']->render('userhome.html.twig', array('users' => User::getAll())); }); //Path to update and activity $app->get("/updateactivity/{id}", function () use($app) { return $app['twig']->render('updateactivity.html.twig', array('activity' => $activity)); }); //Update activity info $app->post("/updateactivity/{id}", function () use($app) { $activity_name = $_POST['activity_name']; $activity_date = $_POST['activity_date']; $activity_location = $_POST['activity_location']; $activity_description = $_POST['activity_description']; $activity_price = $_POST['activity_price']; $activity_quantity = $_POST['activity_quantity']; $activity = new Activity($activity_name, $activity_date, $activity_location, $activity_description, $activity_price, $activity_quantity, $business_id = null, $activity_category_id = null, $id = null); $activity->save();
public function getUsers() { $userController = new User($this->user, $this->token); $users = $userController->getAll(); return $users; }
public static function setUpBeforeClass() { parent::setUpBeforeClass(); // We need to unfreeze here as we are working with custom field values self::$freeze = false; if (RedBeanDatabase::isFrozen()) { RedBeanDatabase::unfreeze(); self::$freeze = true; } SecurityTestHelper::createSuperAdmin(); SecurityTestHelper::createUsers(); self::$super = User::getByUsername('super'); Yii::app()->user->userModel = self::$super; $currencies = Currency::getAll(); $currencyValue1 = new CurrencyValue(); $currencyValue1->value = 100; $currencyValue1->currency = $currencies[0]; $multiDropDownCustomFieldData1 = new CustomFieldData(); $multiDropDownCustomFieldData1->name = 'multiDropDown1'; $multiDropDownCustomFieldData1->serializedData = serialize(array('Ten', 11, 'XII')); $saved = $multiDropDownCustomFieldData1->save(); assert('$saved'); // Not Coding Standard $multiDropDownCustomFieldValue1 = new CustomFieldValue(); $multiDropDownCustomFieldValue1->value = 'Ten'; $multiDropDownCustomFieldValue2 = new CustomFieldValue(); $multiDropDownCustomFieldValue2->value = 11; $multiDropDownCustomFieldValue3 = new CustomFieldValue(); $multiDropDownCustomFieldValue3->value = 'XII'; $tagCustomFieldData1 = new CustomFieldData(); $tagCustomFieldData1->name = 'tagCloud1'; $tagCustomFieldData1->serializedData = serialize(array('Apache', 'PHP')); $saved = $tagCustomFieldData1->save(); assert('$saved'); // Not Coding Standard $tagCustomFieldValue1 = new CustomFieldValue(); $tagCustomFieldValue1->value = 'PHP'; $tagCustomFieldValue2 = new CustomFieldValue(); $tagCustomFieldValue2->value = 'Apache'; $primaryEmail1 = new Email(); $primaryEmail1->emailAddress = "*****@*****.**"; $primaryEmail1->isInvalid = true; $primaryEmail1->optOut = false; $secondaryEmail1 = new Email(); $secondaryEmail1->emailAddress = "*****@*****.**"; $secondaryEmail1->isInvalid = false; $secondaryEmail1->optOut = true; $address1 = new Address(); $address1->street1 = "SomeStreet1"; $address1->street2 = "SomeStreet2"; $address1->city = "SomeCity"; $address1->state = "SomeState"; $address1->postalCode = 1111; $address1->country = "SomeCountry"; $likeContactState1 = new ContactState(); $likeContactState1->name = 'Customer'; $likeContactState1->order = 0; $users = User::getAll(); $user1 = new User(); $user1->lastName = 'Kevin'; $user1->hash = 'rieWoy3aijohP6chaigaokohs1oovohf'; $user1->language = 'es'; $user1->timeZone = 'America/Chicago'; $user1->username = '******'; $user1->currency = $currencies[0]; $user1->manager = $users[0]; //Custom attribute $attributeForm = new TextAttributeForm(); $attributeForm->attributeName = 'custom'; $attributeForm->attributeLabels = array('en' => 'test label en'); $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData(); $adapter = new $modelAttributesAdapterClassName(new EmailTemplateModelTestItem()); $adapter->setAttributeMetadataFromForm($attributeForm); $model = new EmailTemplateModelTestItem(); $model->string = 'abc'; $model->firstName = 'James'; $model->lastName = 'Jackson'; $model->phone = 1122334455; $model->boolean = true; $model->date = '2008-12-31'; $model->dateTime = '2008-12-31 07:48:04'; $model->textArea = 'Multiple Lines\\nOf Text'; $model->url = 'http://www.zurmo.com/'; $model->integer = 999; $model->float = 999.999; $model->currencyValue = $currencyValue1; $model->dropDown->value = "DropdownSelectedValue"; $model->radioDropDown->value = "RadioDropdownSelectedValue"; $model->primaryEmail = $primaryEmail1; $model->secondaryEmail = $secondaryEmail1; $model->primaryAddress = $address1; $model->likeContactState = $likeContactState1; $model->user = $user1; $model->multiDropDown->data = $multiDropDownCustomFieldData1; $model->tagCloud->data = $tagCustomFieldData1; $model->multiDropDown->values->add($multiDropDownCustomFieldValue1); $model->multiDropDown->values->add($multiDropDownCustomFieldValue2); $model->multiDropDown->values->add($multiDropDownCustomFieldValue3); $model->tagCloud->values->add($tagCustomFieldValue1); $model->tagCloud->values->add($tagCustomFieldValue2); $model->customCstm = 'text custom'; $saved = $model->save(); assert('$saved'); // Not Coding Standard self::$emailTemplate = $model; // Update all values but do not save the model. $multiDropDownCustomFieldData2 = new CustomFieldData(); $multiDropDownCustomFieldData2->name = 'multiDropDown2'; $multiDropDownCustomFieldData2->serializedData = serialize(array('Thirteen', 14, 'XV')); $saved = $multiDropDownCustomFieldData2->save(); assert('$saved'); // Not Coding Standard $multiDropDownCustomFieldValue4 = new CustomFieldValue(); $multiDropDownCustomFieldValue4->value = 'Thirteen'; $multiDropDownCustomFieldValue5 = new CustomFieldValue(); $multiDropDownCustomFieldValue5->value = 14; $multiDropDownCustomFieldValue6 = new CustomFieldValue(); $multiDropDownCustomFieldValue6->value = 'XV'; $tagCustomFieldData2 = new CustomFieldData(); $tagCustomFieldData2->name = 'tagCloud2'; $tagCustomFieldData2->serializedData = serialize(array('Nginx', 'Python')); $saved = $tagCustomFieldData2->save(); assert('$saved'); // Not Coding Standard $tagCustomFieldValue3 = new CustomFieldValue(); $tagCustomFieldValue3->value = 'Python'; $tagCustomFieldValue4 = new CustomFieldValue(); $tagCustomFieldValue4->value = 'Nginx'; self::$emailTemplate->string = 'def'; self::$emailTemplate->firstName = 'Jane'; self::$emailTemplate->lastName = 'Bond'; self::$emailTemplate->phone = 66778899; self::$emailTemplate->boolean = false; self::$emailTemplate->date = '2009-12-31'; self::$emailTemplate->dateTime = '2009-12-31 07:48:04'; self::$emailTemplate->textArea = 'Multiple Lines\\nOf\\nText'; self::$emailTemplate->url = 'http://www.zurmo.org/'; self::$emailTemplate->integer = 888; self::$emailTemplate->float = 888.888; self::$emailTemplate->currencyValue->value = 99; self::$emailTemplate->dropDown->value = "DropdownSelectedVal"; self::$emailTemplate->radioDropDown->value = "RadioDropdownSelectedVal"; self::$emailTemplate->primaryEmail->emailAddress = "*****@*****.**"; self::$emailTemplate->primaryEmail->isInvalid = false; self::$emailTemplate->primaryEmail->optOut = true; self::$emailTemplate->secondaryEmail->emailAddress = "*****@*****.**"; self::$emailTemplate->secondaryEmail->isInvalid = true; self::$emailTemplate->secondaryEmail->optOut = false; self::$emailTemplate->primaryAddress->street1 = "SomeOtherStreet1"; self::$emailTemplate->primaryAddress->street2 = "SomeOtherStreet2"; self::$emailTemplate->primaryAddress->city = "SomeOtherCity"; self::$emailTemplate->primaryAddress->state = "SomeOtherState"; self::$emailTemplate->primaryAddress->postalCode = 2222; self::$emailTemplate->primaryAddress->country = "SomeOtherCountry"; self::$emailTemplate->likeContactState->name = 'New'; self::$emailTemplate->likeContactState->order = 1; self::$emailTemplate->user->lastName = 'Dean'; self::$emailTemplate->user->hash = 'teo8eghaipaC5ahngahleiyaebofu6oo'; self::$emailTemplate->user->language = 'en'; self::$emailTemplate->user->timeZone = 'America/Denver'; self::$emailTemplate->user->username = '******'; self::$emailTemplate->multiDropDown->data = $multiDropDownCustomFieldData2; self::$emailTemplate->multiDropDown->values->remove($multiDropDownCustomFieldValue1); self::$emailTemplate->multiDropDown->values->remove($multiDropDownCustomFieldValue2); self::$emailTemplate->multiDropDown->values->remove($multiDropDownCustomFieldValue3); self::$emailTemplate->multiDropDown->values->add($multiDropDownCustomFieldValue4); self::$emailTemplate->multiDropDown->values->add($multiDropDownCustomFieldValue5); self::$emailTemplate->multiDropDown->values->add($multiDropDownCustomFieldValue6); self::$emailTemplate->tagCloud->data = $tagCustomFieldData2; self::$emailTemplate->tagCloud->values->remove($tagCustomFieldValue1); self::$emailTemplate->tagCloud->values->remove($tagCustomFieldValue2); self::$emailTemplate->tagCloud->values->add($tagCustomFieldValue3); self::$emailTemplate->tagCloud->values->add($tagCustomFieldValue4); self::$emailTemplate->customCstm = 'text custom changed'; self::$content = 'Current: [[STRING]] [[FIRST^NAME]] [[LAST^NAME]] ' . '[[PHONE]] Old: [[WAS%STRING]] [[WAS%FIRST^NAME]] ' . '[[WAS%LAST^NAME]] [[WAS%PHONE]]'; self::$compareContent = 'Current: def Jane Bond 66778899 Old: abc James ' . 'Jackson 1122334455'; }
/** * Test users count using NonSystemUsersStateMetadataAdapter */ public function testGetUsersListUsingNonSystemUsersStateMetadataAdapter() { $users = User::getAll(); $this->assertEquals(5, count($users)); $user = UserTestHelper::createBasicUser('mysysuser'); $user->setIsSystemUser(); $this->assertTrue($user->save()); $nonSystemUsersStateMetadataAdapter = new NonSystemUsersStateMetadataAdapter(array('clauses' => array(), 'structure' => '')); $metadata = $nonSystemUsersStateMetadataAdapter->getAdaptedDataProviderMetadata(); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('User'); $where = RedBeanModelDataProvider::makeWhere('User', $metadata, $joinTablesAdapter); $models = User::getSubset($joinTablesAdapter, null, null, $where, null); $this->assertEquals(5, count($models)); $actualUsers = User::getAll(); $this->assertEquals(6, count($actualUsers)); unset($user); $user = User::getByUsername('mysysuser'); $this->assertTrue((bool) $user->isSystemUser); $user->setIsNotSystemUser(); $this->assertTrue($user->save()); unset($user); $user = User::getByUsername('mysysuser'); $this->assertEquals(0, $user->isSystemUser); $where = RedBeanModelDataProvider::makeWhere('User', $metadata, $joinTablesAdapter); $models = User::getSubset($joinTablesAdapter, null, null, $where, null); $this->assertEquals(6, count($models)); }
/** * Listado de usuarios imetos * @param type $is_admin is boolean * @param type $userid is number */ public static function users_list($is_admin = false, $userid = 0) { //$enum_tipos_usuarios=getEnumOptions('usuarios', 'usertype'); if ($users = User::getAll($is_admin)) { echo "\n <h1>Listado de usuarios iMetos</h1>\n <table class=\"table table-striped table-hover table-bordered table-condensed\">\n <tr> \n <th> </th>\n <th>Usuario</th>\n <th>Mails</th>\n </tr>"; foreach ($users as $user) { echo "\n <tr>\n <td align=\"center\">\n <a class=\"link-tabla\" href=\"javascript:borrar_usuario('{$user->getId()}');\">\n <i class=\"fa fa-trash\"></i>\n </a> "; if ($user->getEnableFTP()) { echo " <a class=\"link-tabla\" href=\"javascript:realizar_informe('{$user->getUserFTP()}');\" title=\"Revisar sondas detenidas\">\n <i class=\"fa fa-terminal\"></i>\n </a> "; } echo " <a class=\"link-tabla\" href=\"javascript:mostrar_ocultar('conf_usuario_{$user->getId()}');\" title=\"Configuración de usuario\">\n <i class=\"fa fa-user\"></i>\n </a> "; echo " <a class=\"link-tabla\" href=\"javascript:mostrar_ocultar('conf_exporta_{$user->getId()}');\" title=\"Configuración de estaciones\">\n <i class=\"fa fa-pencil\"></i>\n </a>"; echo " </td>\n <td>{$user->getUsername()}</td>\n <td>{$user->getEmails()}</td>\n </tr>\n <tr>\n <td colspan=\"6\">\n <div id=\"conf_usuario_{$user->getId()}\" style=\"display:none\">\n <form name=\"user_edit\" method=\"post\" action=\"/users/edit/{$user->getId()}\">"; User::formulario_editar_usuario($user); echo " <div class=\"panel-body\" style=\"text-align:right\">\n <div class=\"form-group\">\n <button type=\"submit\" name=\"save_user\" class=\"btn btn-default\"><i class=\"fa fa-floppy-o\" aria-hidden=\"true\"></i> Guardar usuario</button> \n <button type=\"button\" name=\"close\" class=\"btn btn-default\" onClick=\"javascript:mostrar_ocultar('conf_usuario_{$user->getId()}');\"><i class=\"fa fa-times\" aria-hidden=\"true\"></i> Cerrar</button> \n </div>\n </div>\n </form>"; echo " </div>\n <div class=\"conf_exporta\" id=\"conf_exporta_{$user->getId()}\" style=\"display:none\">"; // si esta habilitado muestra info de estaciones if ($user->getEnableMySQL()) { $BD = new IMETOS($user->getIdMySQL(), $user->getServerMySQL(), $user->getDatabaseMySQL(), $user->getUserMySQL(), $user->getPasswMySQL()); if ($stations = Station::getAll($BD, $user->getId())) { Station::listAll($BD, $stations, $user); } } echo " </div> <!-- cierre de div conf_exporta -->\n </td>\n </tr>"; } echo "</table>"; } else { echo "No se pudo cargar los usuarios<br>"; } }
<?php include "../conf/main.php"; include "../libs/functions.php"; include "../model/users.php"; //echo "test"; $user = new User(null); $all = $user->getAll(); //print_r($all); $i = 0; foreach ($all['data'] as $value) { $db = $value['screenname']; if ($db != "template1" and $db != "template0" and $db != "postgres" and $db != "postgis_template" and $db != "mhoegh" and $db != "mygeocloud") { $cmd = "pg_dump -h localhost -p 5432 -U postgres -Fc -b -f '/home/mh/backup/{$db}.backup' {$db}\n"; exec($cmd); $cmd = "rsync -e 'ssh -i us1.pem' -avz /home/mh/backup/{$db}.backup ubuntu@us1.mapcentia.com:/home/mh/upload\n"; echo $cmd; //exec($cmd); //unlink("/home/mh/backup/{$db}.backup"); $i++; } }
protected static function rebuildViaSlowWay($modelClassName) { // The slow way will remain here as documentation // for what the optimized way is doing. $mungeTableName = self::getMungeTableName($modelClassName); self::recreateTable($mungeTableName); //Specifically call RedBeanModel to avoid the use of the security in OwnedSecurableItem since for //rebuild it needs to look at all models regardless of permissions of the current user. $modelCount = RedBeanModel::getCount(null, null, $modelClassName); $subset = intval($modelCount / 20); if ($subset < 100) { $subset = 100; } elseif ($subset > 1000) { $subset = 1000; } $users = User::getAll(); $groups = Group::getAll(); $roles = Role::getAll(); for ($i = 0; $i < $modelCount; $i += $subset) { //Specifically call RedBeanModel to avoid the use of the security in OwnedSecurableItem since for //rebuild it needs to look at all models regardless of permissions of the current user. $models = RedBeanModel::getSubset(null, $i, $subset, null, null, $modelClassName); foreach ($models as $model) { assert('$model instanceof SecurableItem'); $securableItemId = $model->getClassId('SecurableItem'); foreach ($users as $user) { list($allowPermissions, $denyPermissions) = $model->getExplicitActualPermissions($user); $effectiveExplicitPermissions = $allowPermissions & ~$denyPermissions; if (($effectiveExplicitPermissions & Permission::READ) == Permission::READ) { self::incrementCount($mungeTableName, $securableItemId, $user); } } foreach ($groups as $group) { list($allowPermissions, $denyPermissions) = $model->getExplicitActualPermissions($group); $effectiveExplicitPermissions = $allowPermissions & ~$denyPermissions; if (($effectiveExplicitPermissions & Permission::READ) == Permission::READ) { self::incrementCount($mungeTableName, $securableItemId, $group); foreach ($group->users as $user) { if ($user->role->id > 0) { self::incrementParentRolesCounts($mungeTableName, $securableItemId, $user->role); } } foreach ($group->groups as $subGroup) { self::processNestedGroupWhereParentHasReadPermissionOnSecurableItem($mungeTableName, $securableItemId, $subGroup); } } } foreach ($roles as $role) { $count = self::getRoleMungeCount($model, $role); assert('$count >= 0'); if ($count > 0) { self::setCount($mungeTableName, $securableItemId, $role, $count); } } } } }
/** * @depends testSimpleUserImportWhereAllRowsSucceed */ public function testUserImportWithOptionalFields() { Yii::app()->user->userModel = User::getByUsername('super'); $users = User::getAll(); $this->assertEquals(11, count($users)); $import = new Import(); $serializedData['importRulesType'] = 'User'; $serializedData['firstRowIsHeaderRow'] = true; $import->serializedData = serialize($serializedData); $this->assertTrue($import->save()); ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerWithOptionalFields.csv', $import->getTempTableName(), true, Yii::getPathOfAlias('application.modules.users.tests.unit.files')); $this->assertEquals(11, ImportDatabaseUtil::getCount($import->getTempTableName())); // includes header rows. $defaultLanguage = Yii::app()->language; $localeIds = ZurmoLocale::getSelectableLocaleIds(); $defaultLocale = $localeIds[0]; $timezoneIdentifiers = DateTimeZone::listIdentifiers(); $defaultTimeZone = $timezoneIdentifiers[0]; $defaultCurrency = Yii::app()->currencyHelper->getActiveCurrencyForCurrentUser(); $defaultCurrencyId = $defaultCurrency->id; $mappingData = array('column_0' => array('attributeIndexOrDerivedType' => 'username', 'type' => 'importColumn', 'mappingRulesData' => array()), 'column_1' => array('attributeIndexOrDerivedType' => 'Password', 'type' => 'importColumn', 'mappingRulesData' => array('PasswordDefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => null))), 'column_3' => ImportMappingUtil::makeStringColumnMappingData('firstName'), 'column_4' => ImportMappingUtil::makeStringColumnMappingData('lastName'), 'column_5' => array('attributeIndexOrDerivedType' => 'language', 'type' => 'extraColumn', 'mappingRulesData' => array('DefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => $defaultLanguage))), 'column_6' => array('attributeIndexOrDerivedType' => 'locale', 'type' => 'extraColumn', 'mappingRulesData' => array('DefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => $defaultLocale))), 'column_7' => array('attributeIndexOrDerivedType' => 'timeZone', 'type' => 'extraColumn', 'mappingRulesData' => array('DefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => $defaultTimeZone))), 'column_8' => array('attributeIndexOrDerivedType' => 'currency', 'type' => 'extraColumn', 'mappingRulesData' => array('DefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => $defaultCurrencyId)))); $importRules = ImportRulesUtil::makeImportRulesByType('Users'); $page = 0; $config = array('pagination' => array('pageSize' => 50)); //This way all rows are processed. $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config); $dataProvider->getPagination()->setCurrentPage($page); $importResultsUtil = new ImportResultsUtil($import); $messageLogger = new ImportMessageLogger(); ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, new ExplicitReadWriteModelPermissions(), $messageLogger); $importResultsUtil->processStatusAndMessagesForEachRow(); //Confirm that 10 new models are created. $users = User::getAll(); $this->assertEquals(21, count($users)); $user = User::getByUsername('myusername11'); $this->assertEquals($defaultLanguage, $user->language); $this->assertEquals($defaultLocale, $user->locale); $this->assertEquals($defaultTimeZone, $user->timeZone); $this->assertEquals($defaultCurrency, $user->currency); //Confirm 10 rows were processed as 'created'. $this->assertEquals(10, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::CREATED)); //Confirm that 0 rows were processed as 'updated'. $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::UPDATED)); //Confirm 2 rows were processed as 'errors'. $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR)); $beansWithErrors = ImportDatabaseUtil::getSubset($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR); $this->assertEquals(0, count($beansWithErrors)); }
$debtObj->setOwed_by($_POST['user_id'][$i]); $debt_total = $_POST['drinks_owed'][$i] + $_POST['food_owed'][$i]; $total += $debt_total; $debtObj->setAmount($debt_total); $debtObj->create(); //echo "<p>" . $_POST['user_id'][$i] . " owes " . $_COOKIE['user_id'] . " £" . $_POST['drinks_owed'][$i] . " for drinks and £" . $_POST['food_owed'][$i] . " for food for a total of £" . $total . "</p>"; } $paymentObj->setId($payment_id); $paymentObj->setTotal($total); $paymentObj->setDate($_POST['date']); $paymentObj->update(); header("Location: dashboard.php"); exit; } else { // Get list of users for form $user_arr = User::getAll(); // Built debt form input $userObj = new User(); $debt_form = "<select name='user_id[]'>\n"; $debt_form .= "<option>Select a user</option>\n"; foreach ($user_arr as $user_id) { $userObj->setId($user_id); $userObj->load(); $debt_form .= "<option value='{$user_id}'>" . $userObj->getName() . "</option>\n"; } $debt_form .= "</select>\n"; $debt_form .= "<div class=\"input-prepend \">\n <span class=\"add-on\">£</span>\n <input class=\"input-medium drinks\" id=\"drinks_owed1\" name=\"drinks_owed[]\" size=\"16\" type=\"number\" placeholder=\"Drinks\">\n </div>\n"; $debt_form .= "<div class=\"input-prepend \">\n <span class=\"add-on\">£</span>\n <input class=\"input-medium food\" id=\"food_owed1\" name=\"food_owed[]\" size=\"16\" type=\"number\" placeholder=\"Food\">\n </div>\n"; if (!$is_ajax) { include 'header.php'; echo "<h3>Add Debt</h3>";
<?php include 'configs/configs.php'; //$proID = $_POST['proID']; //$tmp="images/productimg/"; //--hiện ra trang quản lý người dùng. $newUser = User::getAll(); //print_r($newUser); $smarty->assign('newUser', $newUser); //$smarty->assign('tmp', $tmp); $smarty->display('manageuser.tpl');
public function testSuperUserAllDefaultControllerActions() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); //Test all default controller actions that do not require any POST/GET variables to be passed. //This does not include portlet controller actions. $this->runControllerWithNoExceptionsAndGetContent('users/default'); $this->runControllerWithNoExceptionsAndGetContent('users/default/index'); $this->runControllerWithNoExceptionsAndGetContent('users/default/list'); $this->runControllerWithNoExceptionsAndGetContent('users/default/create'); $this->runControllerWithNoExceptionsAndGetContent('users/default/profile'); //Access to admin configuration should be allowed. $this->runControllerWithNoExceptionsAndGetContent('configuration'); //Default Controller actions requiring some sort of parameter via POST or GET //Load Model Edit Views $users = User::getAll(); $this->assertEquals(5, count($users)); $aUser = User::getByUsername('auser'); $bUser = User::getByUsername('buser'); $cUser = User::getByUsername('cuser'); $dUser = User::getByUsername('duser'); $super = User::getByUsername('super'); $this->setGetArray(array('id' => $super->id)); //Access to allowed to view Audit Trail. $this->runControllerWithNoExceptionsAndGetContent('users/default/auditEventsModalList'); $this->setGetArray(array('id' => $aUser->id)); //Access to allowed to view Audit Trail. $this->runControllerWithNoExceptionsAndGetContent('users/default/auditEventsModalList'); $this->setGetArray(array('id' => $bUser->id)); //Access to allowed to view Audit Trail. $this->runControllerWithNoExceptionsAndGetContent('users/default/auditEventsModalList'); $this->setGetArray(array('id' => $super->id)); //Access to User Role edit link and control available. $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/edit'); $this->assertContains('User_role_SelectLink', $content); $this->assertContains('User_role_name', $content); $this->setGetArray(array('id' => $aUser->id)); //Access to User Role edit link and control available. $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/edit'); $this->assertContains('User_role_SelectLink', $content); $this->assertContains('User_role_name', $content); $users = User::getAll(); $this->assertEquals(5, count($users)); //Save user. $this->assertTrue($aUser->id > 0); $this->assertEquals('aUserson', $aUser->lastName); $this->assertEquals(null, $aUser->officePhone); $this->setGetArray(array('id' => $aUser->id)); $this->setPostArray(array('User' => array('officePhone' => '456765421'))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/edit'); $users = User::getAll(); $this->assertEquals(5, count($users)); $aUser = User::getById($aUser->id); $this->assertEquals('456765421', $aUser->officePhone); $this->assertEquals('aUserson', $aUser->lastName); //Test having a failed validation on the user during save. $this->setGetArray(array('id' => $aUser->id)); $this->setPostArray(array('User' => array('lastName' => ''))); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/edit'); $this->assertContains('Name cannot be blank', $content); $users = User::getAll(); $this->assertEquals(5, count($users)); //LastName for aUser should still be aUserson. //Need to forget aUser, since it has lastName = '' from the setAttributes called in actionEdit. //Retrieve aUser and confirm the lastName is still aUserson. $aUser->forget(); $aUser = User::getByUsername('auser'); $this->assertEquals('aUserson', $aUser->lastName); //Load Model Detail View $this->setGetArray(array('id' => $aUser->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('users/default/details'); //Load game dashboard view $this->setGetArray(array('id' => $aUser->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('users/default/gameDashboard'); //Load Model Security Detail View $this->setGetArray(array('id' => $aUser->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('users/default/securityDetails'); //Load Model Security Detail View for super user $this->setGetArray(array('id' => $super->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('users/default/securityDetails'); //Load Model MassEdit Views. //MassEdit view for single selected ids $this->setGetArray(array('selectedIds' => '4,5,6,7', 'selectAll' => '')); // Not Coding Standard $this->resetPostArray(); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/massEdit'); $this->assertContains('<strong>4</strong> records selected for updating', $content); //MassEdit view for all result selected ids $users = User::getAll(); $this->assertEquals(5, count($users)); $this->setGetArray(array('selectAll' => '1')); $this->resetPostArray(); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/massEdit'); $this->assertContains('<strong>5</strong> records selected for updating', $content); //save Model MassEdit for selected Ids //Test that the 4 contacts do not have the office phone number we are populating them with. $user1 = User::getById($aUser->id); $user2 = User::getById($bUser->id); $user3 = User::getById($cUser->id); $user4 = User::getById($dUser->id); $this->assertNotEquals('7788', $user1->officePhone); $this->assertNotEquals('7788', $user2->officePhone); $this->assertNotEquals('7788', $user3->officePhone); $this->assertNotEquals('7788', $user4->officePhone); $this->setGetArray(array('selectedIds' => $aUser->id . ',' . $bUser->id, 'selectAll' => '', 'User_page' => 1)); $this->setPostArray(array('User' => array('officePhone' => '7788'), 'MassEdit' => array('officePhone' => 1))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/massEdit'); //Test that the 2 contacts have the new office phone number and the other contacts do not. $user1 = User::getById($aUser->id); $user2 = User::getById($bUser->id); $user3 = User::getById($cUser->id); $user4 = User::getById($dUser->id); $this->assertEquals('7788', $user1->officePhone); $this->assertEquals('7788', $user2->officePhone); $this->assertNotEquals('7788', $user3->officePhone); $this->assertNotEquals('7788', $user4->officePhone); //save Model MassEdit for entire search result $this->setGetArray(array('selectAll' => '1', 'User_page' => 1)); $this->setPostArray(array('User' => array('officePhone' => '1234'), 'MassEdit' => array('officePhone' => 1))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/massEdit'); //Test that all accounts have the new phone number. $user1 = User::getById($aUser->id); $user2 = User::getById($bUser->id); $user3 = User::getById($cUser->id); $user4 = User::getById($dUser->id); $this->assertEquals('1234', $user1->officePhone); $this->assertEquals('1234', $user2->officePhone); $this->assertEquals('1234', $user3->officePhone); $this->assertEquals('1234', $user4->officePhone); //Run Mass Update using progress save. $pageSize = Yii::app()->pagination->getForCurrentUserByType('massEditProgressPageSize'); $this->assertEquals(5, $pageSize); Yii::app()->pagination->setForCurrentUserByType('massEditProgressPageSize', 1); //The page size is smaller than the result set, so it should exit. $this->runControllerWithExitExceptionAndGetContent('users/default/massEdit'); //save Modal MassEdit using progress load for page 2, 3, 4 and 5. $this->setGetArray(array('selectAll' => '1', 'User_page' => 2)); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/massEditProgressSave'); $this->assertContains('"value":40', $content); $this->setGetArray(array('selectAll' => '1', 'User_page' => 3)); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/massEditProgressSave'); $this->assertContains('"value":60', $content); $this->setGetArray(array('selectAll' => '1', 'User_page' => 4)); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/massEditProgressSave'); $this->assertContains('"value":80', $content); $this->setGetArray(array('selectAll' => '1', 'User_page' => 5)); $content = $this->runControllerWithNoExceptionsAndGetContent('users/default/massEditProgressSave'); $this->assertContains('"value":100', $content); //Set page size back to old value. Yii::app()->pagination->setForCurrentUserByType('massEditProgressPageSize', $pageSize); //Autocomplete for User $this->setGetArray(array('term' => 'auser')); $this->runControllerWithNoExceptionsAndGetContent('users/default/autoComplete'); //actionModalList $this->setGetArray(array('modalTransferInformation' => array('sourceIdFieldId' => 'x', 'sourceNameFieldId' => 'y', 'modalId' => 'z'))); $this->runControllerWithNoExceptionsAndGetContent('users/default/modalList'); //Change password view. $this->setGetArray(array('id' => $aUser->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('users/default/changePassword'); //Failed change password validation $this->setPostArray(array('ajax' => 'edit-form', 'UserPasswordForm' => array('newPassword' => '', 'newPassword_repeat' => ''))); $content = $this->runControllerWithExitExceptionAndGetContent('users/default/changePassword'); $this->assertTrue(strlen($content) > 50); //approximate, but should definetely be larger than 50. //Successful change password validation $this->setPostArray(array('ajax' => 'edit-form', 'UserPasswordForm' => array('newPassword' => 'aNewPassword', 'newPassword_repeat' => 'aNewPassword'))); $content = $this->runControllerWithExitExceptionAndGetContent('users/default/changePassword'); $this->assertEquals('[]', $content); //Successful saved password change. $this->setPostArray(array('save' => 'Save', 'UserPasswordForm' => array('newPassword' => 'bNewPassword', 'newPassword_repeat' => 'bNewPassword'))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/changePassword'); //Login using new password successfully. $identity = new UserIdentity('auser', 'bNewPassword'); $authenticated = $identity->authenticate(); $this->assertEquals(0, $identity->errorCode); $this->assertTrue($authenticated); //User Configuration UI. Change aUser configuration values. //First make sure settings are not what we are setting them too. $this->assertNotEquals(9, Yii::app()->pagination->getByUserAndType($aUser, 'listPageSize')); $this->assertNotEquals(4, Yii::app()->pagination->getByUserAndType($aUser, 'subListPageSize')); //Load up configuration page. $this->setGetArray(array('id' => $aUser->id)); $this->runControllerWithNoExceptionsAndGetContent('users/default/configurationEdit'); //Post fake save that will fail validation. $this->setGetArray(array('id' => $aUser->id)); $this->setPostArray(array('UserConfigurationForm' => array('listPageSize' => 0, 'subListPageSize' => 4))); $this->runControllerWithNoExceptionsAndGetContent('users/default/configurationEdit'); //Post fake save that will pass validation. $this->setGetArray(array('id' => $aUser->id)); $this->setPostArray(array('UserConfigurationForm' => array('listPageSize' => 9, 'subListPageSize' => 4))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/configurationEdit'); $this->assertEquals('User configuration saved successfully.', Yii::app()->user->getFlash('notification')); //Check to make sure user configuration is actually changed. $this->assertEquals(9, Yii::app()->pagination->getByUserAndType($aUser, 'listPageSize')); $this->assertEquals(4, Yii::app()->pagination->getByUserAndType($aUser, 'subListPageSize')); //Confirm current user has certain session values $this->assertNotEquals(7, Yii::app()->user->getState('listPageSize')); $this->assertNotEquals(4, Yii::app()->user->getState('subListPageSize')); //Change current user configuration values. (Yii::app()->user->userModel) //First make sure settings are not what we are setting them too. $this->assertNotEquals(7, Yii::app()->pagination->getForCurrentUserByType('listPageSize')); //Load up configuration page. $this->setGetArray(array('id' => Yii::app()->user->userModel->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('users/default/configurationEdit'); //Post fake save that will fail validation. $this->setGetArray(array('id' => Yii::app()->user->userModel->id)); $this->setPostArray(array('UserConfigurationForm' => array('listPageSize' => 0, 'subListPageSize' => 4))); $this->runControllerWithNoExceptionsAndGetContent('users/default/configurationEdit'); //Post fake save that will pass validation. $this->setGetArray(array('id' => Yii::app()->user->userModel->id)); $this->setPostArray(array('UserConfigurationForm' => array('listPageSize' => 7, 'subListPageSize' => 4))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/configurationEdit'); $this->assertEquals('User configuration saved successfully.', Yii::app()->user->getFlash('notification')); //Check to make sure user configuration is actually changed. $this->assertEquals(7, Yii::app()->pagination->getForCurrentUserByType('listPageSize')); //Check getState data. since it should be updated for current user. $this->assertEquals(7, Yii::app()->user->getState('listPageSize')); $this->assertEquals(4, Yii::app()->user->getState('subListPageSize')); //User Notification Configuration UI. Change aUser notification configuration values. //First make sure settings all default values are true $notificationSettings = UserNotificationUtil::getNotificationSettingsByUser($aUser); $notificationSettingsNames = UserNotificationUtil::getAllNotificationSettingAttributes(); foreach ($notificationSettingsNames as $setting) { list($settingName, $type) = UserNotificationUtil::getSettingNameAndTypeBySuffixedConfigurationAttribute($setting); $this->assertTrue((bool) $notificationSettings[$settingName][$type]); } //Load up notification configuration page. $this->setGetArray(array('id' => $aUser->id)); $this->runControllerWithNoExceptionsAndGetContent('users/default/notificationConfiguration'); //Post fake save that will pass validation. $this->setGetArray(array('id' => $aUser->id)); $this->setPostArray(array('UserNotificationConfigurationForm' => array('enableConversationInvitesNotificationInbox' => 0))); $this->runControllerWithRedirectExceptionAndGetContent('users/default/notificationConfiguration'); $this->assertEquals('User notifications configuration saved successfully.', Yii::app()->user->getFlash('notification')); //Check to make sure user notification configuration is actually changed. $this->assertFalse((bool) UserNotificationUtil::isEnabledByUserAndNotificationNameAndType($aUser, 'enableConversationInvitesNotification', 'inbox')); }
<?php require_once 'boot.php'; $users = User::getAll(); require_once '_header.php'; ?> <div class="container"> <div class="row"> <div class="span12"> <h1>Users</h1> <table class="table table-bordered"> <thead> <tr> <td>id</td> <td>name</td> <td>email</td> <td>campaign</td> <td>campaign key</td> <td></td> </tr> </thead> <tbody> <?php foreach ($users as $user) { ?> <tr> <td><?php echo $user->id; ?> </td>
public function moh_active() { $status = 1; $use_id = $this->uri->segment(3); $state = Doctrine::getTable('user')->findOneById($use_id); $state->status = $status; $state->save(); $data['banner_text'] = "All Users"; $data['title'] = "View Users"; $data['content_view'] = "users_moh_v"; $data['result'] = User::getAll(); $data['counties'] = Counties::getAll(); $this->load->view("template", $data); }
// Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) { header("Access-Control-Allow-Methods: GET, PUT, POST, OPTIONS"); } if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) { header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); } exit(0); } require_once 'Slim/Slim.php'; require_once 'models/User.php'; $app = new Slim(); $user = new User(); $app->get('/users', function () use($user) { $user->getAll(); }); $app->get('/users/:id', function ($id) use($user) { $user->getById($id); }); $app->get('/users/:id/friends', function ($id) use($user) { $user->getFriends($id); }); $app->get('/users/:id/score', function ($id) use($user) { $user->getScore($id); }); $app->get('/users/:id/rewards', function ($id) use($user) { $user->getRewards($id); }); $app->get('/users/search/:name', function ($name) use($user) { $user->getByName($name);
protected static function makeNonUserMembershipDataFromUserMembershipData(array $userData) { $allUsers = User::getAll(); $data = array(); foreach ($allUsers as $user) { if (empty($userData[$user->id]) && !$user->isSystemUser) { $data[$user->id] = strval($user); } } return $data; }
/** * @depends testSuperUserAllSimpleControllerActions */ public function testSuperUserCreateMission() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $mary = User::getByUsername('mary'); $missions = Mission::getAll(); $this->assertEquals(0, count($missions)); $this->setPostArray(array('Mission' => array('description' => 'TestDescription', 'reward' => 'Reward'))); $this->runControllerWithRedirectExceptionAndGetContent('missions/default/create'); //Confirm mission saved. $missions = Mission::getAll(); $this->assertEquals(1, count($missions)); $this->assertEquals('TestDescription', $missions[0]->description); $this->assertEquals(Mission::STATUS_AVAILABLE, $missions[0]->status); //Confirm everyone has read/write $everyoneGroup = Group::getByName(Group::EVERYONE_GROUP_NAME); $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($missions[0]); $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables(); $this->assertEquals(1, count($readWritePermitables)); $this->assertTrue(isset($readWritePermitables[$everyoneGroup->id])); //Confirm email was sent $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount()); $this->assertEquals(0, Yii::app()->emailHelper->getSentCount()); $emailMessages = EmailMessage::getAll(); //Dont send message to super neither to steven (he has turned off) $this->assertEquals(2, count($emailMessages[0]->recipients)); $this->assertEquals(4, count(User::getAll())); }
/** * Walkthrough test for synchronous download */ public function testAsynchronousDownloadDefaultControllerActions() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $users = User::getAll(); if (count($users)) { foreach ($users as $user) { if ($user->id !== $super->id) { $user->delete(); } } } $users = array(); for ($i = 0; $i <= ExportModule::$asynchronousThreshold + 1; $i++) { $users[] = UserTestHelper::createBasicUser('aUser' . $i); } $this->setGetArray(array('User_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => '')); $this->runControllerWithRedirectExceptionAndGetUrl('users/default/export'); // Start background job $job = new ExportJob(); $this->assertTrue($job->run()); $exportItems = ExportItem::getAll(); $this->assertEquals(1, count($exportItems)); $fileModel = $exportItems[0]->exportFileModel; $this->assertEquals(1, $exportItems[0]->isCompleted); $this->assertEquals('csv', $exportItems[0]->exportFileType); $this->assertEquals('users', $exportItems[0]->exportFileName); $this->assertTrue($fileModel instanceof ExportFileModel); $this->assertEquals(1, count(Notification::getAll())); $this->assertEquals(1, count(NotificationMessage::getAll())); // Check export job, when many ids are selected. // This will probably never happen, but we need test for this case too. $notificationsBeforeCount = count(Notification::getAll()); $notificationMessagesBeforeCount = count(NotificationMessage::getAll()); // Now test case when multiple ids are selected $exportItems = ExportItem::getAll(); if (count($exportItems)) { foreach ($exportItems as $exportItem) { $exportItem->delete(); } } $selectedIds = ""; foreach ($users as $user) { $selectedIds .= $user->id . ","; // Not Coding Standard } $this->setGetArray(array('UsersSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => ''), 'User_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => "{$selectedIds}")); $this->runControllerWithRedirectExceptionAndGetUrl('users/default/export'); // Start background job $job = new ExportJob(); $this->assertTrue($job->run()); $exportItems = ExportItem::getAll(); $this->assertEquals(1, count($exportItems)); $fileModel = $exportItems[0]->exportFileModel; $this->assertEquals(1, $exportItems[0]->isCompleted); $this->assertEquals('csv', $exportItems[0]->exportFileType); $this->assertEquals('users', $exportItems[0]->exportFileName); $this->assertTrue($fileModel instanceof ExportFileModel); $this->assertEquals($notificationsBeforeCount + 1, count(Notification::getAll())); $this->assertEquals($notificationMessagesBeforeCount + 1, count(NotificationMessage::getAll())); }
function getPage() { //Create instances $language = new Language(); $template = new Template(); $post = new Post(); $user = new User(); //getAvailableLanguages $availableLanguages = $language->getAvailableLanguages(); //getAvailableTemplates $availableTemplates = $template->getAvailableTemplates(); //Get requestedLanguage & requestedTemplate $urlParts = explode('/', $_GET['__cap']); //Set requestedLanguage if (!isset($urlParts[2]) || $urlParts[2] === 'index.php' || $urlParts[2] === '') { //Get browserLanguage $browserLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); if (in_array($browserLanguage, $availableLanguages, true)) { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $browserLanguage); } else { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $availableLanguages[0]); } } else { if (in_array($urlParts[2], $availableLanguages, true)) { $requestedLanguage = $urlParts[2]; } else { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $availableLanguages[0]); } } //Set default site $defaultSite = 'Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[0]; //Set requestedTemplate if (isset($urlParts[3])) { if (in_array($urlParts[3], $availableTemplates, true)) { $requestedTemplate = $urlParts[3]; } else { header($defaultSite); } } else { header($defaultSite); } //Set requestedParameter if (isset($urlParts[4])) { $requestedParameter = $urlParts[4]; } //getLanguageArray by requestedLanguage $languageArray = $language->getLanguageArray($requestedLanguage); //getTemplate by requestedTemplate $page = $template->getTemplate($requestedTemplate); switch ($requestedTemplate) { case 'Admin': Bloggy::checkSessionRedirect($defaultSite); Bloggy::checkAdminRedirect($defaultSite); $contentAccounts = null; $users = $user->getAll(); foreach ($users as $key => $value) { $entry = file_get_contents(DOCUMENT_ROOT . '/template/account_entry.html'); $entry = str_replace('{ACCOUNT_DELETE_HREF}', 'DoDeleteAccount/' . $value['id'], $entry); $entry = str_replace('{TXT_ACCOUNT_NAME}', $value['name'], $entry); $entry = str_replace('{TXT_ACCOUNT_ISADMIN}', $value['isAdmin'], $entry); $contentAccounts = $contentAccounts . $entry; } $page = str_replace('{ACCOUNT_ENTRIES}', $contentAccounts, $page); $contentPosts = null; $posts = $post->getAll(); foreach ($posts as $key => $value) { $entry = file_get_contents(DOCUMENT_ROOT . '/template/posts_entry.html'); $entry = str_replace('{POSTS_EDIT_HREF}', 'Edit/' . $value['id'], $entry); $entry = str_replace('{POSTS_LINK_HREF}', 'Detail/' . $value['id'], $entry); $entry = str_replace('{POSTS_DELETE_HREF}', 'DoDeletePost/' . $value['id'], $entry); $entry = str_replace('{TXT_POSTS_TITLE}', $value['title'], $entry); $entry = str_replace('{TXT_POSTS_SUBTITLE}', $value['subTitle'], $entry); $entry = str_replace('{TXT_POSTS_MODIFIED}', $value['modifiedDate'], $entry); $contentPosts = $contentPosts . $entry; } $page = str_replace('{POST_ENTRIES}', $contentPosts, $page); break; case 'Account': Bloggy::checkSessionRedirect($defaultSite); $content = null; $user = $user->getEntryById($_SESSION['userId']); $entry = file_get_contents(DOCUMENT_ROOT . '/template/account_entry.html'); $entry = str_replace('{ACCOUNT_DELETE_HREF}', 'DoDeleteAccount/' . $user['id'], $entry); $entry = str_replace('{TXT_ACCOUNT_NAME}', $user['name'], $entry); $entry = str_replace('{TXT_ACCOUNT_ISADMIN}', $user['isAdmin'], $entry); $content = $content . $entry; $page = str_replace('{ACCOUNT_ENTRIES}', $content, $page); break; case 'Create': Bloggy::checkSessionRedirect($defaultSite); break; case 'Detail': $entry = $post->getEntryById($requestedParameter); $page = str_replace('{TXT_POST_IMAGE}', $entry['imagePath'], $page); $page = str_replace('{TXT_POST_AUTHOR}', $post->getAuthorNameById($entry['author']), $page); $page = str_replace('{TXT_POST_DATE}', $entry['creationDate'], $page); $page = str_replace('{TXT_POST_TITLE}', $entry['title'], $page); $page = str_replace('{TXT_POST_SUBTITLE}', $entry['subTitle'], $page); $page = str_replace('{TXT_POST_CONTENT}', $entry['content'], $page); break; case 'DoCreatePost': Bloggy::checkSessionRedirect($defaultSite); if (isset($_POST)) { $request = []; $request['author'] = $_SESSION['userId']; $request['title'] = $_POST['title']; $request['subTitle'] = $_POST['subTitle']; $request['content'] = $_POST['content']; $request['creationDate'] = date('Y-m-d h:i:s'); $request['modifiedDate'] = date('Y-m-d h:i:s'); $_POST = []; if (isset($_FILES)) { $file = $_FILES['image']['name']; $fileExt = pathinfo($file, PATHINFO_EXTENSION); $tempFile = $_FILES['image']['tmp_name']; $storeFolder = '/data/media/'; $existingFiles = scandir($storeFolder, 1); do { $randomString = $post->generateRandomString(); } while (in_array($randomString, $existingFiles, false)); $targetFile = DOCUMENT_ROOT . $storeFolder . $randomString . '.' . $fileExt; move_uploaded_file($tempFile, $targetFile); $request['image'] = $storeFolder . $randomString . '.' . $fileExt; } $post->createPost($request); header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[1]); } break; case 'DoDeleteAccount': Bloggy::checkSessionRedirect($defaultSite); $user->checkIfOwnAccountRedirect($_SESSION['userId'], $requestedParameter, $defaultSite); $user->deleteUserById($requestedParameter); header('Location: ' . $_SERVER['HTTP_REFERER']); break; case 'DoDeletePost': Bloggy::checkSessionRedirect($defaultSite); $post->checkIfOwnPostRedirect($_SESSION['userId'], $requestedParameter, $defaultSite); $post->deletePostById($requestedParameter); header('Location: ' . $_SERVER['HTTP_REFERER']); break; case 'DoEditPost': Bloggy::checkSessionRedirect($defaultSite); $post->checkIfOwnPostRedirect($_SESSION['userId'], $requestedParameter, $defaultSite); if (isset($_POST)) { $request = []; $request['id'] = $requestedParameter; $request['title'] = $_POST['title']; $request['subTitle'] = $_POST['subTitle']; $request['content'] = $_POST['content']; $request['modifiedDate'] = date('Y-m-d h:i:s'); $_POST = []; $entry = $post->getEntryById($requestedParameter); $file = $_FILES['image']['name']; $fileExt = pathinfo($file, PATHINFO_EXTENSION); $allowedFileExt = ['png', 'jpg', 'jpeg', 'gif']; if (in_array(strtolower($fileExt), $allowedFileExt, true)) { $tempFile = $_FILES['image']['tmp_name']; $storeFolder = '/data/media/'; $existingFiles = scandir($storeFolder, 1); do { $randomString = $post->generateRandomString(); } while (in_array($randomString, $existingFiles, false)); $targetFile = DOCUMENT_ROOT . $storeFolder . $randomString . '.' . $fileExt; move_uploaded_file($tempFile, $targetFile); $request['image'] = $storeFolder . $randomString . '.' . $fileExt; //Unlink (delete) outdated image $unlinkFile = $entry['imagePath']; unlink(DOCUMENT_ROOT . $unlinkFile); } else { $request['image'] = $entry['imagePath']; } $post->editPost($request); header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[12]); } break; case 'DoLogin': if (isset($_POST)) { $id = $user->getIdByName('\'' . $_POST['Username'] . '\''); $hash = $user->getHashById($id); if (password_verify($_POST['Password'], $hash)) { $request = []; $request['username'] = $_POST['Username']; $request['password'] = $_POST['Password']; $_POST = []; $id = $user->getIdByName('\'' . $request['username'] . '\''); $_SESSION['userId'] = $id; $_SESSION['hash'] = $hash; header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[0]); } else { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[3]); } } else { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[3]); } break; case 'DoSignup': if (isset($_POST)) { $id = $user->getIdByName('\'' . $_POST['Username'] . '\''); if ($id === null || $id === '') { $request = []; $request['username'] = $_POST['Username']; $request['password'] = $_POST['Password']; $request['passwordRepeat'] = $_POST['PasswordRepeat']; $_POST = []; $user->createUser($request); $id = $user->getIdByName('\'' . $request['username'] . '\''); $hash = $user->getHashById($id); $_SESSION['userId'] = $id; $_SESSION['hash'] = $hash; header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[5]); } else { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[4]); } } else { header('Location: ' . PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[3]); } break; case 'Edit': Bloggy::checkSessionRedirect($defaultSite); $post->checkIfOwnPostRedirect($_SESSION['userId'], $requestedParameter, $defaultSite); $entry = $post->getEntryById($requestedParameter); $page = str_replace('{TXT_EDIT_ID}', $entry['id'], $page); $page = str_replace('{TXT_EDIT_TITLE}', $entry['title'], $page); $page = str_replace('{TXT_EDIT_SUBTITLE}', $entry['subTitle'], $page); $page = str_replace('{TXT_EDIT_CONTENT}', $entry['content'], $page); break; case 'Home': $content = null; $posts = $post->getAll(); foreach ($posts as $key => $value) { $entry = file_get_contents(DOCUMENT_ROOT . '/template/home_entry.html'); $entry = str_replace('{POST_LINK_HREF}', 'Detail/' . $value['id'], $entry); $entry = str_replace('{TXT_POST_TITLE}', $value['title'], $entry); $entry = str_replace('{TXT_POST_SUBTITLE}', $value['subTitle'], $entry); $entry = str_replace('{TXT_POST_AUTHOR}', $post->getAuthorNameById($value['author']), $entry); $entry = str_replace('{TXT_POST_DATE}', $value['creationDate'], $entry); $content = $content . $entry; } $page = str_replace('{POST_ENTRIES}', $content, $page); break; case 'Logout': session_destroy(); header($defaultSite); break; case 'Posts': Bloggy::checkSessionRedirect($defaultSite); $content = null; $posts = $post->getAllByAuthor($_SESSION['userId']); foreach ($posts as $key => $value) { $entry = file_get_contents(DOCUMENT_ROOT . '/template/posts_entry.html'); $entry = str_replace('{POSTS_EDIT_HREF}', 'Edit/' . $value['id'], $entry); $entry = str_replace('{POSTS_LINK_HREF}', 'Detail/' . $value['id'], $entry); $entry = str_replace('{POSTS_DELETE_HREF}', 'DoDeletePost/' . $value['id'], $entry); $entry = str_replace('{TXT_POSTS_TITLE}', $value['title'], $entry); $entry = str_replace('{TXT_POSTS_SUBTITLE}', $value['subTitle'], $entry); $entry = str_replace('{TXT_POSTS_MODIFIED}', $value['modifiedDate'], $entry); $content = $content . $entry; } $page = str_replace('{POST_ENTRIES}', $content, $page); break; default: } $page = str_replace('{DEFAULT_SITE}', PROTOCOL . '://' . $_SERVER['HTTP_HOST'] . PATH_OFFSET . '/' . $requestedLanguage . '/' . $availableTemplates[0], $page); $page = str_replace('{NAVIGATION}', $template->getNavigation(), $page); $page = str_replace('{PATH_OFFSET}', PATH_OFFSET, $page); $page = str_replace('{LANGUAGE}', $requestedLanguage, $page); //Replace placeholder through requestedLanguage foreach ($languageArray as $key => $value) { $page = str_replace('{' . $key . '}', $value, $page); } //return page echo $page; }
if (isset($_SESSION["name"])) { unset($_SESSION["name"]); // $isUser =1; } include 'configs/configs.php'; //$a=$_POST['ten']; //$b=$_POST['matKhau']; //echo $a.$b; $count = User::Count(); //echo $count; $count1 = implode($count); //echo $co; if (isset($_POST['ten']) && isset($_POST['matKhau'])) { $userName = $_POST['ten']; $pass = $_POST['matKhau']; $imple = User::getAll(); for ($i = 0; $i < $count1; $i++) { $DB_user = $imple[$i]->userName; $DB_pass = $imple[$i]->passWord; $DB_isAdmin = $imple[$i]->isAdmin; //echo $DB_user; //echo $DB_pass; //echo $DB_isAdmin; if ($userName == $DB_user && $pass == $DB_pass && $DB_isAdmin == 1) { $_SESSION["name"] = $userName; header('location:managerproduct.php'); } elseif ($userName == $DB_user && $pass == $DB_pass) { // session_start(); $_SESSION["name"] = $userName; header('location:index.php'); } else {