public function indexAction() { $session = new Session(); $session->add('name', 'php'); $session->add('type', 'web'); var_dump($_SESSION); $session->remove('name'); var_dump($_SESSION); // 移去所有session变量 $session->clear(); // 移去存储在服务器端的数据 $session->destroy(); // $session->close(); var_dump($_SESSION); }
/** * Método encargado de validar datos * @param Array $array Datos a validar * @return Boolean true = si los datos son validos, false = si son invalidos */ public static function validar($array) { // Validación de la clave if (isset($array['clave'])) { if (($erro = Validaciones::validarPassLogin($array["clave"])) !== true) { Session::addArray('feedback_negative', $erro); } } else { Session::add('feedback_negative', 'No se ha indicado la clave'); } // Validación del email if (isset($array['email'])) { if (($erro = Validaciones::validarEmail($array["email"])) !== true) { Session::addArray('feedback_negative', $erro); } } else { Session::add('feedback_negative', 'No se ha indicado el email'); } // Si hay errores devolvemos false if (Session::get('feedback_negative')) { return false; } // Si no hay errores devolvemos true return true; }
public static function login() { // validate the length if (strlen(Request::post('login_name')) < 2 || strlen(Request::post('login_name')) > 20 || strlen(Request::post('login_password')) < 8 || strlen(Request::post('login_password')) > 255) { // give the same feedback that's on wrong user name to not give out any data Session::add('feedback_negative', 'Error. Username or password wrong.'); return false; } // get user details $user = self::getUserData('user_name', Request::post('login_name')); // if there's no user with given name if (!$user) { Session::add('feedback_negative', 'Error. Username or password wrong.'); return false; } // check if password ok if (!password_verify(Request::post('login_password'), $user->user_password)) { // give the same feedback that's on wrong user name to not give out any data Session::add('feedback_negative', 'Error. Username or password wrong.'); return false; } // set session variables Session::set('user_id', $user->user_id); Session::set('user_name', $user->user_name); Session::set('user_permissions', $user->user_permissions); // set user as logged-in Session::set('user_logged_in', true); return true; }
public static function edit($datos) { $conn = Database::getInstance()->getDatabase(); $errores_validacion = false; if (empty($datos['id_pregunta'])) { Session::add('feedback_negative', 'No he recibido la pregunta'); $errores_validacion = true; } if (empty($datos['asunto'])) { Session::add('feedback_negative', "No he recibido el asunto de la pregunta"); $errores_validacion = true; } if (empty($datos['cuerpo'])) { Session::add('feedback_negative', "No he recibido el cuerpo de la pregunta"); $errores_validacion = true; } if ($errores_validacion) { return false; } else { $ssql = "UPDATE pregunta SET asunto=:asunto, cuerpo=:cuerpo WHERE id_pregunta=:id"; $query = $conn->prepare($ssql); $parameters = array(':asunto' => $datos["asunto"], ':cuerpo' => $datos["cuerpo"], ':id' => $datos["id_pregunta"]); $query->execute($parameters); $count = $query->rowCount(); if ($count == 1) { Session::add('feedback_positive', 'Editado con éxito, gracias!!!'); return true; } Session::add('feedback_positive', 'Actualizadas 0 casillas'); return false; } }
/** * @function appendNotesHelpRequest * @public * @static * @returns {boolean} True if successful. * @desc Adds notes from tutor input, into a record of a help request. * @param {integer} $id The unique identity for the help request. * @param {string} $noteDD The ``quick'' option of filling in notes for a help request. * @param {string} $noteText The type option of filling in notes of a help request. * @example NONE */ public static function appendNotesHelpRequest($id, $noteDD, $noteText) { $database = DatabaseFactory::getFactory()->getConnection(); $query = $database->prepare("UPDATE qscQueue.tblRequests SET notesDropDown = :note_drop_down, notesEditable = :note_text WHERE id = :id_no"); $query->execute(array(':note_drop_down' => $noteDD, ':note_text' => $noteText, ':id_no' => $id)); Session::add('feedback_positive', 'added the notes to a help request - success'); return true; }
/** * Kicks the selected user out of the system instantly by resetting the user's session. * This means, the user will be "logged out". * * @param $userId * @return bool */ private static function resetUserSession($userId) { $database = DatabaseFactory::getFactory()->getConnection(); $query = $database->prepare("UPDATE users SET session_id = :session_id WHERE user_id = :user_id LIMIT 1"); $query->execute(array(':session_id' => null, ':user_id' => $userId)); if ($query->rowCount() == 1) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_USER_SUCCESSFULLY_KICKED')); return true; } }
/** * Remove A user permission * @param $user_id * @param $removed_perm */ public static function removePerm($user_id, $removed_perm) { if (self::$removePermQuery === null) { self::$removePermQuery = DatabaseFactory::getFactory()->getConnection()->prepare("UPDATE users SET perms = :new WHERE user_id = :user_id"); } $original = UserRoleModel::getPerms($user_id); $being_removed = array_search($removed_perm, $original); unset($original[$being_removed]); self::$removePermQuery->execute(array(':new' => json_encode($original), ':user_id' => $user_id)); Session::add('feedback_positive', 'Removed that permission!'); }
public static function createShort($url) { try { $code = ShortModel::urlToShortCode($url); Session::add('feedback_positive', 'SUCCESS! SHORT URL: ' . ShortModel::$shortUrlPrefix . $code); return true; } catch (Exception $e) { // log exception and then redirect to error page. Session::add('feedback_negative', 'URL SHORTENING FAILED'); return false; } }
/** * @function setRequestDetails * @public * @static * @returns NONE * @desc * @param {string} foo Use the 'foo' param for bar. * @example NONE */ public static function setRequestDetails($recordID, $tableNo, $subj, $subSubj, $tutName) { $database = DatabaseFactory::getFactory()->getConnection(); // to do = update according to the settings needed given func's params/args. $query = $database->prepare("UPDATE users SET user_deleted = :user_deleted WHERE user_id = :user_id LIMIT 1"); $query->execute(array(':user_deleted' => $delete, ':user_id' => $userId)); // to do = determine if needed below if-statement if ($query->rowCount() == 1) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUSPENSION_DELETION_STATUS')); return true; } }
public static function menuIsActive() { if (!Session::getNested('active_menu', 'menu_id')) { // destroy session // Session::destroy(); // // create error message Session::add('feedback_errors', ErrorMessage::get('MENU_NOT_ACTIVE')); // redirect to menu selection screen header('Location: ' . URL_WITH_INDEX_FILE . 'menumanager/managemenus'); exit; } }
/** * Delete a specific note * @param int $note_id id of the note * @return bool feedback (was the note deleted properly ?) */ public static function deleteNote($note_id) { if (!$note_id) { return false; } $note = NoteQuery::create()->findPK($note_id); $note->delete(); if ($note) { return true; } // default return Session::add('feedback_negative', Text::get('FEEDBACK_NOTE_DELETION_FAILED')); return false; }
/** * Upgrades / downgrades the user's account. Currently it's just the field user_account_type in the database that * can be 1 or 2 (maybe "basic" or "premium"). Put some more complex stuff in here, maybe a pay-process or whatever * you like. * * @param $type * * @return bool */ public static function changeUserRole($type) { if (!$type) { return false; } // save new role to database if (self::saveRoleToDatabase($type)) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_TYPE_CHANGE_SUCCESSFUL')); return true; } else { Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_TYPE_CHANGE_FAILED')); return false; } }
public function addSelect() { if (empty($_POST['check_list_Material']) || empty($_POST['oeuvre_id'])) { Session::add('feedback_negative', 'Tiene que escoger una de tus obras y seleccionar algún material'); Redirect::to('dashboard/index'); } else { $arrayIdMaterial = $_POST['check_list_Material']; $oeuvre_id = $_POST['oeuvre_id']; foreach ($arrayIdMaterial as $value) { DashboardModel::addMaterialToOeuvre($oeuvre_id, $value); } Session::add('feedback_positive', 'Se ha añadido correctamente en tu obra señalada los materiales señalados'); Redirect::to('dashboard/index'); } }
/** * @function getPublicProfileOfUser * @public * @static * @returns {array} A single user profile. * @desc Gets a user's profile data, according to the given $user_id. * @param {integer} $user_id The user's id. * @example NONE */ public static function getPublicProfileOfUser($user_id) { $database = DatabaseFactory::getFactory()->getConnection(); $sql = "SELECT user_id, user_name, user_email, user_active, user_deleted FROM users WHERE user_id = :user_id LIMIT 1"; $query = $database->prepare($sql); $query->execute(array(':user_id' => $user_id)); $user = $query->fetch(); if ($query->rowCount() != 1) { Session::add('feedback_negative', Text::get('FEEDBACK_USER_DOES_NOT_EXIST')); } // all elements of array passed to Filter::XSSFilter for XSS sanitation, have a look into // application/core/Filter.php for more info on how to use. Removes (possibly bad) JavaScript etc from // the user's values array_walk_recursive($user, 'Filter::XSSFilter'); return $user; }
/** * @function setAccountDeletionStatus * @public * @static * @returns NONE * @desc * @param {string} foo Use the 'foo' param for bar. * @example NONE */ public static function setAccountDeletionStatus($softDelete, $userId) { $database = DatabaseFactory::getFactory()->getConnection(); // FYI "on" is what a checkbox delivers by default when submitted. if ($softDelete == "on") { $delete = 1; } else { $delete = 0; } $query = $database->prepare("UPDATE users SET user_deleted = :user_deleted WHERE user_id = :user_id LIMIT 1"); $query->execute(array(':user_deleted' => $delete, ':user_id' => $userId)); if ($query->rowCount() == 1) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUSPENSION_DELETION_STATUS')); return true; } }
public static function dologin($datos) { if (!$datos) { Session::add('feedback_negative', 'No tengo los datos de Login'); return false; } if (empty($datos['clave'])) { Session::add('feedback_negative', 'No se ha indicado la clave'); } if (empty($datos['email'])) { Session::add('feedback_negative', 'No se ha indicado el email'); } if (Session::get('feedback_negative')) { return false; } $datos['email'] = trim($datos['email']); if (!filter_var($datos['email'], FILTER_VALIDATE_EMAIL)) { Session::add('feedback_negative', 'El Email no es válido'); } if (strlen($datos['clave']) < 4) { Session::add('feedback_negative', 'La clave debe tener 4 o más caracteres'); } if (Session::get('feedback_negative')) { return false; } $conn = Database::getInstance()->getDatabase(); $ssql = "SELECT nombre, id_usuario, id_perfil, pass FROM usuario WHERE login=:email"; $query = $conn->prepare($ssql); $query->bindValue(':email', $datos['email'], PDO::PARAM_STR); $query->execute(); $cuantos = $query->rowCount(); if ($cuantos != 1) { Session::add('feedback_negative', 'No estás registrado'); return false; } $usuario = $query->fetch(); if ($usuario->pass != md5($datos['clave'])) { Session::add('feedback_negative', 'La clave no coincide'); return false; } Session::set('user_id', $usuario->id_usuario); Session::set('user_name', $usuario->nombre); Session::set('user_email', $datos['email']); Session::set('user_logged_in', true); return true; }
/** * Runs validation on login-form input fields * * @param array $postData * @return boolean */ public function validateLoginForm($postData) { if (empty($postData['username']) or empty($postData['password'])) { Session::add('feedback_errors', ErrorMessage::get('ERROR_FIELD_IS_EMPTY')); return false; } else { // attempt to retrieve username and password from database by selecting a row using client supplied username $dbResult = $this->retrieveCredentials($postData['username']); // a row containing client supplied username was found and the client supplied password matches the bcrypt hash of the password from the database if ($dbResult and password_verify($postData['password'], $dbResult['password'])) { // store account id to session Session::set('account_id', $dbResult['account_id']); return true; } else { Session::add('feedback_errors', ErrorMessage::get('ERROR_INVALID_CREDENTIALS')); return false; } } }
/** * @param $suspensionInDays * @param $softDelete * @param $userId * @return bool */ public static function setAccountSuspensionAndDeletionStatus($suspensionInDays, $softDelete, $userId) { if ($suspensionInDays > 0) { $suspensionTime = time() + $suspensionInDays * 60 * 60 * 24; } else { $suspensionTime = null; } // FYI "on" is what a checkbox delivers by default when submitted. Didn't know that for a long time :) $delete = $softDelete == "on" ? 1 : 0; $user = UserQuery::create()->findPk($userId); $user->setUserSuspensionTimestamp($suspensionTime); $user->setUserDeleted($delete); $user->save(); if ($user) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUSPENSION_DELETION_STATUS')); return true; } return true; }
public static function setAccountSuspensionAndDeletionStatus($suspensionInDays, $softDelete, $userId) { $database = DatabaseFactory::getFactory()->getConnection(); if ($suspensionInDays > 0) { $suspensionTime = time() + $suspensionInDays * 60 * 60 * 24; } else { $suspensionTime = null; } // FYI "on" is what a checkbox delivers by default when submitted. Didn't know that for a long time :) if ($softDelete == "on") { $delete = 1; } else { $delete = 0; } $query = $database->prepare("UPDATE users SET user_suspension_timestamp = :user_suspension_timestamp, user_deleted = :user_deleted WHERE user_id = :user_id LIMIT 1"); $query->execute(array(':user_suspension_timestamp' => $suspensionTime, ':user_deleted' => $delete, ':user_id' => $userId)); if ($query->rowCount() == 1) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUSPENSION_DELETION_STATUS')); return true; } }
/* * This example shows how new documents can be added. * * Documentation: http://docs.basex.org/wiki/Clients * * (C) BaseX Team 2005-12, BSD License */ include "BaseXClient.php"; try { // create session $session = new Session("localhost", 1984, "admin", "admin"); // create new database $session->execute("create db database"); print $session->info(); // add document $session->add("world/World.xml", "<x>Hello World!</x>"); print "<br/>" . $session->info(); // add document $session->add("Universe.xml", "<x>Hello Universe!</x>"); print "<br/>" . $session->info(); // run query on database print "<br/>" . $session->execute("xquery /"); // drop database $session->execute("drop db database"); // close session $session->close(); } catch (Exception $e) { // print exception print $e->getMessage(); }
/** * @function * @public * @static * @returns NONE * @desc * @param {string} foo Use the 'foo' param for bar. * @example NONE */ public static function verifyNewUser($user_id, $user_activation_verification_code) { $database = DatabaseFactory::getFactory()->getConnection(); $sql = "UPDATE users SET user_active = 1, user_activation_hash = NULL\n WHERE user_id = :user_id AND user_activation_hash = :user_activation_hash LIMIT 1"; $query = $database->prepare($sql); $query->execute(array(':user_id' => $user_id, ':user_activation_hash' => $user_activation_verification_code)); if ($query->rowCount() == 1) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_SUCCESSFUL')); return true; } Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_FAILED')); return false; }
public static function addArray($key, $array) { foreach ($array as $indice => $value) { Session::add($key, $value); } }
/** * Método que valida los datos a insertar en la base de datos * @param Array $array Datos a validar * @return Boolean True = si los datos son validos, False = sino lo son */ public static function validar($array) { // Si exite el campo lo validamos // Validación del nombre if (isset($array['nombre'])) { if (($erro = Validaciones::validarNombre($array["nombre"], 50)) !== true) { Session::addArray('feedback_negative', $erro); } else { if (isset($array['id'])) { // obtengo todos los nombres salvo el de la empresa // que intento editar $nombres = EmpresaModel::getNombreNoRepetido($array['id']); if (!EmpresaModel::compararNombre($nombres, $array['nombre'])) { Session::add('feedback_negative', 'La empresa ya exite'); } } else { if (EmpresaModel::getNombre($array["nombre"])) { Session::add('feedback_negative', 'La empresa ya exite'); } } } } else { Session::add('feedback_negative', 'El nombre no ha sido recicibido'); } // fin de las validaciones del nombre // Validación de la web if (isset($array['web'])) { if (($erro = Validaciones::validarUrl($array["web"])) !== true) { Session::addArray('feedback_negative', $erro); } } else { Session::add('feedback_negative', 'La web no ha sido recicibida'); } // fin de las validaciones del apellido // Validación de la descripcion if (isset($array['descripcion'])) { $array['descripcion'] = Validaciones::limpiarTextarea($array['descripcion']); if (($erro = Validaciones::validarDescripcion($array["descripcion"], 1000)) !== true) { Session::addArray('feedback_negative', $erro); } } else { Session::add('feedback_negative', 'La descripcion no ha sido recicibida'); } // Fin de la validación de la descripcion // Comprobación de de que no haya habido errores return Session::comprobarErrores(); }
/** * Edit the user's email * * @param $new_user_email * * @return bool success status */ public static function editUserEmail($new_user_email) { // email provided ? if (empty($new_user_email)) { Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_FIELD_EMPTY')); return false; } // check if new email is same like the old one if ($new_user_email == Session::get('user_email')) { Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_SAME_AS_OLD_ONE')); return false; } // user's email must be in valid email format, also checks the length // @see http://stackoverflow.com/questions/21631366/php-filter-validate-email-max-length // @see http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address if (!filter_var($new_user_email, FILTER_VALIDATE_EMAIL)) { Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN')); return false; } // strip tags, just to be sure $new_user_email = substr(strip_tags($new_user_email), 0, 254); // check if user's email already exists if (UserModel::doesEmailAlreadyExist($new_user_email)) { Session::add('feedback_negative', Text::get('FEEDBACK_USER_EMAIL_ALREADY_TAKEN')); return false; } // write to database, if successful ... // ... then write new email to session, Gravatar too (as this relies to the user's email address) if (UserModel::saveNewEmailAddress(Session::get('user_id'), $new_user_email)) { Session::set('user_email', $new_user_email); Session::set('user_gravatar_image_url', AvatarModel::getGravatarLinkByEmail($new_user_email)); Session::add('feedback_positive', Text::get('FEEDBACK_EMAIL_CHANGE_SUCCESSFUL')); return true; } Session::add('feedback_negative', Text::get('FEEDBACK_UNKNOWN_ERROR')); return false; }
public static function validateUserPassword($password, $passwordRepeat) { // check if the password is long enough if (strlen($password) < 8 || strlen($password) > 255) { Session::add('feedback_negative', 'Error. Password has to be longer than 8 characters.'); return false; } // check if the password repeat is long enough if (strlen($passwordRepeat) < 8 || strlen($passwordRepeat) > 255) { Session::add('feedback_negative', 'Error. Password has to be longer than 8 characters.'); return false; } // check if the password matches the repeat if ($password !== $passwordRepeat) { Session::add('feedback_negative', 'Error. Passwords you entered doesn\'t match.'); return false; } return true; }
/** * Validate the password submission * * @param $user_name * @param $user_password_reset_hash * @param $user_password_new * @param $user_password_repeat * * @return bool */ public static function validateNewPassword($user_name, $user_password_reset_hash, $user_password_new, $user_password_repeat) { if (empty($user_name)) { Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_FIELD_EMPTY')); return false; } else { if (empty($user_password_reset_hash)) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_RESET_TOKEN_MISSING')); return false; } else { if (empty($user_password_new) || empty($user_password_repeat)) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_FIELD_EMPTY')); return false; } else { if ($user_password_new !== $user_password_repeat) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_REPEAT_WRONG')); return false; } else { if (strlen($user_password_new) < 6) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_TOO_SHORT')); return false; } } } } } return true; }
/** * checks the email/verification code combination and set the user's activation status to true in the database * * @param int $user_id user id * @param string $user_activation_verification_code verification token * * @return bool success status */ public static function verifyNewUser($user_id, $user_activation_verification_code) { $user = UserQuery::create()->findPk($user_id); $user->setUserActive(1); $user->setUserActivationHash('NULL'); if ($user) { Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_SUCCESSFUL')); return true; } Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_FAILED')); return false; }
/** * performs the login via cookie (for DEFAULT user account, FACEBOOK-accounts are handled differently) * TODO add throttling here ? * * @param $cookie string The cookie "remember_me" * * @return bool success state */ public static function loginWithCookie($cookie) { if (!$cookie) { Session::add('feedback_negative', Text::get('FEEDBACK_COOKIE_INVALID')); return false; } // check cookie's contents, check if cookie contents belong together or token is empty list($user_id, $token, $hash) = explode(':', $cookie); if ($hash !== hash('sha256', $user_id . ':' . $token) or empty($token)) { Session::add('feedback_negative', Text::get('FEEDBACK_COOKIE_INVALID')); return false; } // get data of user that has this id and this token $result = UserModel::getUserDataByUserIdAndToken($user_id, $token); if ($result) { // successfully logged in, so we write all necessary data into the session and set "user_logged_in" to true self::setSuccessfulLoginIntoSession($result->user_id, $result->user_name, $result->user_email, $result->user_account_type); // save timestamp of this login in the database line of that user self::saveTimestampOfLoginOfUser($result->user_name); Session::add('feedback_positive', Text::get('FEEDBACK_COOKIE_LOGIN_SUCCESSFUL')); return true; } else { Session::add('feedback_negative', Text::get('FEEDBACK_COOKIE_INVALID')); return false; } }
/** * Removes the avatar image file from the filesystem * * @param $userId * @return bool */ public static function deleteAvatarImageFile($userId) { // Check if file exists if (!file_exists(Config::get('PATH_AVATARS') . $userId . ".jpg")) { Session::add("feedback_negative", Text::get("FEEDBACK_AVATAR_IMAGE_DELETE_NO_FILE")); return false; } // Delete avatar file if (!unlink(Config::get('PATH_AVATARS') . $userId . ".jpg")) { Session::add("feedback_negative", Text::get("FEEDBACK_AVATAR_IMAGE_DELETE_FAILED")); return false; } return true; }
/** * Validates current and new passwords * * @param string $user_name * @param string $user_password_current * @param string $user_password_new * @param string $user_password_repeat * * @return bool */ public static function validatePasswordChange($user_name, $user_password_current, $user_password_new, $user_password_repeat) { $database = DatabaseFactory::getFactory()->getConnection(); $sql = "SELECT user_password_hash, user_failed_logins FROM users WHERE user_name = :user_name LIMIT 1;"; $query = $database->prepare($sql); $query->execute(array(':user_name' => $user_name)); $user = $query->fetch(); if ($query->rowCount() == 1) { $user_password_hash = $user->user_password_hash; } else { Session::add('feedback_negative', Text::get('FEEDBACK_USER_DOES_NOT_EXIST')); return false; } if (!password_verify($user_password_current, $user_password_hash)) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_CURRENT_INCORRECT')); return false; } else { if (empty($user_password_new) || empty($user_password_repeat)) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_FIELD_EMPTY')); return false; } else { if ($user_password_new !== $user_password_repeat) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_REPEAT_WRONG')); return false; } else { if (strlen($user_password_new) < 6) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_TOO_SHORT')); return false; } else { if ($user_password_current == $user_password_new) { Session::add('feedback_negative', Text::get('FEEDBACK_PASSWORD_NEW_SAME_AS_CURRENT')); return false; } } } } } return true; }