private function registerUser($username, $data = NULL)
 {
     try {
         $gingerKey = sfConfig::get('app_portail_ginger_key');
         if ($gingerKey != "abc") {
             $ginger = new \Ginger\Client\GingerClient(sfConfig::get('app_portail_ginger_key'));
             $cotisants = $ginger->getUser($username);
         } else {
             $cotisants = new stdClass();
             $cotisants->mail = $username . "@etu.utc.fr";
             $cotisants->prenom = "Le";
             $cotisants->nom = "Testeur";
             $cotisants->type = "etu";
         }
         if (!$data) {
             $data = new sfGuardUser();
         }
         $data->setUsername($username);
         $data->setEmailAddress($cotisants->mail);
         $data->setFirstName($cotisants->prenom);
         $data->setLastName($cotisants->nom);
         $data->setIsActive(true);
         $data->save();
         $profile = new Profile();
         $profile->setUser($data);
         $profile->setDomain($cotisants->type);
         $profile->save();
         return $data;
     } catch (\Ginger\Client\ApiException $ex) {
         $this->setFlash('error', "Il n'a pas été possible de vous identifier. Merci de contacter simde@assos.utc.fr en précisant votre login et le code d'erreur " . $ex->getCode() . ".");
     }
     return false;
 }
Exemple #2
0
 protected function doClean($values)
 {
     $username = isset($values[$this->getOption('username_field')]) ? $values[$this->getOption('username_field')] : '';
     bhLDAP::debug('######## Username: '******'password_field')]) ? $values[$this->getOption('password_field')] : '';
     bhLDAP::debug('######## User exists?');
     $user = Doctrine::getTable('sfGuardUser')->findOneByUsername($username);
     //    bhLDAP::debugDump($user, "user:");
     if (!$user) {
         if (bhLDAP::checkPassword($username, $password)) {
             // pretend the user exists, then check AD password
             bhLDAP::debug('######## User does not exist. Creating dummy user.');
             $user = new sfGuardUser();
             $user->setUsername($username);
             $user->setSalt('unused');
             $user->setPassword('unused');
             $user->setUserProfile(new UserProfile());
             $user->save();
         }
         return array_merge($values, array('user' => $user));
     }
     // password is ok?
     bhLDAP::debug('######## Checking Password...');
     if ($user->checkPassword($password)) {
         bhLDAP::debug('######## Check Password successful...');
         return array_merge($values, array('user' => $user));
     }
     bhLDAP::debug('######## Check Password failed...');
     if ($this->getOption('throw_global_error')) {
         throw new sfValidatorError($this, 'invalid');
     }
     throw new sfValidatorErrorSchema($this, array($this->getOption('username_field') => new sfValidatorError($this, 'invalid')));
 }
 /**
  * @see sfValidatorBase
  */
 protected function doClean($values)
 {
     // only validate if username and password are both present
     if (isset($values[$this->getOption('username_field')]) && isset($values[$this->getOption('password_field')])) {
         $username = $values[$this->getOption('username_field')];
         $password = $values[$this->getOption('password_field')];
         // user exists?
         if ($user = sfGuardUserPeer::retrieveByUsername($username)) {
             // password is ok?
             if ($user->getIsActive()) {
                 if (Configuration::get('ldap_enabled', false)) {
                     if (authLDAP::checkPassword($username, $password)) {
                         return array_merge($values, array('user' => $user));
                     }
                 } elseif ($user->checkPassword($password)) {
                     return array_merge($values, array('user' => $user));
                 }
             }
         } elseif (Configuration::get('ldap_enabled', false) && Configuration::get('ldap_create_user', false) && authLDAP::checkPassword($username, $password)) {
             $user = new sfGuardUser();
             $user->setUsername($username);
             $user->save();
             $profile = new Profile();
             $profile->setSfGuardUserId($user->getId());
             $profile->save();
             return array_merge($values, array('user' => $user));
         }
         if ($this->getOption('throw_global_error')) {
             throw new sfValidatorError($this, 'invalid');
         }
         throw new sfValidatorErrorSchema($this, array($this->getOption('username_field') => new sfValidatorError($this, 'invalid')));
     }
     // assume a required error has already been thrown, skip validation
     return $values;
 }
 /**
  * Tests saving a sfGuardUserSubredditMembership that identifies a User as
  * "blocked" for a particular Subreddit.  When this occurs, all existing
  * future EpisodeAssignments should be deleted because blocked users cannot
  * participate with the Subreddit.
  */
 public function testSavingBlockedUser()
 {
     // Establish fake Subreddit
     $subreddit = new Subreddit();
     $subreddit->setName(rand(0, 1000));
     $subreddit->setDomain(rand(0, 1000));
     $subreddit->save();
     // Establish User
     $user = new sfGuardUser();
     $user->setEmailAddress(rand(0, 100000));
     $user->setUsername(rand(0, 10000));
     $user->setIsValidated(1);
     $user->save();
     $user_id = $user->getIncremented();
     $this->assertNotEquals(0, $user_id);
     // Establish Episode for Subreddit
     $episode = new Episode();
     $episode->setSubreddit($subreddit);
     $episode->setReleaseDate(date('Y-m-d H:i:s', time() + 34000));
     $episode->save();
     $author_type = AuthorTypeTable::getInstance()->findOneBy('type', 'squid');
     $deadline = new Deadline();
     $deadline->setSubreddit($subreddit);
     $deadline->setAuthorType($author_type);
     $deadline->setSeconds(0);
     $deadline->save();
     $episode_assignment = new EpisodeAssignment();
     $episode_assignment->setSfGuardUser($user);
     $episode_assignment->setEpisode($episode);
     $episode_assignment->setAuthorType($author_type);
     $episode_assignment->save();
     $number_of_episodes = EpisodeAssignmentTable::getInstance()->createQuery()->select('COUNT(EpisodeAssignment.id)')->leftJoin('Episode')->where('subreddit_id = ?', $subreddit->getIncremented())->andWhere('EpisodeAssignment.sf_guard_user_id = ?', $user_id)->andWhere('Episode.release_date > NOW()')->groupBy('EpisodeAssignment.id')->count();
     $this->assertEquals(1, $number_of_episodes);
     // Establish User Membership as Blocked
     $blocked = MembershipTable::getInstance()->findOneBy('type', 'blocked');
     $user_membership = new sfGuardUserSubredditMembership();
     $user_membership->setSubreddit($subreddit);
     $user_membership->setSfGuardUser($user);
     $user_membership->setMembership($blocked);
     // Save Membership
     $user_membership->save();
     // Asert that User has zero Episodes
     $number_of_episodes = EpisodeAssignmentTable::getInstance()->createQuery()->select('COUNT(EpisodeAssignment.id)')->leftJoin('Episode')->where('subreddit_id = ?', $subreddit->getIncremented())->andWhere('EpisodeAssignment.sf_guard_user_id = ?', $user_id)->andWhere('Episode.release_date > NOW()')->groupBy('EpisodeAssignment.id');
     $sql = $number_of_episodes->getSqlQuery();
     $number_of_episodes = $number_of_episodes->count();
     $this->assertTrue(0 == $number_of_episodes, $sql . "\n" . $subreddit->getIncremented() . "\n" . $user_id);
     // Remove User Membership
     $user_membership->delete();
     // Delete User
     $user->delete();
     // Delete Episode
     $episode->delete();
     // Delete Deadline
     $deadline->delete();
     // Delete Subreddit
     $subreddit->delete();
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $user = new sfGuardUser();
     $user->setUsername($arguments['username']);
     $user->setPassword($arguments['password']);
     $user->save();
     $this->logSection('guard', sprintf('Create user "%s"', $arguments['username']));
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $configuration = ProjectConfiguration::getApplicationConfiguration($arguments['application'], $options['env'], true);
     $databaseManager = new sfDatabaseManager($configuration);
     $user = new sfGuardUser();
     $user->setUsername($arguments['username']);
     $user->setPassword($arguments['password']);
     $user->setIsActive(true);
     $user->save();
     $this->logSection('guard', sprintf('Create user "%s"', $arguments['username']));
 }
 public function doSave($con = null)
 {
     $user = new sfGuardUser();
     $user->setUsername($this->getValue('username'));
     $user->setPassword($this->getValue('password'));
     // They must confirm their account first
     $user->setIsActive(false);
     $user->save();
     $this->userId = $user->getId();
     return parent::doSave($con);
 }
 /**
  * Accepts proof of identity from the client side Facebook SDK.
  * https://developers.facebook.com/docs/howtos/login/signed-request/#step2
  * This will not work if your site doesn't have a proper
  * domain name (it will not work in dev, in most cases).
  */
 public function executeFacebookLogin(sfWebRequest $request)
 {
     $fb = sfConfig::get('app_sfApplyPlugin_facebook');
     $secret = isset($fb['secret']) ? $fb['secret'] : null;
     if (!$secret) {
         throw new sfException('app_sfApplyPlugin_facebook not configured, secret missing');
     }
     $signed_request = $request->getParameter('signed_request');
     list($encoded_sig, $payload) = explode('.', $signed_request, 2);
     // decode the data
     $sig = $this->base64UrlDecode($encoded_sig);
     $data = json_decode($this->base64UrlDecode($payload), true);
     // Contrary to FB docs we're not done yet, we have to
     // trade the 'code' in for an access token and then we
     // can query for information about the user
     $code = $data['code'];
     $url = "https://graph.facebook.com/oauth/access_token?" . http_build_query(array('client_id' => $fb['id'], 'redirect_uri' => '', 'client_secret' => $secret, 'code' => $code));
     $accessToken = file_get_contents($url);
     parse_str($accessToken, $result);
     $accessToken = $result['access_token'];
     $me = json_decode(file_get_contents("https://graph.facebook.com/me?" . http_build_query(array('access_token' => $accessToken))), true);
     if (!isset($me['email'])) {
         $this->forward404();
     }
     $email = $me['email'];
     $first_name = $me['first_name'];
     $last_name = $me['last_name'];
     $username = '******' . (isset($me['username']) ? $me['username'] : $me['id']);
     if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
         $this->forward404();
     }
     // Adding the verification of the signed_request below
     $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
     if ($sig !== $expected_sig) {
         $this->forward404();
     }
     $user = Doctrine::getTable('sfGuardUser')->findOneByEmailAddress($email);
     if (!$user) {
         $user = new sfGuardUser();
         $user->setIsActive(true);
         $user->setPassword(aGuid::generate());
         $user->setEmailAddress($email);
         $user->setUsername($username);
     }
     $user->setFirstName($firstName);
     $user->setLastName($lastName);
     $user->setEmailAddress($email);
     $user->save();
     $this->getUser()->signIn($user);
     return $this->renderText('OK');
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $user = new sfGuardUser();
     $user->setUsername($arguments['username']);
     $user->setPassword($arguments['password']);
     $user->save();
     $profile = new Profile();
     $profile->setNickname($arguments['nickname']);
     $profile->setEmail($arguments['email']);
     $profile->setSfGuardUserId($user->getId());
     $profile->save();
     $this->logSection('crew', sprintf('Create user "%s"', $arguments['username']));
 }
 public function createUser(array $guard_tab, $ei_user_tab)
 {
     $new_guard = new sfGuardUser();
     $new_guard->setId($guard_tab['id']);
     $new_guard->setUsername($guard_tab['username']);
     $new_guard->setFirstName($guard_tab['first_name']);
     $new_guard->setLastName($guard_tab['last_name']);
     $new_guard->setEmailAddress($guard_tab['email_address']);
     $new_guard->setPassword($guard_tab['password']);
     $new_guard->save();
     /* Création du EiUser */
     EiUserTable::createUser($ei_user_tab, $new_guard->getId());
     return $new_guard;
 }
 /**
  * @see sfTask
  */
 protected function execute($arguments = array(), $options = array())
 {
     $databaseManager = new sfDatabaseManager($this->configuration);
     $user = new sfGuardUser();
     $user->setEmailAddress($arguments['email_address']);
     $user->setUsername($arguments['username']);
     $user->setPassword($arguments['password']);
     $user->setFirstName($arguments['first_name']);
     $user->setLastName($arguments['last_name']);
     $user->setIsActive(true);
     $user->setIsSuperAdmin($options['is-super-admin']);
     $user->save();
     $this->logSection('guard', sprintf('Create user "%s"', $arguments['username']));
 }
 public function doSave($con = null)
 {
     if ($this->isNew) {
         $user = new sfGuardUser();
         $user->setUsername($this->getValue('username'));
         $user->setPassword($this->getValue('password'));
         $user->setEmailAddress($this->getValue('email'));
         $user->addGroupByName(sfConfig::get('app_user_default_group'));
         // They must confirm their account first
         $user->setIsActive(false);
         $user->save();
         $this->getObject()->setUserId($user->getId());
     }
     return parent::doSave($con);
 }
Exemple #13
0
 public function executeApply()
 {
     $request = $this->getRequest();
     $this->form = new RegisterForm();
     if ($this->getRequest()->getMethod() == sfRequest::POST) {
         $this->form->bind($request->getParameter('register'));
         if ($this->form->isValid()) {
             mysfLog::log($this, "DEBUG: " . print_r($this->form->getValues(), TRUE));
             $this->form_ref =& $this->form;
             $username = $this->form->getValue('email');
             $password = $this->form->getValue('password');
             $sfGuardUser = new sfGuardUser();
             $sfGuardUser->setUsername($username);
             $sfGuardUser->setPassword($password);
             // Not until confirmed
             $sfGuardUser->setIsActive(false);
             $profile = $sfGuardUser->getProfile();
             $sfGuardUser->save();
             // save sfGuardUser before we populate the user profile because we need the user id
             $this->myPopulateProfileSettings($profile, $sfGuardUser);
             $profile->save();
             // Email start
             $opts = array();
             $opts['from_name'] = sfConfig::get('app_mail_fromname', "Spectralmind");
             $opts['from_email'] = sfConfig::get('app_mail_from', "*****@*****.**");
             $opts['parameters'] = array('validate' => $profile->getValidate());
             $opts['body_is_partial'] = true;
             $opts['to_name'] = $profile->getName();
             $opts['to_email'] = $profile->getEmail();
             $opts['subject'] = sfConfig::get('app_mail_subjectconfirmmail', "Confirm your registration");
             //$opts['html'] = "sendValidateNew";
             $opts['text'] = "sendValidateNew";
             /*
             				 // Or to use the Echo Logger
             				 $logger = new Swift_Plugins_Loggers_EchoLogger();
             				 $this->getMailer()->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
             				 * */
             $numSent = smintMailHelper::mail($opts);
             // not sent? react accordingly
             if ($numSent != 1) {
                 mysfLog::log($this, "ERROR: confirmation email not sent. Return value was {$numSent}");
                 return 'Error';
             }
             mysfLog::log($this, "DEBUG: Confirm link:" . url_for("sfApply/confirm?validate=" . $profile->getValidate(), true));
             return 'After';
         }
     }
 }
 /**
  * Create a user for a Facebook account
  *
  * Based on and borrowed heavily from
  * sfFacebookGuardAdapter::createSfGuardUserWithFacebookUidAndCon in
  * sfFacebookConnectPlugin by Fabrice Bernhard
  *
  * @param   int     $facebookUid
  * @param   string  $accessToken
  * @param   int     $accessTokenExpiry
  * @param   array   $facebookUserInfo
  * @return  sfGuardUser
  */
 public static function createUser($facebookUid, $accessToken, $accessTokenExpiry, array $facebookUserInfo)
 {
     $sfGuardUser = new sfGuardUser();
     $sfGuardUser->setUsername(self::generateFacebookUsername($facebookUid));
     $connection = Doctrine::getConnectionByTableName('sfGuardUser');
     try {
         $connection->beginTransaction();
         $sfGuardUser->save();
         $sfGuardUser->getProfile()->setFacebookOnlyAccount(true)->_connectToFacebook($facebookUid, $accessToken, $accessTokenExpiry, $facebookUserInfo, $sfGuardUser);
         $connection->commit();
     } catch (Exception $e) {
         $connection->rollback();
         throw $e;
     }
     return $sfGuardUser;
 }
Exemple #15
0
 /**
  * DOCUMENT ME
  * @return mixed
  */
 public static function getTaskUser()
 {
     $user = Doctrine::getTable('sfGuardUser')->findOneByUsername('ataskuser');
     if (!$user) {
         $user = new sfGuardUser();
         $user->setUsername('ataskuser');
         // Set a good unique password just in case someone cluelessly sets the active flag.
         // This further ensures that no one can ever log in with this account
         $user->setPassword(aGuid::generate());
         // Prevents normal login
         $user->setIsActive(false);
         $user->setIsSuperAdmin(true);
         $user->save();
     }
     return $user;
 }
 public static function updateOrCreateFbUser($profile)
 {
     $sfGuardUser = Doctrine_Core::getTable('sfGuardUser')->findOneByFacebookId($profile['id']);
     if (!$sfGuardUser) {
         $sfGuardUser = new sfGuardUser();
         $sfGuardUser->setUsername('FB_' . $profile['id']);
         $sfGuardUser->facebook_id = $profile['id'];
         $sfGuardUser->first_name = $profile['first_name'];
         $sfGuardUser->last_name = $profile['last_name'];
         if (array_key_exists('email', $profile)) {
             $sfGuardUser->email_address = $profile['email'];
         } else {
             $sfGuardUser->email_address = $profile['id'] . '@fb.com';
         }
         $sfGuardUser->save();
     }
     return $sfGuardUser;
 }
 /**
  * This is a symfony workaround. As soon as someone logs in check if they are in the DB.
  * If they aren't just insert them so they can authenticate.
  *
  * @param sfWebRequest $request
  */
 public function executeSignin($request)
 {
     if ($request->isMethod("post")) {
         $form = new sfGuardFormSignin();
         $username = $request->getParameter($form->getName() . "[username]");
         $c = new Criteria();
         $c->add(sfGuardUserPeer::USERNAME, $username);
         $res = sfGuardUserPeer::doCount($c);
         // if they dont exist in the db then stick them in so LDAP works
         if ($res == 0) {
             $u = new sfGuardUser();
             $u->setUsername($username);
             $u->save();
             $u->getProfile();
         }
     }
     parent::executeSignin($request);
 }
 public function executeApply()
 {
     if ($this->getRequest()->getMethod() == sfRequest::POST) {
         $username = $this->getRequestParameter('username');
         $password = $this->getRequestParameter('password');
         $sfGuardUser = new sfGuardUser();
         $sfGuardUser->setUsername($username);
         $sfGuardUser->setPassword($password);
         // Not until confirmed
         $sfGuardUser->setIsActive(false);
         $profile = $sfGuardUser->getProfile();
         $this->populateProfileSettings($profile);
         $sfGuardUser->save();
         $profile->save();
         $this->setFlash('sfApplyPlugin_id', $sfGuardUser->getId(), false);
         $this->sendEmail('sfApply', 'sendValidate');
         return 'After';
     }
 }
 public function executeSignUp($request)
 {
     $this->form = new SignUpForm();
     if ($request->isMethod('get')) {
         return;
     }
     $this->form->bind($request->getParameter('form'));
     if (!$this->form->isValid()) {
         return;
     }
     $sfGuardUser = new sfGuardUser();
     $sfGuardUser->setUsername($this->form->getValue('username'));
     $sfGuardUser->setPassword($this->form->getValue('password'));
     $sfGuardUser->setIsActive(false);
     $sfGuardUser->save();
     $sfGuardUserProfile = new sfGuardUserProfile();
     $sfGuardUserProfile->setSfGuardUser($sfGuardUser);
     $sfGuardUserProfile->setEmail($this->form->getValue('email'));
     $sfGuardUserProfile->setFirstName($this->form->getValue('first_name'));
     $sfGuardUserProfile->setLastName($this->form->getValue('last_name'));
     $sfGuardUserProfile->setGender($this->form->getValue('gender'));
     $sfGuardUserProfile->setBirthday($this->form->getValue('birthday'));
     $sfGuardUserProfile->setWebpage($this->form->getValue('webpage'));
     $sfGuardUserProfile->save();
     try {
         $connection = new Swift_Connection_SMTP('mail.sis-nav.com', 25);
         $connection->setUsername('*****@*****.**');
         $connection->setPassword('gahve123');
         $mailer = new Swift($connection);
         $message = new Swift_Message('Account Confirmation');
         $mailContext = array('email' => $sfGuardUserProfile->getEmail(), 'full_name' => $sfGuardUserProfile->getFullName(), 'activation_key' => $sfGuardUserProfile->getActivationKey());
         $message->attach(new Swift_Message_Part($this->getPartial('mail/signUpHtmlBody', $mailContext), 'text/html'));
         $message->attach(new Swift_Message_Part($this->getPartial('mail/signUpTextBody', $mailContext), 'text/plain'));
         $mailer->send($message, $sfGuardUserProfile->getEmail(), '*****@*****.**');
         $mailer->disconnect();
     } catch (Exception $e) {
         $mailer->disconnect();
     }
     $this->getUser()->setFlash('info', 'A confirmation email has been sent to your email address.');
     $this->forward('site', 'message');
 }
 /**
  * Serialize the form into the database.
  **/
 public function save($con = null)
 {
     if (!is_null($this->getValue("photographer_id"))) {
         $p = $this->getObject();
     } else {
         $sfUser = new sfGuardUser();
         $sfUser->setUsername($this->getValue("email"));
         $sfUser->setPassword($this->getValue("password"));
         $sfUser->save();
         if (strpos($this->getValue("name"), " ") !== false) {
             list($firstName, $lastName) = explode(" ", $this->getValue("name"));
         } else {
             $firstName = "";
             $lastName = "";
         }
         $sfProfile = new sfGuardUserProfile();
         $sfProfile->setUserTypeId(sfConfig::get("app_user_type_photographer"));
         $sfProfile->setUserId($sfUser->getId());
         $sfProfile->setEmail($this->getValue("email"));
         $sfProfile->setFirstName($firstName);
         $sfProfile->setLastName($lastName);
         $sfProfile->save();
         $p = new Photographer();
         $p->setUserId($sfProfile->getId());
     }
     $p->setName($this->getValue("name"));
     $p->setEmail($this->getValue("email"));
     $p->setPhone($this->getValue("phone"));
     $p->setAffiliation($this->getValue("affiliation"));
     $p->setWebsite($this->getValue("website"));
     $p->setDescription($this->getValue("description"));
     $p->setBillingAddress($this->getValue("billing_info"));
     $p->save();
     if ($this->getValue("reset_password")) {
         $user = $p->getsfGuardUserProfile()->getsfGuardUser();
         $user->setPassword($this->getValue("password"));
         $user->save();
     }
 }
    /**
     * Updates or creates a sfGuardUser for the logged in Facebook usser
     * 
     * @param array $me 
     * @return sfGuardUser
     */
    public static function updateOrCreateUser(array $me) {
        // Try by Facebook ID
        $sfGuardUser = Doctrine_Core::getTable('sfGuardUser')->findOneByFacebookId($me['id']);
        if (!$sfGuardUser) {
            // Try by email address
            $sfGuardUser = Doctrine_Core::getTable('sfGuardUser')->findOneByEmailAddress($me['email']);
            if (!$sfGuardUser) {
                $sfGuardUser = new sfGuardUser();
                $sfGuardUser->setUsername('Facebook_' . $me['id']);
            }
        }
        
        $sfGuardUser->setFacebookId($me['id']);
        $sfGuardUser->setFacebookLink($me['link']);
        $sfGuardUser->setFirstName($me['first_name']);
        $sfGuardUser->setLastName($me['last_name']);
        if (array_key_exists('verified', $me)) {
            $sfGuardUser->setFacebookVerified($me['verified']);
        }
        if (array_key_exists('location', $me)) {
            $sfGuardUser->setLocation($me['location']['name']);
            $sfGuardUser->setFacebookLocationId($me['location']['id']);
        }
        if (array_key_exists('hometown', $me)) {
            $sfGuardUser->setHometown($me['hometown']['name']);
            $sfGuardUser->setFacebookHometownId($me['hometown']['id']);
        }
        $sfGuardUser->setGender($me['gender']);
        $sfGuardUser->setLocale($me['locale']);
        $sfGuardUser->setTimezone($me['timezone']);
        if (array_key_exists('email', $me)) {
            $sfGuardUser->setEmailAddress($me['email']);
        }
        $sfGuardUser->save();

        return $sfGuardUser;
    }
 protected function processForm(sfWebRequest $request, sfForm $form)
 {
     $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
     if ($form->isValid()) {
         $peticion = $form->save();
         $newUser = new sfGuardUser();
         $newUser->setUsername($form->getObject()->getUsername());
         $newUser->setFirstName($form->getObject()->getFirstName());
         $newUser->setLastName($form->getObject()->getLastName());
         $newUser->setSexo($form->getObject()->getSexo());
         $newUser->setDireccion($form->getObject()->getDireccion());
         $newUser->setTelefono($form->getObject()->getTelefono());
         $newUser->setTelefonoMovil($form->getObject()->getTelefonoMovil());
         $newUser->setEmailAddress($form->getObject()->getEmailAddress());
         $newUser->setPassword($form->getObject()->getPassword());
         try {
             $newUser->save();
             $peticion->delete();
             $this->redirect('sfGuardUser/editagregar?id=' . $newUser->getId());
         } catch (Exception $e) {
             $this->redirect('peticion/edit?id=' . $peticion->getId());
         }
     }
 }
 /**
  * Since a User can only have one membership in a Subreddit, this tests that
  * the first returned sfGuardUserSubredditMembership is the exact same as
  * the only one made.  The limitation on sfGuardUserSubredditMemberships is
  * in place using Unique indexes in the database, so we depend upon that to
  * prevent multiple Subreddit Memberships.
  */
 public function testGetFirstByUserSubredditAndMemberships()
 {
     $user = new sfGuardUser();
     $user->setEmailAddress(rand(0, 1000));
     $user->setUsername(rand(0, 1000));
     $user->setIsValidated(1);
     $user->save();
     $subreddit = new Subreddit();
     $subreddit->setName(rand(0, 1000));
     $subreddit->setDomain(rand(0, 1000));
     $subreddit->save();
     $membership = MembershipTable::getInstance()->findOneByType('user');
     $second_membership = MembershipTable::getInstance()->findOneByType('admin');
     $user_subreddit_membership = new sfGuardUserSubredditMembership();
     $user_subreddit_membership->setSfGuardUserId($user->getIncremented());
     $user_subreddit_membership->setSubredditId($subreddit->getIncremented());
     $user_subreddit_membership->setMembership($membership);
     $user_subreddit_membership->save();
     $second_user_subreddit_membership = new sfGuardUserSubredditMembership();
     $second_user_subreddit_membership->setSfGuardUserId($user->getIncremented());
     $second_user_subreddit_membership->setSubredditId($subreddit->getIncremented());
     $second_user_subreddit_membership->setMembership($second_membership);
     $exception_thrown = false;
     try {
         $second_user_subreddit_membership->save();
     } catch (Exception $exception) {
         unset($exception);
         $exception_thrown = true;
     }
     $retrieved_object = sfGuardUserSubredditMembershipTable::getInstance()->getFirstByUserSubredditAndMemberships($user->getIncremented(), $subreddit->getIncremented(), array($membership->getType()));
     $this->assertEquals($retrieved_object->getIncremented(), $user_subreddit_membership->getIncremented());
     $user_subreddit_membership->delete();
     $subreddit->delete();
     $user->delete();
     $this->assertTrue($exception_thrown);
 }
 /**
  * Creates an empty sfGuardUser with profile field Facebook UID set
  *
  * @param Integer $facebook_uid
  * @return sfGuardUser
  * @author fabriceb
  * @since 2009-05-17
  * @since 2009-08-11 ORM-agnostic version
  */
 public function createSfGuardUserWithFacebookUidAndCon($facebook_uid, $con)
 {
     $sfGuardUser = new sfGuardUser();
     $sfGuardUser->setUsername('Facebook_' . $facebook_uid);
     $this->setUserFacebookUid($sfGuardUser, $facebook_uid);
     sfFacebookConnect::newSfGuardConnectionHook($sfGuardUser, $facebook_uid);
     // Save them into the database using a transaction to ensure a Facebook sfGuardUser cannot be stored without its facebook uid
     try {
         if (method_exists($con, 'begin')) {
             $con->begin();
         } else {
             $con->beginTransaction();
         }
         $sfGuardUser->save();
         $sfGuardUser->getProfile()->save();
         $con->commit();
     } catch (Exception $e) {
         $con->rollback();
         throw $e;
     }
     $this->setDefaultPermissions($sfGuardUser);
     return $sfGuardUser;
 }
Exemple #25
0
 /**
  * Updates the values of the object with the cleaned up values.
  *
  * @param  array $values An array of values
  *
  * @return BaseObject The current updated object
  */
 public function updateObject($values = null)
 {
     parent::updateObject($values);
     $guard_user = $this->getObject()->getSfGuardUser();
     if (!is_null($guard_user)) {
         /* changed password? */
         if (isset($values['password']) && !empty($values['password'])) {
             $guard_user->setPassword($values['password']);
         }
     } else {
         if (isset($values['password']) && !empty($values['password']) && isset($values['username']) && !empty($values['username'])) {
             $guard_user = new sfGuardUser();
             $guard_user->setUsername($values['username']);
             $guard_user->setPassword($values['password']);
             $this->getObject()->setSfGuardUser($guard_user);
         }
         if (isset($values['delete_photo'])) {
             $this->getObject()->deleteImage();
         }
     }
     return $this->getObject();
 }
 /**
  * We've combined the process for preventing saving with a specific call for
  * deletion to aid in handling errors and dealing with unsaved objects.
  * This tests whether the exception is thrown
  */
 public function testdeleteWithException()
 {
     $subreddit = new Subreddit();
     $subreddit->setName(rand(0, 10000));
     $subreddit->setDomain(rand(0, 10000));
     $subreddit->save();
     $user = new sfGuardUser();
     $user->setUsername(rand(0, 10000));
     $user->setEmailAddress(rand(0, 10000));
     $user->setIsValidated(1);
     $user->save();
     $first = AuthorTypeTable::getInstance()->findOneByType('squid');
     $episode = new Episode();
     $episode->setReleaseDate(date('Y-m-d H:i:s', time() + 100000));
     $episode->setSubreddit($subreddit);
     $episode->save();
     $deadline = new Deadline();
     $deadline->setSubreddit($subreddit);
     $deadline->setAuthorType($first);
     $deadline->setSeconds(0);
     $deadline->save();
     $assignment = new EpisodeAssignment();
     $assignment->setSfGuardUser($user);
     $assignment->setEpisode($episode);
     $assignment->setAuthorType($first);
     $assignment->save();
     // Delete with exception
     $exception_thrown = false;
     $exception_code = 987654321;
     try {
         $assignment->deleteWithException("Test exception", $exception_code);
     } catch (sfException $exception) {
         $this->assertEquals($exception_code, $exception->getCode());
         unset($exception);
         $exception_thrown = true;
     }
     $this->assertTrue($exception_thrown);
     // Delete the rest of the objects
     $episode->delete();
     $user->delete();
     $subreddit->delete();
 }
// create a new test browser
$browser = new sfTestBrowser();
$browser->initialize();
// start tests
$t = new lime_test(9, new lime_output_color());
// these tests check for the comments attachement consistency
$t->diag('start tests');
// objects creation
$object1 = _create_object();
$object1->setName('one');
$object1->save();
$object2 = _create_object();
$object2->setName('two');
$object2->save();
$user1 = new sfGuardUser();
$user1->setUsername('one');
$user1->save();
$t->ok(is_numeric($object1->getRecommendationScore()), 'getRecommendationScore() returns numeric value');
$t->is($object1->getRecommendationScore(), 0, 'getRecommendationScore() object 1 score initialized : 0');
$t->ok($object1->recommend(), 'recommend() object 1');
$t->is($object1->getRecommendationScore(), 1, 'getRecommendationScore() object 1 score updated : 1');
$object2->recommend();
$object2->recommend();
$object2->recommend();
$t->is($object1->getRecommendationScore(), 1, 'getRecommendationScore() object 1 score not updated : 1');
$t->is($object2->getRecommendationScore(), 3, 'getRecommendationScore() object 2 score updated : 3');
$t->ok($object1->recommend($user1->getPrimaryKey()), 'recommend() a user can recommend object 1 once');
$t->ok(!$object1->recommend($user1->getPrimaryKey()), 'recommend() a user cannot recommend object 1 twice');
$t->ok($object2->recommend($user1->getPrimaryKey()), 'recommend() a user can recommend object 2');
// test object creation
function _create_object()
 public function transformJobs()
 {
     $statusHash = array();
     $statusObjects = StatusPeer::doSelect(new Criteria());
     foreach ($statusObjects as $s) {
         $statusHash[$s->getState()] = $s->getId();
     }
     $this->jobKeys = array();
     $dom = DOMDocument::load("tuftsph_jm2db.xml");
     $jobs = $dom->getElementsByTagName("jobs");
     $total = $jobs->length;
     $count = 1;
     $jobList = array();
     foreach ($jobs as $job) {
         $jid = 0;
         $childNodes = $job->childNodes;
         $j = new Job();
         $del = new Delivery();
         $jid = 1;
         $startTime = null;
         $shootStart = null;
         $shootEnd = null;
         $endTime = null;
         $notes = "";
         $photog = 0;
         $slug = "";
         $childNodes = $job->childNodes;
         foreach ($childNodes as $child) {
             switch ($child->nodeName) {
                 case "id":
                     $jid = $child->textContent;
                     break;
                 case "shoot_name":
                     $j->setEvent($child->textContent);
                     break;
                 case "shoot_date":
                     $j->setDate($child->textContent);
                     break;
                 case "shoot_startT":
                     $startTime = $child->textContent;
                     break;
                 case "shoot_start":
                     $shootStart = $child->textContent;
                     break;
                 case "shoot_endT":
                     $endTime = $child->textContent;
                     break;
                 case "shoot_end":
                     $shootEnd = $child->textContent;
                     break;
                 case "shoot_duedate":
                     $j->setDueDate($child->textContent);
                     break;
                 case "submitted_at":
                     $j->setCreatedAt($child->textContent);
                     break;
                 case "requester_address":
                     $j->setStreet($child->textContent);
                     break;
                 case "requester_campus":
                     $j->setCity($child->textContent);
                     break;
                 case "requester_name":
                     $j->setContactName($child->textContent);
                     break;
                 case "requester_email":
                     $j->setContactEmail($child->textContent);
                     break;
                 case "requester_phone":
                     $j->setContactPhone($child->textContent);
                     break;
                 case "internal_notes":
                     $notes .= $child->textContent . "<br/>";
                     break;
                 case "billing_notes":
                     $notes .= $child->textContent . "<br/>";
                     break;
                 case "estimate":
                     $j->setEstimate($child->textContent);
                     break;
                 case "billing_acctnum":
                     $j->setAcctNum($child->textContent);
                     break;
                 case "billing_deptid":
                     $j->setDeptId($child->textContent);
                     break;
                 case "billing_grantid":
                     $j->setGrantId($child->textContent);
                     break;
                 case "shoot_directions":
                     $j->setOther($child->textContent);
                     break;
                 case "status":
                     $j->setStatusId($statusHash[$child->textContent]);
                     break;
                 case "photog_id":
                     $photog = $child->textContent;
                     break;
                 case "delivery_pubname":
                     $del->setPubName($child->textContent);
                     break;
                 case "delivery_pubtype":
                     $del->setPubType($child->textContent);
                     break;
                 case "delivery_other":
                     $del->setOther($child->textContent);
                     break;
                 case "delivery_format":
                     break;
                 case "delivery_color":
                     $del->setColor($child->textContent);
                     break;
                 case "delivery_format":
                     $del->setFormat($child->textContent);
                     break;
                 case "delivery_size":
                     $del->setSize($child->textContent);
                     break;
                 case "delivery_method":
                     $del->setMethod($child->textContent);
                     break;
                 case "delivery_special":
                     $del->setInstructions($child->textContent);
                     break;
                 case "slug":
                     $slug = $child->textContent;
                     break;
                 case "#text":
                 default:
                     break;
             }
         }
         if (is_null($endTime)) {
             $endTime = $shootEnd;
         }
         if (is_null($startTime)) {
             $startTime = $shootStart;
         }
         if ($j->getCity() == "Boston") {
             $j->setZip("02101");
         } else {
             $j->setZip("02155");
         }
         $j->setNotes($notes);
         $j->setState("Massachusetts");
         list($hour, $min, $sec) = explode(":", $endTime);
         list($shour, $smin, $ssec) = explode(":", $startTime);
         $t = new DateTime();
         $t->setTime($hour, $min, $sec);
         $j->setEndTime($t);
         $t = new DateTime();
         $t->setTime($shour, $smin, $ssec);
         $j->setStartTime($t);
         $j->addTag($slug);
         if (isset($this->jobProjectKeys[$jid])) {
             $j->setProjectId($this->projectKeys[$this->jobProjectKeys[$jid]]);
         }
         while (count($jobList) - 1 != $jid) {
             $jobList[] = false;
         }
         $jobList[intval($jid)] = array("job" => $j, "del" => $del, "photog" => $photog);
     }
     for ($i = 1; $i < count($jobList); $i++) {
         sleep(1);
         $obj = $jobList[$i];
         $c = new Criteria();
         $c->add(JobPeer::ID, $i);
         if (JobPeer::doCount($c) > 0) {
             continue;
         }
         echo $i . "/" . $total . "\n";
         // keep the ids lined up
         if ($obj == false) {
             $myJob = new Job();
             try {
                 $myJob->save();
             } catch (Exception $ex) {
                 echo $ex->getMessage();
             }
             $myJob->delete();
         } else {
             $j = $obj["job"];
             $del = $obj["del"];
             $photog = $obj["photog"];
             try {
                 $j->save();
             } catch (Exception $ex) {
                 echo $ex->getMessage();
                 echo $ex->getTraceAsString();
             }
             $del->setJobId($j->getId());
             $del->save();
             $this->jobKeys[$jid] = $j->getId();
             if ($photog) {
                 $jp = new JobPhotographer();
                 $jp->setPhotographerId($this->photogKeys[$photog]);
                 $jp->setJobId($j->getId());
                 try {
                     $jp->save();
                 } catch (Exception $ex) {
                     echo $ex->getMessage();
                 }
             }
             // add the requester as a client
             $c = new Criteria();
             $c->add(sfGuardUserPeer::USERNAME, $j->getContactEmail());
             if (ClientPeer::doCount($c) == 0 && trim(strlen($j->getContactEmail())) != 0) {
                 $user = new sfGuardUser();
                 $user->setUsername($j->getContactEmail());
                 $user->setPassword("admin");
                 $user->save();
                 $userProfile = new sfGuardUserProfile();
                 $userProfile->setUserId($user->getId());
                 $userProfile->setUserTypeId(sfConfig::get("app_user_type_client"));
                 $userProfile->save();
                 $clientProfile = new Client();
                 $clientProfile->setUserId($userProfile->getId());
                 $clientProfile->setName($j->getContactName());
                 $clientProfile->setEmail($j->getContactEmail());
                 $clientProfile->setPhone($j->getContactPhone());
                 $clientProfile->save();
                 $jobClient = new JobClient();
                 $jobClient->setClientId($clientProfile->getId());
                 $jobClient->setJobId($j->getId());
                 $jobClient->save();
             }
         }
         $count += 1;
     }
 }
Exemple #29
0
 public function executeRegister()
 {
     $campus = CampusPeer::retrieveByEmail($this->getRequestParameter('register_email'));
     $department = DepartmentPeer::retrieveByUuid($this->getRequestParameter('department'));
     //$subdepartment = SubdepartmentPeer::retrieveByName('cognitive neuroscience');
     if ($campus == null) {
         $campus = CampusPeer::retrieveByEmail("@public");
         $this->logMessage("Campus was null, now set to ({$campus})");
     }
     $this->forward404Unless($campus, 'campus not found');
     $this->forward404Unless($department, 'department not found');
     //$this->forward404Unless($subdepartment, 'subdepartment not found');
     $user = new sfGuardUser();
     // TODO: Implement form validation in validate.yml
     $user->setUsername($this->getRequestParameter('register_email'));
     $user->setPassword($this->getRequestParameter('register_password'));
     $user->save();
     $this->user = $user->toArray();
     $this->logMessage('USER_ARRAY: ' . print_r($this->user, true));
     $this->username = $this->user['Username'];
     $this->logMessage('USER_NAME_VAR: ' . $this->username);
     sfPropelApprovableBehavior::disable();
     $this->getRequest()->setAttribute('user_id', $user->getId());
     $this->logMessage('Set user_id in attributes: [' . $user->getId() . ']:[' . $this->getRequest()->getAttribute('user_id') . ']');
     //$temp_email = $this->sendEmail('messages', 'confirmRegistrationEmail');
     // Generate a UUID for the user profile, done upon saving it
     $profile = $user->getProfile();
     $profile->setUserId($user->getId());
     $profile->setCampusId($campus->getId());
     $profile->setDepartmentId($department->getId());
     $profile->setFirstName($this->getRequestParameter('first_name'));
     $profile->setLastName($this->getRequestParameter('last_name'));
     $profile->setNoPicture();
     $profile->setTitle('student');
     $profile->setGender(sfConfig::get('app_profile_unknown'));
     //$profile->setSubdepartmentId($subdepartment->getId());
     $profile->save();
     $profile->getPrimaryContactInfo();
     $profile->addHistoryEvent($profile->getFullName() . ' has joined the Cothink community.', "We would like to welcome you to Cothink, we know you'll work to make the world a better place!");
     $profile->addKarma(sfConfig::get('app_karma_join_site_points'));
     //    $register_email = $this->sendEmail('messages', 'sendConfirmRegistrationEmail');
     sfPropelApprovableBehavior::disable();
     $this->user = sfGuardUserPeer::retrieveByUsername('*****@*****.**');
     /*
     $this->logMessage("Sending email confirmation");
     $conn = new Swift_Connection_SMTP( sfConfig::get('mod_sfswiftmailer_smtp_host', 'localhost') );
     
     // Need auth for SMTP
     $conn->setUsername( sfConfig::get('mod_sfswiftmailer_smtp_user') );
     $conn->setPassword( sfConfig::get('mod_sfswiftmailer_smtp_pass') );
     
     $mailer = new Swift($conn);
     
     // Get our message bodies
     $htmlBody = $this->getPresentationFor('messages', 'confirmRegistrationHtml');
     $textBody = $this->getPresentationFor('messages', 'confirmRegistrationText');
     
       //Create a message
       $message = new Swift_Message("Thank you for joining the Cothink community. Please confirm your email address to complete registration.");
       
       //Add some "parts"
       $message->attach(new Swift_Message_Part($textBody));
       $message->attach(new Swift_Message_Part($htmlBody, "text/html"));
     
     // Send out our mailer
     $mailer->send($message, $this->username, '*****@*****.**');
     $mailer->disconnect();
     $this->logMessage("Email confirmation sent");
     //return sfView:: SUCCESS;
     */
     //return $this->redirect('user/pleaseConfirm?user='******'Username']));
     return $this->redirect("@show_user_profile?user=" . $profile->getUuid());
 }
Exemple #30
0
 protected function processOrganizerForm(sfWebRequest $request, sfForm $form)
 {
     //$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
     if ($form->isValid()) {
         //$form->save();
         $name = $form->getValue('name');
         $email = $form->getValue('email');
         //$colour = $form->getValue('colour_code');
         $guard_user = new sfGuardUser();
         $guard_user->setEmailAddress($email);
         $guard_user->setUsername($email);
         $guard_user->setPassword($form->getValue('password'));
         $guard_user->setIsActive(1);
         $guard_user->save();
         $organizer = new Organizer();
         $organizer->setName($name);
         $organizer->setSfGuardId($guard_user->getId());
         //$organizer->setColourCode($colour);
         $organizer->save();
         $this->redirect('organize/new');
     }
 }