Ejemplo n.º 1
0
 public function testSetLocation()
 {
     $em = $this->getService('doctrine')->getEntityManager();
     $user = new User();
     $user->setEmail('*****@*****.**');
     $user->setFirstName('first name');
     $user->setLastName('last name');
     $this->persist($user);
     $this->flush();
     $location = $this->getService('doctrine')->getRepository('Entity\\Location')->findOneBy(array());
     $session = $this->createSession();
     $session->set('user.id', $user->getId());
     $client = $this->createClient($session);
     $client->loadPage('/');
     $this->assertEquals('/login/location', $client->getUrl(), 'invalid url');
     $form = $client->getElement('form');
     $fields = $form->getFields();
     $this->assertCount(1, $fields, 'Invalid number fields');
     $fields[0]->setData('');
     $form->submit();
     $form = $client->getElement('form');
     $fields = $form->getFields();
     $this->assertEquals('/login/location', $client->getUrl(), 'Invalid url form after submited form');
     $this->assertEquals('Value can not empty', $fields[0]->getParent()->getElement('label')->getText(), 'Invalid error message for location');
     $fields[0]->setData($location->getId());
     $form->submit();
     $this->assertEquals('/', $client->getUrl(), 'Invalid url form after submited form');
     $em->clear();
     $users = $em->getRepository('Entity\\User')->findAll();
     $this->assertCount(2, $users, 'Invalid number users');
     $user = $users[1];
     $this->assertEquals($location->getId(), $user->getLocation()->getId(), 'Invalid location');
     $client->loadPage('/login/location');
     $this->assertEquals('/', $client->getUrl(), 'Invalid url after set location');
 }
Ejemplo n.º 2
0
 /**
  * Static Functions
  */
 public static function processExternal($provider, $user_profile, User $user = null)
 {
     $external = self::getRepository()->findOneBy(array('provider' => $provider, 'external_id' => $user_profile->identifier));
     // Locate a user account to associate.
     if ($user instanceof User) {
         // No additional processing.
     } elseif ($external instanceof self && $external->user instanceof User) {
         $user = $external->user;
     } elseif (!empty($user_profile->email)) {
         $user = User::getRepository()->findOneBy(array('email' => $user_profile->email));
         if (!$user instanceof User) {
             $user = new User();
             $user->email = $user_profile->email;
             $user->name = $user_profile->displayName;
             $user->avatar_url = $user_profile->photoURL;
             $user->generateRandomPassword();
             $user->save();
         }
     } else {
         // Not enough information to auto-create account; throw exception.
         throw new \PVL\Exception\AccountNotLinked();
     }
     // Create new external record (if none exists)
     if (!$external instanceof self) {
         // Create new external account and associate with the specified user.
         $external = new self();
         $external->provider = $provider;
         $external->external_id = $user_profile->identifier;
     }
     $external->user = $user;
     $external->name = $user_profile->displayName;
     $external->avatar_url = $user_profile->photoURL;
     $external->save();
     return $user;
 }
/**
 * Fonction ajoutant en BDD le nouveau membre inscrit et lui envoyant un message contenant son code d'activation
 * d'inscription.
 */
function addDB()
{
    $userToAdd = new User(array("UserName" => $_POST['userName'], "email" => $_POST['email'], "Mdp" => $_POST['mdp']));
    $code_aleatoire = genererCode();
    $adresseAdmin = "*****@*****.**";
    $to = $userToAdd->getEmail();
    $sujet = "Confirmation de l'inscription";
    $entete = "From:" . $adresseAdmin . "\r\n";
    $entete .= "Content-Type: text/html; charset=utf-8\r\n";
    $message = "Nous confirmons que vous êtes officiellement inscrit sur le site EveryDayIdea <br>\n\t\t\t\t\t\t\t\t\tVotre login est : " . $userToAdd->getUserName() . " <br>\n\t\t\t\t\t\t\t\t\tVotre email est : " . $userToAdd->getEmail() . " <br>\n\t\t\t\t\t\t\t\t\tVotre lien d'activation est : <a href='http://www.everydayidea.be/Page/activationInscription.page.php?code=" . $code_aleatoire . "'>Cliquez ici !</a>";
    mail($to, $sujet, $message, $entete);
    /** @var $um : un nouvel user qui va être ajouté à la BDD
        J'ajoute le nouvel user à la BDD*/
    $um = new UserManager(connexionDb());
    $um->addUser($userToAdd);
    /**
     * Ici j'ai besoin de savoir quel est le user id du nouveau membre ajouté pour pouvoir le mettre dans l'ajout du code d'activation de cet user
     * Donc je vais le rechercher en base de donnée où il vient d'être ajouté
     */
    $user = $um->getUserByUserName($userToAdd->getUserName());
    $userid = $user->getId();
    $um->setUserDroit($user, 4);
    /**
     * J'ajoute le nouveau code d'activation à la BDD
     */
    $am = new ActivationManager(connexionDb());
    $activation = new Activation(array("code" => $code_aleatoire, "id_user" => $userid, "libelle" => "Inscription"));
    $am->addActivation($activation);
}
Ejemplo n.º 4
0
/**
 * @author Sebastien Piraux <*****@*****.**> old code
 * @author Julio Montoya 2013
 * @desc Record information for login event when an user identifies himself with username & password
 */
function event_login(\Entity\User $user)
{
    $userId = $user->getUserId();
    $TABLETRACK_LOGIN = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
    $reallyNow = api_get_utc_datetime();
    $sql = "INSERT INTO " . $TABLETRACK_LOGIN . " (login_user_id, login_ip, login_date, logout_date) VALUES\n                ('" . $userId . "',\n        \t\t'" . Database::escape_string(api_get_real_ip()) . "',\n        \t\t'" . $reallyNow . "',\n        \t\t'" . $reallyNow . "'\n        \t\t)";
    Database::query($sql);
    $roles = $user->getRolesObj();
    // auto subscribe
    /** @var \Entity\Role $role  */
    foreach ($roles as $role) {
        $role = $role->getRole();
        $userStatusParsed = 'student';
        switch ($role) {
            case 'ROLE_SESSION_MANAGER':
                $userStatusParsed = 'sessionadmin';
                break;
            case 'ROLE_TEACHER':
                $userStatusParsed = 'teacher';
                break;
            case 'ROLE_RRHH':
                $userStatusParsed = 'DRH';
                break;
        }
        $autoSubscribe = api_get_setting($userStatusParsed . '_autosubscribe');
        if ($autoSubscribe) {
            $autoSubscribe = explode('|', $autoSubscribe);
            foreach ($autoSubscribe as $code) {
                if (CourseManager::course_exists($code)) {
                    CourseManager::subscribe_user($userId, $code);
                }
            }
        }
    }
}
Ejemplo n.º 5
0
 /**
  * Find one entry in DB by given id
  *
  * @param  int $id
  * @return \Entity\User
  * @since  1.0
  */
 public function findOneById($id)
 {
     $userData = $this->em->query('SELECT * FROM users WHERE id = ' . $id . ';')->fetch();
     $newUser = new UserEntity();
     $newUser->setPostRepository($this->em->getPostRepository());
     return $this->registerUserEntity($id, $this->mapper->populate($userData, $newUser));
 }
Ejemplo n.º 6
0
 /**
  * Convert an object user to an associative array
  *
  * @param \Entity\User $entity The object user
  *
  * @return array The associative array
  */
 protected function convertObjectToArray($entity)
 {
     $data = array();
     $data['id'] = $entity->getId();
     $data['password'] = $entity->getPassword();
     $data['username'] = $entity->getUsername();
     return $data;
 }
Ejemplo n.º 7
0
 function create_user($row)
 {
     $user = new User();
     $user->setUsername($row['username']);
     $user->setPassword($row['password']);
     $user->setRole($row['role']);
     return $user;
 }
/**
 * Fonction vérifiant le password de l'admin.
 * @return bool : true si le password est bon, sinon false.
 */
function checkAdminPwd()
{
    $userSession = getSessionUser();
    $userMdpTest = new User(array("Mdp" => $_POST['mdpAdmin']));
    $userMdpTest->setHashMdp();
    if ($userSession->getDroit()[0]->getLibelle() and $userSession->getMdp() == $userMdpTest->getMdp()) {
        return true;
    }
    return false;
}
Ejemplo n.º 9
0
 /**
  * Find entrie in DB by given user
  *
  * @param  \Entity\User $user
  * @return array of \Entity\Post
  * @since  1.0
  */
 public function findByUser($user)
 {
     $postsData = $this->em->query('SELECT * FROM posts WHERE user_id = ' . $user->getId() . ';')->fetchAll();
     $posts = array();
     foreach ($postsData as $postData) {
         $newPost = new PostEntity();
         $posts[] = $this->mapper->populate($postData, $newPost);
     }
     return $posts;
 }
Ejemplo n.º 10
0
 /**
  * dev:deploy
  */
 public function deployAction()
 {
     if (FA_APPLICATION_ENV == "production") {
         die('Not in a development environment!');
     }
     // Create an admin user.
     $user = new User();
     $user->fromArray(array('username' => 'admin', 'password' => 'admin', 'fullname' => 'Local Administrator', 'seeadultart' => Upload::RATING_ADULT, 'birthday' => date('Y-m-d', strtotime('-21 years')), 'regbdate' => date('Y-m-d', strtotime('-21 years')), 'email' => '*****@*****.**', 'regemail' => '*****@*****.**', 'access_level' => User::LEGACY_ACL_ADMINISTRATOR));
     $user->save();
     $this->printLn('Local administrator account ("admin" / "admin") created!');
 }
 /**
  * Fonction permettant de retrouver un groupe en fonction de l'user qui est son leader.
  * @param User $user : utilisateur ayant le lead du groupe.
  * @return Groupe : la classe groupe concernée.
  */
 public function getGroupeByLeader(User $user)
 {
     $resultats = $this->db->prepare("SELECT * FROM groupe WHERE id_leader = :id");
     $resultats->execute(array(":id" => $user->getId()));
     if ($tabGroupe = $resultats->fetch(PDO::FETCH_ASSOC)) {
         $groupe = new Groupe($tabGroupe);
     } else {
         $groupe = new Groupe(array());
     }
     return $groupe;
 }
Ejemplo n.º 12
0
 /**
  * Rajoute à l'activité de l'utilisateur les notifications suivantes
  * @param array $notif_list liste des ids
  * @param \Entity\User $user
  */
 public function add_new_notif_visited($notif_list, $user)
 {
     $nb = count($notif_list);
     if ($nb > 0) {
         $activity = $user->getActivity();
         if (is_null($activity)) {
             $activity = new \Entity\UserActivity();
             $user->setActivity($activity);
             ci()->doctrine->em->persist($activity);
             ci()->doctrine->em->flush();
             //$activity->setUser($user);
         }
         $activity->add_notification_visited($notif_list);
         ci()->doctrine->em->flush();
     }
     return $nb;
 }
Ejemplo n.º 13
0
 /**
  * Configure enviorment.
  */
 protected function setUp()
 {
     $this->executeCommand('migrate:downgrade');
     $this->executeCommand('migrate:update');
     $em = $this->getService('doctrine')->getEntityManager();
     $this->log = new \Entity\Log();
     $this->log->setAction($this->getService('doctrine')->getRepository('Entity\\LogAction')->findOneById(14));
     $this->log->setIpAddress('127.0.0.1');
     $this->log->setIsSuccess(true);
     $this->log->setCountModifiedEntities(0);
     $em->persist($this->log);
     $role = new Role();
     $role->setName('Admin');
     foreach ($em->getRepository('Entity\\Functionality')->findAll() as $functionality) {
         $role->getFunctionalities()->add($functionality);
     }
     $this->persist($role);
     $user = new User();
     $user->setEmail('*****@*****.**');
     $user->setFirstName('first name');
     $user->setLastName('last name');
     $user->setLocation($em->getRepository('Entity\\Location')->findOneBy(array()));
     $user->setRole($role);
     $em->persist($user);
     $this->createLogEntity($user);
     $em->flush();
     $this->user = $user;
 }
Ejemplo n.º 14
0
 public function removeadminAction()
 {
     $this->doNotRender();
     $id = (int) $this->getParam('id');
     $user = \Entity\User::find($id);
     $user->podcasts->removeElement($this->podcast);
     $user->save();
     return $this->redirectFromHere(array('action' => 'index', 'id' => NULL));
 }
Ejemplo n.º 15
0
 /**
  * @PreDelete
  */
 public function deleted()
 {
     if ($this->comments->count() > 0) {
         foreach ($this->comments as $comment) {
             \FA\Legacy\Notifications::purge('journal_comment', $comment->id, $this->user_id);
         }
     }
     User::decrementCounter('journals', $this->user_id);
     \FA\Legacy\Notifications::purge('journal', $this->id);
 }
Ejemplo n.º 16
0
 public function authenticate($credentials = NULL)
 {
     $user_auth = User::authenticate($credentials['username'], $credentials['password']);
     if ($user_auth instanceof User) {
         $this->setUser($user_auth);
         return true;
     } else {
         \DF\Flash::addMessage('Could not authenticate your credentials!', 'red');
         return false;
     }
 }
Ejemplo n.º 17
0
 public function getNotifications()
 {
     $notifications = array();
     $notify_types = User::getNotificationTypes();
     foreach ($notify_types as $notify_key => $notify_info) {
         $notify_info['count'] = 0;
         $notify_info['show'] = FALSE;
         $notify_info['text'] = '';
         $notifications[$notify_info['short']] = $notify_info;
     }
 }
Ejemplo n.º 18
0
 public function impersonateAction()
 {
     $id = (int) $this->getParam('id');
     $user = User::find($id);
     if (!$user instanceof User) {
         throw new \DF\Exception\DisplayOnly('User not found!');
     }
     // Set new identity in Zend_Auth
     $this->auth->masqueradeAsUser($user);
     $this->alert('<b>Logged in as ' . $user->firstname . ' ' . $user->lastname . '.</b>', 'green');
     $this->redirectHome();
     return;
 }
Ejemplo n.º 19
0
 public function verifyAction()
 {
     $id = (int) $this->getParam('id');
     $code = trim($this->getParam('code'));
     if ($id == 0 || empty($code)) {
         throw new \FA\Exception('This page requires a valid user ID and recovery code.');
     }
     $user = User::getRepository()->findOneBy(array('id' => $id, 'lostpw' => $code));
     if (!$user instanceof User) {
         throw new \FA\Exception('Invalid ID or recovery code provided!');
     }
     // Reset the "lost password" code.
     $user->lostpw = NULL;
     $user->save();
     $this->auth->setUser($user);
 }
Ejemplo n.º 20
0
 /**
  * Get course user relationship based in the course_rel_user table.
  * @return array
  */
 public function getCourses(User $user)
 {
     $queryBuilder = $this->createQueryBuilder('user');
     // Selecting course info.
     $queryBuilder->select('c');
     // Loading User.
     //$qb->from('Entity\User', 'u');
     // Selecting course
     $queryBuilder->innerJoin('Entity\\Course', 'c');
     //@todo check app settings
     //$qb->add('orderBy', 'u.lastname ASC');
     $wherePart = $queryBuilder->expr()->andx();
     // Get only users subscribed to this course
     $wherePart->add($queryBuilder->expr()->eq('user.userId', $user->getUserId()));
     $queryBuilder->where($wherePart);
     $query = $queryBuilder->getQuery();
     return $query->execute();
 }
Ejemplo n.º 21
0
 /**
  * build form
  * @param FormBuilderInterface $builder bulder object
  * @param array                $options available options to inject
  *
  * @see \Symfony\Component\Form\AbstractType::buildForm()
  *
  * @return void
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $object = isset($options['data']) ? $options['data'] : null;
     $builder->add('userAuth', UserAuthType::class, array('label' => ' '));
     $builder->add('userType');
     $builder->add('userRoles', EntityType::class, array('class' => RoleInfo::class, 'attr' => array('class' => 'js-user-roles'), 'expanded' => false, 'multiple' => false, 'data' => $this->currentRole));
     $builder->add('firstName');
     $builder->add('lastName');
     $builder->add('email', null, array('required' => false, 'constraints' => array(new VALIDATOR\NotBlank(array('message' => "Please enter email")))));
     $builder->add('address');
     $builder->add('phone', null, array('attr' => array('class' => 'js-phone')));
     $builder->add('mobile', null, array('attr' => array('class' => 'js-phone')));
     $builder->add('fax', null, array('attr' => array('class' => 'js-phone')));
     $builder->add('company');
     $builder->add('slogan');
     $builder->add('homepage', null, array('attr' => array('class' => 'js-homepage'), 'constraints' => array(new VALIDATOR\Url(array('protocols' => array('http', 'https', 'ftp'), 'dnsMessage' => "Please enter proper home page url")))));
     $builder->add('status', ChoiceType::class, array('choices' => User::getStatusOptions(), 'expanded' => true, 'multiple' => false, 'data' => isset($object) ? $object->getStatus() ? $object->getStatus() : 'A' : 'A', 'attr' => array('class' => 'minimal display-inline')));
     $builder->add('logo', 'file', array('required' => false, 'label' => 'Image', 'constraints' => array(new VALIDATOR\File(array('mimeTypes' => array('image/jpg', 'image/jpeg', 'image/png', 'image/bmp', 'image/gif'), 'mimeTypesMessage' => "Please Upload Valid File")))));
     $builder->add('updatedAt', 'hidden', array('data' => ''));
 }
Ejemplo n.º 22
0
 public function indexAction()
 {
     $cache = $this->di->get('cache');
     $rating_query = '(true = true)';
     $rating_cache = '';
     if ($this->fa->canSeeArt('adult')) {
         $rating_cache = 'gma';
     } elseif ($this->fa->canSeeArt('mature')) {
         $rating_query = '(up.rating = ' . Upload::RATING_GENERAL . ' OR up.rating = ' . Upload::RATING_MATURE . ')';
         $rating_cache = 'gm-';
     } else {
         $rating_query = '(up.rating = ' . Upload::RATING_GENERAL . ')';
         $rating_cache = 'g--';
     }
     $frontpage_cache_key = 'fa.frontpage.recent' . $rating_cache;
     $frontpage_cache_lifetime = 30;
     // 30 seconds
     $frontpage_data = $cache->load($frontpage_cache_key);
     if (!$frontpage_data) {
         $frontpage_data = array();
         $record_types = array('images' => Upload::TYPE_IMAGE, 'audio' => Upload::TYPE_AUDIO, 'text' => Upload::TYPE_TEXT);
         $type_records_query = $this->em->createQuery('SELECT up.id, up.title, up.description, up.rating, up.thumbnail, us.username, us.lower, us.avatar_mtime FROM Entity\\Upload up JOIN up.user us WHERE up.upload_type = :type AND up.is_scrap = 0 AND ' . $rating_query . ' ORDER BY up.id DESC')->setMaxResults(21);
         foreach ($record_types as $type_key => $type_code) {
             $type_records_raw = $type_records_query->setParameter('type', $type_code)->getArrayResult();
             $type_records = array();
             foreach ($type_records_raw as $record) {
                 if ($record['rating'] != Upload::RATING_GENERAL) {
                     $this->fa->setPageHasMatureContent(true);
                 }
                 $record['rating_text'] = Upload::getRatingText($record['rating']);
                 $record['thumbnail_url'] = Upload::getFileUrl($record['thumbnail']);
                 $record['avatar'] = User::getUserAvatar($record['lower'], $record['avatar_mtime']);
                 $type_records[$record['id']] = $record;
             }
             $frontpage_data[$type_key] = $type_records;
         }
         $cache->set($frontpage_data, $frontpage_cache_key, $frontpage_cache_lifetime);
     }
     $this->view->records = $frontpage_data;
 }
Ejemplo n.º 23
0
 /**
  * @PreDelete
  */
 public function deleting()
 {
     // Delete files
     $full_path = $this->getFullPath();
     if (!empty($full_path)) {
         @unlink($full_path);
     }
     $small_path = $this->getSmallPath();
     if (!empty($small_path)) {
         @unlink($small_path);
     }
     $thumb_path = $this->getThumbnailPath();
     if (!empty($thumb_path)) {
         @unlink($thumb_path);
     }
     if ($this->comments->count() > 0) {
         foreach ($this->comments as $comment) {
             \FA\Legacy\Notifications::purge('upload_comment', $comment->id, $this->user_id);
         }
     }
     User::decrementCounter('uploads', $this->user_id);
     \FA\Legacy\Notifications::purge('upload', $this->id);
 }
 public function registerUser(Request $request)
 {
     $sessionUserData = $this->app['session'];
     $entityManager = $this->app['doctrine'];
     $user = new User();
     $user->setUserName($request->request->get('userName'));
     $user->setUserEmail($request->request->get('userEmail'));
     $user->setPassword($request->request->get('userPassword'));
     $user->setOfficeLocation($request->request->get('officeLocation'));
     $user->setUserAddress($request->request->get('userAddress'));
     try {
         $entityManager->persist($user);
         $entityManager->flush();
         if (null !== $request->files->get('resumeFile')) {
             $fs = new FileHandler();
             $fs->fileUpload($request->files->get('resumeFile'), $user->getId(), UPLOAD_PATH);
         }
         $sessionUserData->getFlashBag()->add('alert_success', 'Registration successful');
         return $this->app->redirect(BASEPATH . "/login");
     } catch (UniqueConstraintViolationException $ex) {
         $sessionUserData->getFlashBag()->add('alert_danger', 'Sorry, this email id is already registered!');
         return $this->app->redirect(BASEPATH . "/register");
     }
 }
Ejemplo n.º 25
0
 /**
  * Set the username and lower-case version together.
  * @param $username
  */
 public function setUsername($username)
 {
     $this->username = $username;
     $this->lower = User::getLowerCase($username);
 }
Ejemplo n.º 26
0
 /**
  * 
  * @param \Entity\User $user
  */
 public function delete($user)
 {
     $sql = 'delete from  user  WHERE user_id=:id';
     $stmt = $this->db->getConnection()->prepare($sql);
     $stmt->bindParam('id', $user->getUserId());
     return $stmt->execute();
 }
Ejemplo n.º 27
0
 public function transform(\Entity\User $user)
 {
     return ['id' => (int) $user->getUserId(), 'email' => $user->getEmail(), 'name' => $user->getName(), 'active' => $user->getActive(), 'group' => $user->getGroup(), 'links' => ['rel' => 'self', 'uri' => \Util\SlimUtil::absoluteUrlFor('user_by_id', ['id' => $user->getUserId()]), 'method' => 'GET']];
 }
 /**
  * Get all users that are registered in the course. No matter the status
  *
  * @param \Entity\CurriculumItem $course
  * @return bool
  */
 public function isAllowToInsert(\Entity\CurriculumItem $item, \Entity\User $user)
 {
     $max = $item->getMaxRepeat();
     $count = $this->createQueryBuilder('a')->select('COUNT(a)')->where('a.itemId = :itemId')->andWhere('a.userId = :userId')->setParameters(array('itemId' => $item->getId(), 'userId' => $user->getUserId()))->getQuery()->getSingleScalarResult();
     return $count <= $max ? true : false;
 }
Ejemplo n.º 29
0
<?php

require_once __DIR__ . '/bootstrap_doctrine.php';
use Entity\User;
use Entity\Article;
$factoryManager = new Fixtures\FactoryManager();
$factoryManager->set('user', function ($provider) {
    $user = new User();
    $user->setUsername($provider->get('username', 'John'));
    return $user;
});
$factoryManager->set('article', function ($provider) {
    $article = new Article();
    $article->setAuthor($provider->getRelation('author', 'user'));
    $article->setTitle($provider->get('title', 'The title'));
    $article->setContent($provider->get('content', 'The content'));
    return $article;
});
$storageManager = new Fixtures\StorageManager();
$storageManager->register(new Fixtures\Storage\Doctrine\ORM($entityManager));
$environment = new Fixtures\Environment($factoryManager, $storageManager);
$environment->reset();
$environment->createCollection(100, 'article', array('author' => $environment->create('user')));
 /**
  * Fonction permettant d'ajouter un message à un groupe concerné en BDD.
  * @param Groupe $groupe : le groupe concerné.
  * @param User $user : l'utilisateur envoyant le message.
  * @param $desc : le contenu du message.
  */
 public function addMess(Groupe $groupe, User $user, $desc)
 {
     $query = $this->db->prepare("INSERT INTO groupe_message(id_groupe, id_user, description, date ) VALUES (:id_groupe , :id_user, :desc , NOW())");
     $query->execute(array("id_groupe" => $groupe->getIdGroupe(), "id_user" => $user->getId(), "desc" => $desc));
 }