PHP Method User::findByUsername, codiad Code Examples

This page contains top rated real world PHP examples of method User::findByUsername from package codiad extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: LoginForm.php Project: humanized/yii2-user-module
0
 /**
  * Finds user by [[username]]
  *
  * @return User|null
  */
 protected function getUser()
 {
     if ($this->_user === null) {
         $this->_user = User::findByUsername($this->username);
     }
     return $this->_user;
 }
Example #2
Show file File: document_controller.php Project: ratbird/hope
0
 public function before_filter(&$action, &$args)
 {
     parent::before_filter($action, $args);
     // Lock context to user id
     $this->owner = $GLOBALS['user'];
     $this->context_id = $this->owner->id;
     $this->full_access = true;
     if (Config::get()->PERSONALDOCUMENT_OPEN_ACCESS) {
         $username = Request::username('username', $GLOBALS['user']->username);
         $user = User::findByUsername($username);
         if ($user && $user->id !== $GLOBALS['user']->id) {
             $this->owner = $user;
             $this->context_id = $user->id;
             $this->full_access = Config::get()->PERSONALDOCUMENT_OPEN_ACCESS_ROOT_PRIVILEDGED && $GLOBALS['user']->perms === 'root';
             URLHelper::bindLinkParam('username', $username);
         }
     }
     $this->limit = $GLOBALS['user']->cfg->PERSONAL_FILES_ENTRIES_PER_PAGE ?: Config::get()->ENTRIES_PER_PAGE;
     $this->userConfig = DocUsergroupConfig::getUserConfig($GLOBALS['user']->id);
     if ($this->userConfig['area_close'] == 1) {
         $this->redirect('document/closed/index');
     }
     if (Request::isPost()) {
         CSRFProtection::verifySecurityToken();
     }
     if (($ticket = Request::get('studip-ticket')) && !check_ticket($ticket)) {
         $message = _('Bei der Verarbeitung Ihrer Anfrage ist ein Fehler aufgetreten.') . "\n" . _('Bitte versuchen Sie es erneut.');
         PageLayout::postMessage(MessageBox::error($message));
         $this->redirect('document/files/index');
     }
 }
Example #3
Show file File: LoginForm.php Project: absol3112/sonneboutique
0
 /**
  * Finds user by [[username]]
  *
  * @return User|null
  */
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByUsername($this->username);
     }
     return $this->_user;
 }
Example #4
Show file File: LoginForm.php Project: dvizh/yii2-users-module
0
 /**
  * Finds user by username.
  *
  * @return User|null User instance
  */
 protected function getUser()
 {
     if ($this->_user === null) {
         $scope = $this->scenario === 'admin' ? ['admin', 'active'] : 'active';
         $this->_user = User::findByUsername($this->username, $scope);
     }
     return $this->_user;
 }
Example #5
Show file File: User.php Project: hamaco/phwittr-on-xoops
0
 /**
  * @test
  */
 public function updatePassword()
 {
     $user1 = User::findByUsername("test1");
     $this->eq(md5("test1"), $user1->password);
     $user1->updatePassword("foo");
     $user1 = new User($user1->id);
     $this->eq(md5("foo"), $user1->password);
     $user1->updatePassword("test1");
 }
Example #6
Show file File: registerctrl.php Project: samdubey/ads2
0
 public static function check()
 {
     return function ($req, $res) {
         $user = User::findByUsername($req->user);
         if ($user) {
             $res->code(200);
         } else {
             $res->code(404);
         }
     };
 }
Example #7
Show file File: ForgotPasswordForm.php Project: kalyabin/comitka
0
 /**
  * Validate existence of user and save it's model.
  *
  * @param string $attribute
  * @param array $params
  */
 public function validateUser($attribute, $params = [])
 {
     if (!$this->hasErrors()) {
         $res = User::findByUsername($this->{$attribute});
         if (!$res instanceof User) {
             $this->addError($attribute, \Yii::t('user', 'User not found'));
         } else {
             $this->user = $res;
         }
     }
 }
Example #8
Show file File: auth_extension.php Project: masayukiando/googlemap-search_ActionScript3.0
0
 function initialize(&$controller)
 {
     $this->controller = $controller;
     if ($controller->Auth->user()) {
         // already authenticated
         return;
     }
     $cookie = $controller->Cookie->read(AuthExtensionComponent::cookie_name);
     if (!$cookie) {
         return;
     }
     $all_fields = isset($cookie['username']) && isset($cookie['hash1']) && isset($cookie['time']) && isset($cookie['hash']);
     // all fields present?
     if (!$all_fields) {
         $this->logout();
         return;
     }
     // global hash correct?
     if (Security::hash($cookie['username'] . $cookie['hash1'] . $cookie['time']) !== $cookie['hash']) {
         $this->logout();
         return;
     }
     if (time() - $cookie['time'] > AuthExtensionComponent::cookie_expire_seconds) {
         $this->logout();
         return;
     }
     // find the user
     App::import('Model', 'User');
     $User = new User();
     $u = $User->findByUsername($cookie['username']);
     if (!$u) {
         $this->logout();
         return;
     }
     if (Security::hash($u['User']['password'] . 'another random string', null, true) === $cookie['hash1']) {
         // user confirmed
         $login_array = array('User' => array('username' => $u['User']['username'], 'password' => $u['User']['password']));
         $u = null;
         if ($controller->Auth->login($login_array)) {
             //  Clear auth message, just in case we use it.
             $controller->Session->del('Message.auth');
             $controller->redirect($controller->Auth->redirect());
         } else {
             // Delete invalid Cookie
             $this->logout();
         }
     } else {
         $u = null;
     }
 }
Example #9
Show file File: online.php Project: ratbird/hope
0
 /**
  * Controller for all buddy related action.
  *
  * The following actions are supported:
  * - "add" to add a user to the current user's buddy list
  * - "remove" to remove a user from the current user's buddy list
  *
  * @param String $action The action to be executed
  */
 public function buddy_action($action = 'add')
 {
     $username = Request::username('username');
     if ($action === 'add' && $username !== null) {
         if (Contact::import(array('owner_id' => User::findCurrent()->id, 'user_id' => User::findByUsername($username)->id))->store()) {
             PageLayout::postMessage(MessageBox::success(_('Der Benutzer wurde zu Ihren Kontakten hinzugefügt.')));
         }
     } elseif ($action === 'remove' && $username !== null) {
         $contact = Contact::find(array(User::findCurrent()->id, User::findByUsername($username)->id));
         if ($contact && $contact->delete()) {
             PageLayout::postMessage(MessageBox::success(_('Der Benutzer gehört nicht mehr zu Ihren Kontakten.')));
         }
     }
     $this->redirect('online');
 }
Example #10
Show file File: Status.php Project: hamaco/phwittr-on-xoops
0
 public static function post($userId, $comment)
 {
     $status = new self();
     $comment = self::normalizeComment($comment);
     if (preg_match('/^@(\\w{1,20})/', $comment, $matches) === 1) {
         $targetUser = User::findByUsername($matches[1]);
         if ($targetUser->isActive()) {
             $status->reply_user_id = $targetUser->uid;
         }
     }
     $status->user_id = $userId;
     $status->comment = $comment;
     $status->created_at = now();
     $status->save();
     return $status;
 }
Example #11
Show file File: settings.php Project: ratbird/hope
0
 /**
  * Sets up the controller
  *
  * @param String $action Which action shall be invoked
  * @param Array $args Arguments passed to the action method
  */
 public function before_filter(&$action, &$args)
 {
     // Abwärtskompatibilität, erst ab 1.1 bekannt
     if (!isset($GLOBALS['ALLOW_CHANGE_NAME'])) {
         $GLOBALS['ALLOW_CHANGE_NAME'] = TRUE;
     }
     parent::before_filter($action, $args);
     // Ensure user is logged in
     $GLOBALS['auth']->login_if($action !== 'logout' && $GLOBALS['auth']->auth['uid'] === 'nobody');
     // extract username
     $username = Request::username('username', $GLOBALS['user']->username);
     $user = User::findByUsername($username);
     if (!$GLOBALS['perm']->have_profile_perm('user', $user->user_id)) {
         $username = $GLOBALS['user']->username;
     } else {
         $username = $user->username;
         URLHelper::addLinkParam('username', $username);
     }
     $this->about = new about($username, null);
     $this->about->get_user_details();
     if (!$this->about->check) {
         $this->reportErrorWithDetails(_('Zugriff verweigert.'), array(_("Wahrscheinlich ist Ihre Session abgelaufen. Bitte " . "nutzen Sie in diesem Fall den untenstehenden Link, " . "um zurück zur Anmeldung zu gelangen.\n\n" . "Eine andere Ursache kann der Versuch des Zugriffs " . "auf Userdaten, die Sie nicht bearbeiten dürfen, sein. " . "Nutzen Sie den untenstehenden Link, um zurück auf " . "die Startseite zu gelangen."), sprintf(_('%s Hier%s geht es wieder zur Anmeldung beziehungsweise Startseite.'), '<a href="index.php">', '</a>')));
         $this->render_nothing();
         return;
     }
     $this->user = User::findByUsername($username);
     $this->restricted = $GLOBALS['perm']->get_profile_perm($this->user->user_id) !== 'user' && $username !== $GLOBALS['user']->username;
     $this->config = UserConfig::get($this->user->user_id);
     $this->validator = new email_validation_class();
     # Klasse zum Ueberpruefen der Eingaben
     $this->validator->timeout = 10;
     // Default auth plugin to standard
     if (!$this->user->auth_plugin) {
         $this->user->auth_plugin = 'standard';
     }
     PageLayout::addSqueezePackage('settings');
     // Show info message if user is not on his own profile
     if ($username != $GLOBALS['user']->username) {
         $message = sprintf(_('Daten von: %s %s (%s), Status: %s'), htmlReady($this->user->Vorname), htmlReady($this->user->Nachname), $username, $this->user->perms);
         $this->reportInfo($message);
     }
     Sidebar::get()->setImage('sidebar/person-sidebar.png');
     $this->set_layout($GLOBALS['template_factory']->open('layouts/base'));
 }
Example #12
Show file File: class.LoginController.php Project: JoffreyO/hackademic
0
 public function go()
 {
     $this->setViewTemplate('admin_login.tpl');
     $this->addPageTitle('Log in');
     if ($this->isLoggedIn()) {
         header('Location: ' . SOURCE_ROOT_PATH . "admin/pages/dashboard.php");
     } else {
         if (isset($_POST['submit']) && $_POST['submit'] == 'Login' && isset($_POST['username']) && isset($_POST['pwd'])) {
             if ($_POST['username'] == '' || $_POST['pwd'] == '') {
                 if ($_POST['username'] == '') {
                     $this->addErrorMessage("Username must not be empty");
                     return $this->generateView();
                 } else {
                     $this->addErrorMessage("Password must not be empty");
                     return $this->generateView();
                 }
             } else {
                 $session = new Session();
                 $username = $_POST['username'];
                 $this->addToView('username', $username);
                 $user = User::findByUsername($username);
                 if (!$user) {
                     $this->addErrorMessage("Incorrect username");
                     return $this->generateView();
                 } elseif (!$session->pwdCheck($_POST['pwd'], $user->password)) {
                     $this->addErrorMessage("Incorrect password");
                     return $this->generateView();
                 } elseif (!$user->type) {
                     $this->addErrorMessage("You are not an administrator");
                     return $this->generateView();
                 } else {
                     // this sets variables in the session
                     $session->completeLogin($user);
                     header('Location: ' . SOURCE_ROOT_PATH . "admin/pages/login.php");
                 }
             }
         } else {
             $this->addPageTitle('Log in');
             return $this->generateView();
         }
     }
 }
Example #13
Show file File: User.php Project: pvpalvk/kyberkoulutus2
0
 /**
  * @param $username string
  * @param $password string
  * @param $firstName string
  * @param $lastName string
  * @return mixed
  */
 public static function register($username, $password, $firstName, $lastName, $accessLevel = 0, $premade = 0, $email = "", $phone = "")
 {
     if (User::findByUsername($username)) {
         return null;
     }
     $user = new User();
     $user->username = $username;
     $user->salt = Auth::generatePasswordSalt();
     $user->password = Auth::hashPassword($password, $user->salt);
     $user->firstName = $firstName;
     $user->lastName = $lastName;
     $user->email = $email;
     $user->phone = $phone;
     $user->accessLevel = $accessLevel;
     $user->premade = $premade;
     $user->createDate = Database::now();
     if (!$user->save()) {
         return null;
     }
     return $user;
 }
Example #14
Show file File: class.LoginController.php Project: JoffreyO/hackademic
0
 public function go()
 {
     $this->setViewTemplate('landingpage.tpl');
     $this->addPageTitle('Log in');
     if ($this->isLoggedIn()) {
         $controller = new LandingPageController();
         return $controller->go();
     } else {
         if (isset($_POST['submit']) && $_POST['submit'] == 'Login' && isset($_POST['username']) && isset($_POST['pwd'])) {
             if ($_POST['username'] == '' || $_POST['pwd'] == '') {
                 if ($_POST['username'] == '') {
                     $this->addErrorMessage("Username must not be empty");
                     return $this->generateView();
                 } else {
                     $this->addErrorMessage("Password must not be empty");
                     return $this->generateView();
                 }
             } else {
                 $session = new Session();
                 $username = $_POST['username'];
                 $this->addToView('username', $username);
                 $user = User::findByUsername($username);
                 if (!$user) {
                     header('Location:' . SOURCE_ROOT_PATH . "pages/mainlogin.php?msg=username");
                     //return $this->generateView();
                 } elseif (!$session->pwdCheck($_POST['pwd'], $user->password)) {
                     header('Location:' . SOURCE_ROOT_PATH . "pages/mainlogin.php?msg=password");
                     return $this->generateView();
                 } else {
                     // this sets variables in the session
                     $session->completeLogin($user);
                     header('Location:' . SOURCE_ROOT_PATH . "pages/home.php");
                 }
             }
         } else {
             $this->addPageTitle('Log in');
             return $this->generateView();
         }
     }
 }
Example #15
Show file File: Auth.php Project: ShawnRyanRocks/adlister.dev
0
 public static function attempt($email, $password)
 {
     // $log = new Log('users.login');
     $_SESSION['LOGGED_IN_USER'] = null;
     $_SESSION['LOGGED_IN'] = false;
     $user = User::findByUsername($email);
     $hashedPassword = $user->password;
     if (password_verify($password, $hashedPassword)) {
         //echo 'loged in';
         $_SESSION['LOGGED_IN_USER'] = $user;
         $_SESSION['LOGGED_IN'] = true;
         // $log->logInfo("User {$user->username} loggin in");
         // unset($log);
         return true;
     } else {
         // $log->logError("{$email} tryed to log in");
         // unset($log);
         // header("Location: /index.php");
         // die();
         return false;
     }
 }
Example #16
Show file File: SlugRoute.php Project: riverans/manage-expenses
0
 function parse($url)
 {
     $params = parent::parse($url);
     if (isset($params['slug'])) {
         $username = $params['slug'];
         App::import("Component", "Users.ControllerList");
         $contList = new ControllerListComponent(new ComponentCollection());
         $conts = $contList->getControllers();
         unset($conts[-2]);
         unset($conts[-1]);
         $conts = array_map('strtolower', $conts);
         $usernameTmp = strtolower(str_replace(' ', '', ucwords(str_replace('_', ' ', $username))));
         if (!in_array($usernameTmp, $conts)) {
             $plugins = App::objects('plugins');
             $plugins = array_map('strtolower', $plugins);
             if (in_array($usernameTmp, $plugins)) {
                 return false;
             }
             $customRoutes = Router::$routes;
             $usernameTmp = '/' . $username;
             foreach ($customRoutes as $customRoute) {
                 if (strpos(strtolower($customRoute->template), strtolower($usernameTmp)) !== false) {
                     return false;
                 }
             }
             App::import("Model", "Users.User");
             $userModel = new User();
             $isUser = $userModel->findByUsername($params['slug']);
             if ($isUser) {
                 $params['pass'][0] = $params['slug'];
                 return $params;
             }
         }
         return false;
     }
     return false;
 }
Example #17
Show file File: Signup.php Project: bolivarez9193/Brandons_Repo
0
// case 1: the signup fields are valid
// outcome: save the validated user object to the db, start a session and push
//          the user into session, and render the home.php view
// case 2: the signup fields are not valid
// outcome: create a $signup_user with the full_name and username set and
//          appropriate error messages, also an empty $login_user object,
//          and render the loginform.php view
// find their session or create a new one
session_start();
// copy the form fields in to a new User object
$full_name = $_POST["full_name"];
$username = $_POST["username"];
$password = $_POST["password"];
$password2 = $_POST["password2"];
$signup_user = new User();
$checkUser = User::findByUsername($username, $dbh);
// validate the object, if success, save and render home view
if ($full_name != null && $username != null && $password != null && $password2 != null && $signup_user->validatePassword($password, $password2) && !$checkUser) {
    $signup_user->full_name = $full_name;
    $signup_user->username = $username;
    $signup_user->saveWithPassword($dbh, $password);
    $user = $signup_user;
    $_SESSION["user"] = $user;
    include_once "views/home.php";
    // if failed, errors should already be set, go back to loginform view
    // you'll also need an empty login user model for the page
} else {
    if ($full_name == null) {
        $signup_user->errors = array();
        $signup_user->errors['full_name'] = 'You need to enter a name.';
        $login_user = new User();
Example #18
Show file File: TestControl.php Project: elifah93/Internet-Programming
0
<?php

require_once 'models/DB.php';
require_once 'models/User.php';
// test insert
/*$user = new User();
$user->username = "testguy";
$user->full_name = "Test Guy";
$user->saveWithPassword($dbh, "bogusbogusbogus");
echo "User added, ID is: ".$user->id."<br/>";*/
// test login
$user = new User();
$user->findByUsername("testguy", $dbh);
echo "Got user " . $user->full_name . " (" . $user->username . "), id: " . $user->id . "<br/>";
echo "Login with correct password...<br/>";
if ($user->login("bogusbogusbogus")) {
    echo "Success!<br/>";
} else {
    echo "Failure!<br/>";
}
echo "Login with incorrect password...<br/>";
if ($user->login("notmypassword")) {
    echo "Success!<br/>";
} else {
    echo "Failure!<br/>";
}
Example #19
Show file File: StudipAuthAbstract.class.php Project: ratbird/hope
0
 /**
  * method to retrieve the Stud.IP user id to a given username
  *
  *
  * @access   private
  * @param    string  the username
  * @return   User  the Stud.IP or false if an error occurs
  */
 function getStudipUser($username)
 {
     $user = User::findByUsername($username);
     if ($user) {
         $auth_plugin = $user->auth_plugin;
         if ($auth_plugin === null) {
             $this->error_msg = _("Dies ist ein vorläufiger Benutzer.") . "<br>";
             return false;
         }
         if ($auth_plugin != $this->plugin_name) {
             $this->error_msg = sprintf(_("Dieser Benutzername wird bereits über %s authentifiziert!"), $auth_plugin) . "<br>";
             return false;
         }
         return $user;
     }
     $new_user = new User();
     $new_user->username = $username;
     $new_user->perms = 'autor';
     $new_user->auth_plugin = $this->plugin_name;
     $new_user->preferred_language = $_SESSION['_language'];
     if ($new_user->store()) {
         $this->is_new_user = true;
         return $new_user;
     }
 }
Example #20
Show file File: ProfileDeletionCept.php Project: DavBfr/BlogMVC
0
<?php

use Codeception\Util\Fixtures;
/** @type \Codeception\Scenario $scenario */
$scenario->groups('front', 'user-management');
\Yii::app()->fixtureManager->prepare();
$I = new TestGuy($scenario);
$I->wantTo('Delete my account');
$I->expectTo('Lose ability to sign in under my regular account and all my posts');
$login = Fixtures::get('data:users[0]:login');
$password = Fixtures::get('data:users[0]:password');
$I->amOnPage(\AuthorFeedPage::route(1));
// confirming that test landed on required page
$I->see($login, \AuthorFeedPage::$postSelector);
$I->amOnPage(\LoginPage::$url);
$I->submitForm(\LoginPage::$formSelector, array(\LoginPage::$loginField => $login, \LoginPage::$passwordField => $password));
$I->amOnPage(\SuicideBoothPage::$url);
$I->click(\SuicideBoothPage::$benderButtonXPath);
$I->seeCurrentUrlEquals('/');
$I->amOnPage(\LoginPage::$url);
$I->submitForm(\LoginPage::$formSelector, array(\LoginPage::$loginField => $login, \LoginPage::$passwordField => $password));
$I->see('auth.login.fail');
$I->amOnPage(\AuthorFeedPage::route(1));
$I->see('pageTitle.site.error', \AuthorFeedPage::$pageHeaderSelector);
$I->seeResponseCodeIs(404);
$h = fopen(\Yii::getPathOfAlias('application.runtime.login'), 'a');
fwrite($h, $login . PHP_EOL);
fclose($h);
$I->assertNull(\User::findByUsername($login, false));
$I->assertEmpty(\Post::model()->with(array('author' => array('condition' => 'author.username = :login', 'params' => array(':login' => $login))))->findAll());
Example #21
Show file File: contact.php Project: ratbird/hope
0
 function remove_action($group = null)
 {
     $contact = Contact::find(array(User::findCurrent()->id, User::findByUsername(Request::username('user'))->id));
     if ($contact) {
         if ($group) {
             $contact->group_assignments->unsetBy('statusgruppe_id', $group);
             if ($contact->store()) {
                 PageLayout::postMessage(MessageBox::success(_("Der Kontakt wurde aus der Gruppe entfernt.")));
             }
         } else {
             if ($contact->delete()) {
                 PageLayout::postMessage(MessageBox::success(_("Der Kontakt wurde entfernt.")));
             }
         }
     }
     $this->redirect('contact/index/' . $group);
 }
Example #22
Show file File: User.php Project: elifah93/Internet-Programming
0
 function validateWithPassword($password1, $password2, $dbh)
 {
     $tmp = new User();
     if ($this->full_name == "") {
         $this->errors["full_name"] = "Full name cannot be blank";
     }
     if ($this->username == "") {
         $this->errors["username"] = "Username cannot be blank";
     } else {
         if ($tmp->findByUsername($this->username, $dbh)) {
             $this->errors["username"] = "Someone is already using that username";
         }
     }
     if ($password1 == "" || $password2 == "") {
         $this->errors["password"] = "Password fields cannot be blank";
     } else {
         if ($password1 != $password2) {
             $this->errors["password"] = "Passwords do not match.";
         }
     }
     if (isset($this->errors)) {
         return false;
     } else {
         return true;
     }
 }
Example #23
Show file File: messaging.inc.php Project: ratbird/hope
0
 /**
  *
  * @param $message
  * @param $rec_uname
  * @param $user_id
  * @param $time
  * @param $tmp_message_id
  * @param $set_deleted
  * @param $signature
  * @param $subject
  * @param $force_email
  * @param $priority
  */
 function insert_message($message, $rec_uname, $user_id = '', $time = '', $tmp_message_id = '', $set_deleted = '', $signature = '', $subject = '', $force_email = '', $priority = 'normal', $tags = null)
 {
     global $user;
     $my_messaging_settings = UserConfig::get($user->id)->MESSAGING_SETTINGS;
     // wenn kein subject uebergeben
     $subject = $subject ?: _('Ohne Betreff');
     $email_request = $this->send_as_email ?: $my_messaging_settings['send_as_email'];
     // wenn keine zeit uebergeben
     $time = $time ?: time();
     // wenn keine id uebergeben
     $tmp_message_id = $tmp_message_id ?: md5(uniqid('321losgehtes', true));
     // wenn keine user_id uebergeben
     $user_id = $user_id ?: $user->id;
     # send message now
     if ($user_id != '____%system%____') {
         // real-user message
         $snd_user_id = $user_id;
         $set_deleted = $set_deleted ?: $my_messaging_settings['save_snd'] != '1';
         // don't save sms in outbox
     } else {
         // system-message
         $set_deleted = '1';
         // system-signatur
         $snd_user_id = '____%system%____';
         setTempLanguage();
         $message .= $this->sig_string;
         $message .= _('Diese Nachricht wurde automatisch vom Stud.IP-System generiert. Sie können darauf nicht antworten.');
         restoreLanguage();
     }
     // Setzen der Message-ID als Range_ID für angehängte Dateien
     if (isset($this->provisonal_attachment_id) && $GLOBALS['ENABLE_EMAIL_ATTACHMENTS']) {
         $query = "UPDATE dokumente SET range_id = ?, description = '' WHERE dokument_id = ?";
         $statement = DBManager::get()->prepare($query);
         foreach (get_message_attachments($this->provisonal_attachment_id, true) as $attachment) {
             $statement->execute(array($tmp_message_id, $attachment['dokument_id']));
         }
     }
     // insert message
     $query = "INSERT INTO message (message_id, autor_id, subject, message, priority, mkdate)\n                  VALUES (?, ?, ?, ?, ?, UNIX_TIMESTAMP())";
     $statement = DBManager::get()->prepare($query);
     $statement->execute(array($tmp_message_id, $snd_user_id, $subject, $message, $priority));
     // insert snd
     $insert_tags = DBManager::get()->prepare("\n            INSERT IGNORE INTO message_tags\n            SET message_id = :message_id,\n                user_id = :user_id,\n                tag = :tag,\n                chdate = UNIX_TIMESTAMP(),\n                mkdate = UNIX_TIMESTAMP()\n        ");
     $query = "INSERT INTO message_user (message_id, user_id, snd_rec, deleted, mkdate)\n                  VALUES (?, ?, 'snd', ?, UNIX_TIMESTAMP())";
     $statement = DBManager::get()->prepare($query);
     $statement->execute(array($tmp_message_id, $snd_user_id, $set_deleted ? 1 : 0));
     if ($tags) {
         is_array($tags) || ($tags = explode(" ", (string) $tags));
         foreach ($tags as $tag) {
             $insert_tags->execute(array('message_id' => $tmp_message_id, 'user_id' => $snd_user_id, 'tag' => strtolower($tag)));
         }
     }
     // heben wir kein array bekommen, machen wir einfach eins ...
     if (!is_array($rec_uname)) {
         $rec_uname = array($rec_uname);
     }
     // wir bastelen ein neues array, das die user_id statt des user_name enthaelt
     $rec_id = array();
     foreach ($rec_uname as $one) {
         $rec_id[] = User::findByUsername($one)->user_id;
     }
     $rec_id = array_filter($rec_id);
     // wir gehen das eben erstellt array durch und schauen, ob irgendwer was weiterleiten moechte.
     // diese user_id schreiben wir in ein tempraeres array
     foreach ($rec_id as $one) {
         $tmp_forward_id = User::find($this->get_forward_id($one))->user_id;
         if ($tmp_forward_id) {
             $rec_id[] = $tmp_forward_id;
         }
     }
     // wir mergen die eben erstellten arrays und entfernen doppelte eintraege
     $rec_id = array_unique($rec_id);
     // hier gehen wir alle empfaenger durch, schreiben das in die db und schicken eine mail
     $query = "INSERT INTO message_user (message_id, user_id, snd_rec, mkdate)\n                   VALUES (?, ?, 'rec', UNIX_TIMESTAMP())";
     $insert = DBManager::get()->prepare($query);
     $snd_name = $user_id != '____%system%____' ? User::find($user_id)->getFullName() . ' (' . User::find($user_id)->username . ')' : 'Stud.IP-System';
     foreach ($rec_id as $one) {
         $insert->execute(array($tmp_message_id, $one));
         if ($GLOBALS['MESSAGING_FORWARD_AS_EMAIL']) {
             // mail to original receiver
             $mailstatus_original = $this->user_wants_email($one);
             if ($mailstatus_original == 2 || $mailstatus_original == 3 && $email_request == 1 || $force_email) {
                 $this->sendingEmail($one, $snd_user_id, $message, $subject, $tmp_message_id);
             }
         }
         if ($tags) {
             foreach ($tags as $tag) {
                 $insert_tags->execute(array('message_id' => $tmp_message_id, 'user_id' => $one, 'tag' => strtolower($tag)));
             }
         }
     }
     // Obtain all users that should receive a notification
     $user_ids = $rec_id;
     if (is_object($GLOBALS['user'])) {
         $user_ids = array_diff($user_ids, array($GLOBALS['user']->id));
     }
     // Create notifications
     PersonalNotifications::add($user_ids, URLHelper::getUrl("dispatch.php/messages/read/{$tmp_message_id}", array('cid' => null)), sprintf(_('Sie haben eine Nachricht von %s erhalten!'), $snd_name), 'message_' . $tmp_message_id, Icon::create('mail', 'clickable')->asImagePath(80));
     return sizeof($rec_id);
 }
Example #24
Show file File: ProfileNavigation.php Project: ratbird/hope
0
 /**
  * Initialize the subnavigation of this item. This method
  * is called once before the first item is added or removed.
  */
 public function initSubNavigation()
 {
     global $user, $perm;
     parent::initSubNavigation();
     $username = Request::username('username', $user->username);
     $current_user = $username == $user->username ? $user : User::findByUsername($username);
     // profile
     $navigation = new Navigation(_('Profil'), 'dispatch.php/profile/index');
     $this->addSubNavigation('index', $navigation);
     if ($perm->have_profile_perm('user', $current_user->user_id)) {
         // avatar
         $navigation = new Navigation(_('Bild'), 'dispatch.php/settings/avatar');
         $this->addSubNavigation('avatar', $navigation);
         // profile data
         $navigation = new Navigation(_('Nutzerdaten'));
         $navigation->addSubNavigation('profile', new Navigation(_('Grunddaten'), 'dispatch.php/settings/account'));
         if (($perm->get_profile_perm($current_user->user_id) == 'user' || $perm->have_perm('root') && Config::get()->ALLOW_ADMIN_USERACCESS) && !StudipAuthAbstract::CheckField('auth_user_md5.password', $current_user->auth_plugin) && !LockRules::check($current_user->user_id, 'password')) {
             $navigation->addSubNavigation('password', new Navigation(_('Passwort ändern'), 'dispatch.php/settings/password'));
         }
         $navigation->addSubNavigation('details', new Navigation(_('Weitere Daten'), 'dispatch.php/settings/details'));
         if (!in_array($current_user->perms, words('user admin root'))) {
             $navigation->addSubNavigation('studies', new Navigation(_('Studiendaten'), 'dispatch.php/settings/studies'));
         }
         if ($current_user->perms != 'root') {
             if (count(UserDomain::getUserDomains())) {
                 $navigation->addSubNavigation('userdomains', new Navigation(_('Nutzerdomänen'), 'dispatch.php/settings/userdomains'));
             }
             if ($perm->is_staff_member($current_user->user_id)) {
                 $navigation->addSubNavigation('statusgruppen', new Navigation(_('Einrichtungsdaten'), 'dispatch.php/settings/statusgruppen'));
             }
         }
         $this->addSubNavigation('edit', $navigation);
         if ($perm->have_perm('autor')) {
             $navigation = new Navigation(_('Einstellungen'));
             $navigation->addSubNavigation('general', new Navigation(_('Allgemeines'), 'dispatch.php/settings/general'));
             $navigation->addSubNavigation('privacy', new Navigation(_('Privatsphäre'), 'dispatch.php/settings/privacy'));
             $navigation->addSubNavigation('messaging', new Navigation(_('Nachrichten'), 'dispatch.php/settings/messaging'));
             if (get_config('CALENDAR_ENABLE')) {
                 $navigation->addSubNavigation('calendar_new', new Navigation(_('Terminkalender'), 'dispatch.php/settings/calendar'));
             }
             if (!$perm->have_perm('admin') and get_config('MAIL_NOTIFICATION_ENABLE')) {
                 $navigation->addSubNavigation('notification', new Navigation(_('Benachrichtigung'), 'dispatch.php/settings/notification'));
             }
             if (isDefaultDeputyActivated() && $perm->get_perm() == 'dozent') {
                 $navigation->addSubNavigation('deputies', new Navigation(_('Standardvertretung'), 'dispatch.php/settings/deputies'));
             }
             if (Config::Get()->API_ENABLED) {
                 $navigation->addSubNavigation('api', new Navigation(_('API-Berechtigungen'), 'dispatch.php/api/authorizations'));
             }
             $this->addSubNavigation('settings', $navigation);
         }
         // user defined sections
         $navigation = new Navigation(_('Kategorien'), 'dispatch.php/settings/categories');
         $this->addSubNavigation('categories', $navigation);
     }
     // user documents page
     if (Config::get()->PERSONALDOCUMENT_ENABLE && ($perm->have_profile_perm('user', $current_user->user_id) || Config::get()->PERSONALDOCUMENT_OPEN_ACCESS)) {
         $title = _('Meine Dateien');
         if (Config::get()->PERSONALDOCUMENT_OPEN_ACCESS && $current_user->id !== $user->id) {
             $title = _('Dateibereich');
         }
         $navigation = new Navigation($title, 'dispatch.php/document/files');
         $this->addSubNavigation('files', $navigation);
     }
 }
Example #25
Show file File: Login.php Project: bolivarez9193/Brandons_Repo
0
<?php

require_once "models/DB.php";
require_once "models/User.php";
// attempt to login
// case 1: the username/password match what's in the db
// outcome: inflate $user with that username, start a session and push the user
//          into session as userid, and render the home.php view
// case 2: the username/password don't match what's in the db
// outcome: the $login_user should have an appropriate error set, create an
//          empty $signup_user object, and render the loginform.php view
// find their session or create a new one
session_start();
// try logging in
$username = $_POST["username"];
$password = $_POST["password"];
$login_user = User::findByUsername($username, $dbh);
if ($login_user && $login_user->login($password)) {
    // on success, show the home view and get out of here
    $_SESSION["user"] = $login_user;
    $user = $login_user;
    require_once "views/home.php";
} else {
    // on failure, errors should be set in the User model so that GetError works
    // you'll also need an empty signup user model for the page
    $signup_user = new User();
    include_once "views/loginform.php";
}
Example #26
Show file File: login.php Project: googlecode-mirror/timovy2007
0
 /**
  * Obnovi data o pouzivatelovi z databazy
  * 
  * Tuto funckiu treba zavolat, ak sa manipulovalo s pristupovymi alebo
  * osobnymi udajmi o pouzivatelovi, aby sa preniesli do session premennej	 *
  */
 public function refresh()
 {
     // musi byt prihlaseny
     if (!$this->isLogged()) {
         return false;
     }
     // jedna sa o momentalneho pouzivatela
     $username = $this->username();
     // ziskaj info o pouzivatelovi
     $User = new User();
     $someone = $User->findByUsername($username);
     // uzivatel neexistuje, bol vymazany z databazby
     if (empty($someone['User']['username'])) {
         return false;
     }
     // ziskaj prava
     $permissions = array('permissions' => $this->clearances($username));
     // ziskaj IP adresu
     $ip = $this->ip();
     $someone['User']['ip'] = $ip;
     // zapis do session
     $_SESSION['User'] = array_merge($someone['User'], $permissions);
     return true;
 }
Example #27
Show file File: Login.php Project: elifah93/Internet-Programming
0
<?php

require_once "models/DB.php";
require_once "models/User.php";
// attempt to login
// case 1: the username/password match what's in the db
// outcome: inflate $user with that username, start a session and push the user
//          into session as user, and render the home.php view
// case 2: the username/password don't match what's in the db
// outcome: the $login_user should have an appropriate error set, create an
//          empty $signup_user object, and render the loginform.php view
// find their session or create a new one
session_start();
$login_user = new User();
// try logging in
if ($_POST && $login_user->findByUsername($_POST["username"], $dbh)) {
    // on success, show the home view and get out of here
    if ($login_user->login($_POST["password"])) {
        $user = $login_user;
        $_SESSION["userId"] = $user->id;
        include_once "views/home.php";
    } else {
        $login_user->errors['login'] = "Invalid username or password.";
        $signup_user = new User();
        include_once "views/loginform.php";
    }
} else {
    $login_user->errors['login'] = "Invalid username or password.";
    $signup_user = new User();
    include_once "views/loginform.php";
}
Example #28
Show file File: banner.php Project: ratbird/hope
0
 /**
  * Create a new banner
  */
 public function new_action()
 {
     // add new banner input
     if (Request::submitted('anlegen')) {
         $description = Request::get('description');
         $alttext = Request::get('alttext');
         $target_type = Request::option('target_type');
         //add the right target
         if ($target_type == 'url') {
             $target = Request::get('target');
         } else {
             if ($target_type == 'inst') {
                 $target = Request::option('institut');
             } else {
                 if ($target_type == 'user') {
                     $target = Request::username('user');
                 } else {
                     if ($target_type == 'seminar') {
                         $target = Request::option('seminar');
                     } else {
                         $target = Request::get('target');
                     }
                 }
             }
         }
         $priority = Request::int('priority');
         $errors = array();
         $upload = $_FILES['imgfile'];
         if (!$upload['name']) {
             $errors[] = _('Es wurde kein Bild ausgewählt.');
         } else {
             $banner_path = $this->bannerupload($upload['tmp_name'], $upload['size'], $upload['name'], $errors);
         }
         $startDate = explode('.', Request::get('start_date'));
         if (($x = $this->valid_date(Request::int('start_hour'), Request::int('start_minute'), $startDate[0], $startDate[1], $startDate[2])) == -1) {
             $errors[] = _('Bitte geben Sie einen gültiges Startdatum ein.');
         } else {
             $startdate = $x;
         }
         $endDate = explode('.', Request::get('end_date'));
         if (($x = $this->valid_date(Request::int('end_hour'), Request::int('end_minute'), $endDate[0], $endDate[1], $endDate[2])) == -1) {
             $errors[] = _('Bitte geben Sie einen gültiges Enddatum ein.');
         } else {
             $enddate = $x;
         }
         if (!$target && $target_type != 'none') {
             $errors[] = _('Es wurde kein Verweisziel angegeben.');
         } else {
             switch ($target_type) {
                 case 'url':
                     if (!preg_match('~^(https?|ftp)://~i', $target)) {
                         $errors[] = _('Das Verweisziel muss eine gültige URL sein (incl. http://).');
                     }
                     break;
                 case 'inst':
                     if (Institute::find($target) === null) {
                         $errors[] = _('Die angegebene Einrichtung existiert nicht. ' . 'Bitte geben Sie eine gültige Einrichtungs-ID ein.');
                     }
                     break;
                 case 'user':
                     if (User::findByUsername($target) === null) {
                         $errors[] = _('Der angegebene Benutzername existiert nicht.');
                     }
                     break;
                 case 'seminar':
                     try {
                         Seminar::getInstance($target);
                     } catch (Exception $e) {
                         $errors[] = _('Die angegebene Veranstaltung existiert nicht. ' . 'Bitte geben Sie eine gültige Veranstaltungs-ID ein.');
                     }
                     break;
                 case 'none':
                     $target = '';
                     break;
             }
         }
         if (count($errors) > 0) {
             PageLayout::postMessage(MessageBox::error(_('Es sind folgende Fehler aufgetreten:'), $errors));
         } else {
             $banner = new Banner();
             $banner->banner_path = $banner_path;
             $banner->description = $description;
             $banner->alttext = $alttext;
             $banner->target_type = $target_type;
             $banner->target = $target;
             $banner->startdate = $startdate;
             $banner->enddate = $enddate;
             $banner->priority = $priority;
             $banner->store();
             PageLayout::postMessage(MessageBox::success(_('Der Banner wurde erfolgreich gespeichert.')));
             $this->redirect('admin/banner');
         }
     }
 }
Example #29
Show file File: Comment.php Project: DavBfr/BlogMVC
0
 /**
  * Returns comment author.
  *
  * @missingOptimization Searching through lots of users by unindexed text
  * field is a bad idea.
  *
  * @return \User Current comment author (if he or she is registered).
  * @since 0.1.0
  */
 public function getAuthor()
 {
     if (!$this->username || $this->username[0] !== '@') {
         return false;
     } else {
         if ($this->author === null) {
             $username = substr($this->username, 1);
             $this->author = \User::findByUsername($username);
         }
         return $this->author;
     }
 }
Example #30
Show file File: index.php Project: samdubey/ads2
0
            echo $e->getMessage();
        }
    } else {
        $tpl = Template::load('user_index.html');
        $data = array("title" => "Adsell", "username" => $request->session('username'));
        echo $tpl->render($data);
    }
}
respond('/login', function ($req, $res) {
    if ($req->method('post')) {
        $username = $req->param('username');
        $password = $req->param('password');
        $auth = User::validateUserPass($username, $password);
        if ($auth) {
            # code...
            $user = User::findByUsername($username);
            $res->session('id', $user->id);
            $res->session('username', $user->username);
            $res->redirect('/');
        } else {
            $res->redirect('/login');
        }
    } else {
        $tpl = Template::load('login.html');
        echo $tpl->render(array());
    }
});
respond('/logout', function ($req, $res) {
    $res->session('id', null);
    $res->session('username', null);
    $res->session('admin', null);