/** * create the user */ function createUser() { // all data is already correct $this->userName = $this->_request->getValue("userName"); $this->userFullName = $this->_request->getValue("userFullName"); $this->userPassword = $this->_request->getValue("userPassword"); $this->userEmail = $this->_request->getValue("userEmail"); $users = new Users(); $user = new UserInfo($this->userName, $this->userPassword, $this->userEmail, "", $this->userFullName); // if user registration need email confirm, that is // user must active his account if ($this->need_confirm == true) { $user->setStatus(USER_STATUS_UNCONFIRMED); } else { $user->setStatus(USER_STATUS_ACTIVE); } $userId = $users->addUser($user); if (!$userId) { $this->_view = new SummaryView("registererror"); $this->_view->setErrorMessage($this->_locale->tr("error_adding_user")); $this->setCommonData(true); return false; } return $userId; }
public function testCreateUsersWithoutPrivileges() { $app = new Users(); $app->ds->loadMock('users', APP_ROOT . 'data/users.txt'); $this->assertTrue($app->login('*****@*****.**', '1234')); $app->ds->loadMock('users', APP_ROOT . 'data/users.txt'); $app->ds->loadMock('roles_definitions', APP_ROOT . 'data/roles_definitions.txt'); $app->ds->loadMock('profiles', APP_ROOT . 'data/profiles.txt'); $app->ds->data["profiles"]->index = "profile_id"; $this->assertEquals(3, $app->ds->recordCount()); $app->addUser('Standard', 'User', '*****@*****.**', '1234'); $app->ds->selectFrom(['users']); $this->assertEquals(4, $app->ds->recordCount()); }
public function signupAction() { if (!$this->getRequest()->isPost()) { $this->addErrorMessage("Form was not properly posted."); $this->_forward('index'); } // Retrieve the form values and its values $form = $this->getForm(); $valid = $form->isValid($_POST); $values = $form->getValues(); $username = $values['username']; $email = $values['email']; $password = $values['password']; // Validate the form itself if (!$form->isValid($_POST)) { // Failed validation; redisplay form $this->view->form = $form; $this->addErrorMessage("Your form contains some errors, please correct them and submit this form again"); return $this->_forward('register'); } // Register user $users = new Users(); $user = $users->addUser($username, $password, $email); // Add some default widgets to the user $widgets = new Widgets(array(Stuffpress_Db_Table::USER => $user->id)); $widgets->addWidget('search'); $widgets->addWidget('rsslink'); $widgets->addWidget('links'); $widgets->addWidget('lastcomments'); $widgets->addWidget('archives'); $widgets->addWidget('logo'); // Add some default properties $properties = new Properties(array(Stuffpress_Db_Properties::KEY => $user->id)); $properties->setProperty('theme', 'clouds'); $properties->setProperty('title', ucfirst($username)); $properties->setProperty('subtitle', "my life online"); // Add the storytlr data source StuffpressModel::forUser($user->id); // Add default pages $pages = new Pages(array(Stuffpress_Db_Table::USER => $user->id)); //$pages->addPage('dashboard', 'Home'); $pages->addPage('lifestream', 'Stream'); $pages->addPage('stories', 'Stories'); // Send the user a verification email Stuffpress_Emails::sendWelcomeEmail($email, $username, $password, $user->token); // Done ! $this->view->username = $username; $this->view->email = $email; $this->render('success'); }
public function resultAction() { $post = $this->request->getPost(); $email = $post["email"]; $username = $post["username"]; $password = $post["password"]; $error = array(); $userModel = new Users(); $result = $userModel->addUser(array($username, $password, $email)); if (false == $result) { $errorFlg = 1; $this->view->assign('errorFlg', $errorFlg); } else { $this->view->assign('username', $username); } }
function addUser() { $db = getDB(); $app = Slim::getInstance(); $userName = $app->request()->params('user_name'); $nameFirst = $app->request()->params('name_first'); $nameLast = $app->request()->params('name_last'); // used for degugging if desired. $startTime = time(); $results = Users::addUser($db, $userName, $nameFirst, $nameLast); if (!$results) { return; } // User ID is private so don't send it back to the client unset($results->user_id); sendResponse($results, $startTime); }
function perform() { // fetch the validated data $this->_userName = Textfilter::filterAllHTML($this->_request->getValue("userName")); $this->_userPassword = $this->_request->getValue("newUserPassword"); $this->_userEmail = Textfilter::filterAllHTML($this->_request->getValue("userEmail")); $this->_userFullName = Textfilter::filterAllHTML($this->_request->getValue("userFullName")); $this->_userStatus = $this->_request->getValue("userStatus"); $this->_userBlog = $this->_request->getValue("userBlog"); // now that we have validated the data, we can proceed to create the user, making // sure that it doesn't already exists $users = new Users(); $userInfo = $users->userExists($this->_userName); if ($userInfo) { $this->_form->setFieldValidationStatus("userName", false); $this->_view = new AdminAddUserView($this->_blogInfo); $this->setCommonData(true); return false; } // otherwise, we can create a new one $user = new UserInfo($this->_userName, $this->_userPassword, $this->_userEmail, "", $this->_userFullName, 0, $this->_properties); $user->setStatus($this->_userStatus); $this->notifyEvent(EVENT_PRE_USER_ADD, array("user" => &$user)); $newUserId = $users->addUser($user); if (!$newUserId) { $this->_view = new AdminAddUserView($this->_blogInfo); $this->_form->setFieldValidationStatus("userName", false); $this->setCommonData(true); return false; } // if the userBlog parameter is different than 0, we have to add a relationship // between that user and the blog if ($this->_userBlog > 0) { $permissions = new UserPermissions(); $result = $permissions->grantPermission($newUserId, $this->_userBlog, PERMISSION_BLOG_USER); } $this->notifyEvent(EVENT_POST_USER_ADD, array("user" => &$user)); $this->_view = new AdminSiteUsersListView($this->_blogInfo); $this->_view->setSuccessMessage($this->_locale->pr("user_added_ok", $user->getUsername())); $this->setCommonData(); return true; }
/** * Performs an authentication attempt * * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed * @return Zend_Auth_Result */ public function authenticate() { $config = new Zend_Config_Ini('../config/zportal.ini', 'mail'); $mailConfig = array('auth' => 'login', 'username' => $this->name, 'password' => $this->password); $login = new Zend_Mail_Protocol_Smtp_Auth_Login($config->mail->get('server'), null, $mailConfig); $login->connect(); try { $login->helo("localhost"); } catch (Exception $e) { // unauth user $result = Zend_Auth_Result::FAILURE; $identity = $this->name; $message = 'Authentication failed. Please check your login details or call system admin.'; return new Zend_Auth_Result($result, $identity, array($message)); } // create result array $users = new Users(); $email = strtolower($this->name . "@zend.com"); $user = $users->getByEmail($email); // if first time visit if (!$user) { // add record to users $users->addUser(array('email' => $email, 'role' => 'member')); $user = $users->getByEmail($email); // send welcome page $bodyHtml = 'Dear User<br>Welcome to ZPortal.<br>'; $config = new Zend_Config_Ini('../config/zportal.ini', 'mail'); $transport = new Zend_Mail_Transport_Smtp($config->mail->get('server'), $mailConfig); $mail = new Zend_Mail(); $mail->setBodyText("See html attachment"); $mail->setBodyHtml($bodyHtml, 'UTF-8', Zend_Mime::ENCODING_BASE64); $mail->setFrom('*****@*****.**', 'ZPortal'); $mail->addTo($email, $email); $mail->setSubject('Welcome to ZPortal'); $mail->send($transport); } $result = Zend_Auth_Result::SUCCESS; $identity = $user; $message = ''; return new Zend_Auth_Result($result, $identity, array($message)); }
function _addUser($data, $_debug) { if ($data["username"] == NULL) { $data["username"] = "******"; } if ($data["password"] == NULL) { $data["password"] = "******"; } if ($data["email"] == NULL) { $data["email"] = "email address"; } if ($data["about"] == NULL) { $data["about"] = "NA"; } if ($data["fullname"] == NULL) { $data["fullname"] = "Full Name"; } $users = new Users(); if ($data["id"]) { $user = $users->getUserInfoFromId($data["id"]); if ($user) { if ($user->getUsername() == $data["username"]) { if ($_debug) { print "--- user " . $data["username"] . " already exists, at the proper id (" . $data["id"] . "). next entry.<br />\n\r"; } return $data["id"]; } } } $user = $users->getUserInfoFromUsername($data["username"]); if ($user) { if ($user->getUsername() == $data["username"]) { $user_id = $user->getId(); } } else { $user = new UserInfo($data["username"], $data["password"], $data["email"], $data["about"], $data["fullname"], ""); $user_id = $users->addUser($user); $this->_stats["users"]["write"]++; } if ($_debug) { print "--- user " . $data["username"] . " has id number: " . $user_id . "<br />\n\r"; } if (!($user_id == $data["id"])) { // remap blogs foreach ($this->_t_container["blogs"] as $blog => $val) { if ($val["owner"] == $data["id"] || $val["owner"] == NULL) { $this->_container["blogs"][$blog]["owner"] = $user_id; if ($_debug) { print "--- --- remapping blog entry #" . $blog . " to proper user id<br />\n\r"; } } } // remap posts foreach ($this->_t_container["posts"] as $post => $val) { if ($val["user_id"] == $data["id"] || $val["user_id"] == NULL) { $this->_container["posts"][$post]["user_id"] = $user_id; if ($_debug) { print "--- --- remapping post entry #" . $post . " to proper user id<br />\n\r"; } } } } return $user_id; }
/** ******************************************************************** * When a new client is searching for a public transcoder, it can call * http://discovery.open-mediakit.org/public?application=<application>&version=<version> * to obtain a json-list of the currently active public transcoders. * then it choose one of them and call the subscribe api call * on this transcoder to subscribe to it and get an account there. * the parameters are : * email: the email address of the subscriber (*it will be verified by sending an email*) * url: url of the api root of the client. will be used to call * app_key: the api Key the client want me to use when contacting him, <=32 characters * application: client application that request an account * version: version of the client application * non-mandatory parameters: * lang: language of the client, default to en_US (for discussion & email verification text) * @return array the list of available settings on this transcoder. if the subscription was successfull. */ public function app_subscribeAction() { if (!defined("PUBLIC_TRANSCODER") || !PUBLIC_TRANSCODER) { $this->api->apiError(API_ERROR_NOTPUBLIC, _("This server is not a public transcoder, please use another one")); } // anonymous api call $this->me=$this->api->checkCallerIdentity(); $this->api->enforceLimits(); // for each params, tell its name, and its type and if it is mandatory $this->params = $this->api->filterParams(array("email" => array("string", true), "url" => array("string", true), "app_key" => array("string", true), "application" => array("string", true), "version" => array("string", true), "lang" => array("string", false, "en_US"))); // TODO : use gettext to set the LOCALES according to the lang set by the caller. require_once MODULES . "/users/libs/users.php"; $this->api->logApiCall("app_subscribe"); // Check for application / version blacklist $this->api->allowApplication($this->params['application'], $this->params['version']); // Create an account $this->params['pass'] = Users::randomPass(); $this->params['enabled'] = 1; $this->params['validated'] = 0; $this->params['admin'] = 0; $this->params['clientkey'] = $this->params['app_key']; unset($this->params['app_key']); $uid = Users::addUser($this->params); if (!$uid) { $this->api->apiError(API_ERROR_CREATEACCOUNT, _("An error happened when creating the account. Please retry later.")); } $me = Users::get($uid); // Send a validation email to the user Users::sendValidationEmail($uid); $s = $this->api->getAllSettings(); foreach ($s as $setting) { $settings[$setting["id"]] = array("id" => $setting["id"], "type" => $setting["type"], "slug" => $setting["slug"], "name" => $setting["name"], "technical" => $setting["technical"], "extension" => $setting["extension"], "recommend" => $setting["recommend"], "size_43" => $setting["size_43"], "size_169" => $setting["size_169"], "cardinality" => $setting["cardinality"]); } $this->api->returnValue(array("apikey" => $me["apikey"], "settings" => $settings)); }
public function testCreateUsersWithoutPrivileges() { $app = new Users(); $data = new data_source_mysqli(); $data->config = self::$config; $data->connect(""); $app->ds = $data; $data->index_field = "user_id"; $this->assertTrue($app->login('*****@*****.**', '1234')); $app->ds->data["profiles"]->index = "profile_id"; $app->ds->selectAllFrom("profiles"); $this->assertEquals(3, $app->ds->recordCount()); $app->addUser('Standard', 'User', '*****@*****.**', '1234'); $app->ds->selectAllFrom("users"); $this->assertEquals(4, $app->ds->recordCount()); }
function perform() { $this->_userName = $this->_request->getValue("userName"); $this->_userPassword = $this->_request->getValue("userPassword"); $this->_confirmPassword = $this->_request->getValue("userPasswordCheck"); $this->_userEmail = $this->_request->getValue("userEmail"); $this->_userFullName = $this->_request->getValue("userFullName"); $db = connectDb(); if (!$db) { $this->_view = new WizardView("step3"); $this->_view->setErrorMessage("There was an error connecting to the database. Please check your settings."); $this->setCommonData(); return false; } if ($this->_confirmPassword != $this->_userPassword) { $this->_view = new WizardView("step3"); $this->_form->setFieldValidationStatus("userPasswordCheck", false); $this->setCommonData(true); return false; } $dbPrefix = Db::getPrefix(); $users = new Users(); $user = new UserInfo($this->_userName, $this->_userPassword, $this->_userEmail, "", $this->_userFullName); $userId = $users->addUser($user); if (!$userId) { $this->_view = new WizardView("step3"); $message = "There was an error adding the user. Make sure that the user does not already exist in the database (" . $users->DbError() . ")"; $this->_view->setErrorMessage($message); $this->setCommonData(); return false; } // we also have to execute the code to give administrator privileges to this user $query = "INSERT INTO {$dbPrefix}users_permissions(user_id,blog_id,permission_id) VALUES( {$userId}, 0, 1 );"; $db->Execute($query); $this->_view = new Wizardview("step4"); $this->_view->setValue("ownerid", $userId); $this->_view->setValue("siteLocales", Locales::getLocales()); $this->_view->setValue("defaultLocale", Locales::getDefaultLocale()); $ts = new TemplateSets(); $this->_view->setValue("siteTemplates", $ts->getGlobalTemplateSets()); $this->setCommonData(); return true; }
function reg($args = null) { $answer = array(); //ответ $answer["success"]["fields"] = array(); //массив удачно заполненных полей /*$answer["error"]["msg"] = print_r($_POST,true); return $answer;*/ //проводим валидацию логина $login = null; if (isset($_POST["login"])) { $login = $_POST["login"]; } $error = Users::validateLogin($login, true, Users::LOGIN_TYPE_EMAIL); if ($error !== Users::ERROR_NOT) { //в случае ошибки возвращаем текст ошибки $answer["error"]["field"] = "login"; $answer["error"]["msg"] = Users::errorMsg($error); return $answer; } array_push($answer["success"]["fields"], "login"); //проводим валидацию пароля $pwd_strong = 0; $pwd1 = null; $pwd2 = null; if (isset($_POST["pwd"])) { $pwd1 = $_POST["pwd"]; } if (isset($_POST["pwd2"])) { $pwd2 = $_POST["pwd2"]; } $error = Users::validatePassword($pwd1, $pwd2, $pwd_strong); if ($error !== Users::ERROR_NOT) { //в случае ошибки возвращаем текст ошибки //если пароли отличаются или второй пароль пустой, указываем фокус на второй пароль if ($error === Users::ERROR_PWD_DIFFERENT || $error === Users::ERROR_PWD_EMPTY && !empty($pwd1)) { $answer["error"]["field"] = "pwd2"; array_push($answer["success"]["fields"], "pwd"); } else { $answer["error"]["field"] = "pwd"; } $answer["error"]["msg"] = Users::errorMsg($error); return $answer; } array_push($answer["success"]["fields"], "pwd"); array_push($answer["success"]["fields"], "pwd2"); //проверяем капчу //считываем ее из поста и сессии $captcha = null; if (isset($_POST["captcha"])) { $captcha = $_POST["captcha"]; } $session_captcha = null; if (isset($_SESSION["captcha"])) { $session_captcha = $_SESSION["captcha"]; } if (empty($captcha) || empty($session_captcha)) { //в случае ошибки возвращаем текст ошибки $answer["error"]["field"] = "captcha"; $answer["error"]["msg"] = "Текст с картинки не указан"; return $answer; } //сверяем капчу if (strcmp(strtolower($captcha), strtolower($session_captcha)) != 0) { //в случае ошибки возвращаем текст ошибки $answer["error"]["field"] = "captcha"; $answer["error"]["msg"] = "Неверный текст с картинки"; return $answer; } array_push($answer["success"]["fields"], "captcha"); //если нужна была только валидация, выходим if (!isset($_POST["submit"]) || !$_POST["submit"]) { return $answer; } //очищаем курчу в сессии, чтобы не прошла второй раз unset($_SESSION["captcha"]); $agent = false; $company = ""; $city = ""; $type = 1; if (isset($_POST["agent"]) && $_POST["agent"] == true) { if (isset($_POST["city"])) { $city = $_POST["city"]; } if (isset($_POST["company"])) { $company = $_POST["company"]; } $type = 2; } //добавляем пользователя $error = Users::addUser($login, $_POST["pwd"], $_POST["pwd2"], $type, $company, $city, Users::LOGIN_TYPE_EMAIL); if ($error !== Users::ERROR_NOT) { $answer["error"]["field"] = "submit"; $answer["error"]["msg"] = Users::errorMsg($error); return $answer; } Users::getUser(array("login" => $login, "auth" => true)); //возвращаем код успешной операции array_push($answer["success"]["fields"], "submit"); $answer["success"]["msg"] = "Поздравляю, вы успешно зарегистрировались"; //выводим ответ return $answer; }
public function personAction($reception = null, $item_id = null) { $this->view->setVar("TopMenuSelected", 'work'); $this->view->setVar("MenuSelected", 'persons'); $this->view->setVar("MenuItemActive", $reception); $messages = array(); if (!empty($reception)) { $view = $reception; switch ($reception) { case 'add': $this->view->setVar("CountriesAll", References::getCountries()); break; case 'preview-cache-station': if ($this->request->isPost()) { if ((bool) $this->request->getPost('add')) { View::addMessages($this, [References::addPersonNew($this->request->getPost('full_name'), $this->request->getPost('address'), $this->request->getPost('country_id'), 3, $this->request->getPost('code'), 1, $this->request->getPost('phone'), Users::getStationId($this))]); } } View::addMessages($this, [array('class' => 'alert-info', 'text' => "<p>Перечень записей Адресной книги кэшированных только для этой станции.</p>")]); $this->view->setVar("PersonsCacheAll", References::getPersonsCache(Users::getStationId($this))); break; case 'preview-cache': if ($this->request->isPost()) { } View::addMessages($this, [array('class' => 'alert-info', 'text' => "<p>Перечень часто использующихся записей Адресной книги всех станций.</p>")]); $this->view->setVar("PersonsCacheAll", References::getPersonsHot()); break; case 'preview': if ($this->request->isPost()) { //$messages[] = Users::addUser($this->request->getPost()); //$messages[] = Users::deleteUser($this->request->getPost('id')); } View::addMessages($this, [array('class' => 'alert-info', 'text' => "<p>Полный перечень записей Адресной книги всех станций.</p>")]); $this->view->setVar("PersonsCacheAll", References::getPersonsAll()); break; case 'edit': if (empty($item_id)) { if ($this->request->isPost()) { $this->response->redirect('/administration/user/edit/' . $this->request->getPost('user_id'), '/'); } $messages[] = array('class' => 'alert-info', 'text' => "<p><b>Выберите</b> из выпадающего списка <b>профиль пользователя</b>, который нужно изменить.</p>"); $this->view->setVar("UsersAll", Users::getUsers()); } else { if ($this->request->isPost()) { $messages[] = Users::setUser($this->request->getPost()); } $this->view->setVar("User", Users::getUsers($item_id)); $this->view->setVar("StationsAll", Stations::getStations()); $this->view->setVar("RolesAll", Roles::getRoles()); $this->view->setVar("LanguagesAll", References::getLanguages()); $this->view->setVar("CurrencyAll", References::getCurrency()); $this->view->setVar("Units1", References::getUnits(NULL, array(1))['units']); $this->view->setVar("Units2", References::getUnits(NULL, array(3))['units']); $this->view->setVar("Units3", References::getUnits(NULL, array(4))['units']); } break; case 'settings': if ($this->request->isPost()) { $messages[] = Users::addUser($this->request->getPost()); //$messages[] = Users::deleteUser($this->request->getPost('id')); } $this->view->setVar("UsersAll", Users::getUsers()); break; } $this->view->pick('/administration/' . "person_" . $view); } //$this->view->setVar("messages", $messages); }
<?php require_once "../config.inc.php"; session_start(); $first = $_REQUEST['first']; $last = $_REQUEST['last']; $email = $_REQUEST['email']; $creator_id = $_REQUEST['creator_id']; $user_type_id = $_REQUEST['user_type_id']; $active = 0; print_r($_FILES); print_r($_REQUEST); $file = $_FILES['file']['name']; $temp_file = $_FILES['file']['tmp_name']; $token = bin2hex(openssl_random_pseudo_bytes(3)); $data['creator_id'] = $creator_id; $data['user_type_id'] = $user_type_id; $data['first'] = $first; $data['last'] = $last; $data['email'] = $email; $data['active'] = $active; $data['avatar'] = $file; $data['hasher'] = $token; $db = Database::obtain(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE); $db->connect(); $u = new Users('member', BASE_DOMAIN); $data['password'] = $u->setPassword($token); //setPassword($password) $update = $u->addUser($data); $upload_dir = '/avatars/'; $upload_file = $u->uploader($file, $temp_file, $upload_dir);
break; case 'adduser': if (isset($_GET['action'])) { include_once 'views/adduser.php'; } else { if ($_POST['submit'] == "Cancel") { // Check if the user clicked cancel, if so don't submit header('location: ' . $loc); exit; } // Include database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); $users = new Users($db); $dreams = new Dreams($db); $d = $dreams->getDreams(); $user = $users->addUser($_POST); $_SESSION['loggedin'] = $user['num_users'] == 1 ? 0 : NULL; $_SESSION['username'] = $_POST['username']; $message = msgUserCreated($_POST['username']); include_once 'views/list.php'; exit; } break; case 'login': if (isset($_GET['action'])) { include_once 'views/login.php'; } else { // Include database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); $users = new Users($db); $dreams = new Dreams($db);
#!/usr/bin/env php <?php require_once __DIR__ . '/../lib.php'; if (empty($argv[1]) || empty($argv[2])) { echo "login .. pass\n"; exit; } $informations = array('login' => $argv[1], 'pass' => $argv[2], 'admin' => true, 'enabled' => true); Users::addUser($informations);