public function executeSignin($request)
 {
     $user = $this->getUser();
     if ($user->isAuthenticated()) {
         return $this->redirect('@homepage');
     }
     // Create SimpleSAML module
     $simpleSAMLAuth = new SimpleSAML_Auth_Simple('default-sp');
     // If the user is authenticated from the IdP
     if ($simpleSAMLAuth->isAuthenticated()) {
         $attributes = $simpleSAMLAuth->getAttributes();
         // save the referer
         $user_referer = $user->getReferer($request->getReferer());
         // Try to find the user with his uid
         $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')->where('u.username = ?', $attributes['eduPersonPrincipalName'][0]);
         // If the sGuardUser already exists in the database, it's OK
         if ($query->count() >= 1) {
             $guard_user = $query->fetchOne();
             $guard_user->setEmailAddress($attributes['mail'][0]);
             $guard_user->setLastName($attributes['cn'][0]);
             $guard_user->save();
         } else {
             // the user doesn't exist, we create a new one with random password
             $guard_user = new sfGuardUser();
             $guard_user->setUsername($attributes['eduPersonPrincipalName'][0]);
             $guard_user->setPassword(md5(microtime() . $attributes['eduPersonPrincipalName'][0] . mt_rand()));
             $guard_user->setEmailAddress($attributes['mail'][0]);
             $guard_user->setLastName($attributes['cn'][0]);
             $guard_user->setIsActive(true);
             $guard_user->save();
         }
         // Let the User signin
         // The auth is not rembered : the IdP can decide that
         $this->getUser()->signin($guard_user, $remember = false);
         // always redirect to a URL set in app.yml
         // or to the referer
         // or to the homepage
         $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user_referer);
         return $this->redirect('' != $signinUrl ? $signinUrl : '@homepage');
     } else {
         if ($request->isXmlHttpRequest()) {
             $this->getResponse()->setHeaderOnly(true);
             $this->getResponse()->setStatusCode(401);
             return sfView::NONE;
         }
         // if we have been forwarded, then the referer is the current URL
         // if not, this is the referer of the current request
         $user->setReferer($this->getContext()->getActionStack()->getSize() > 1 ? $request->getUri() : $request->getReferer());
         /* gyufi $this->url_idp = $simpleSAMLAuth->login(array(
              //'saml:idp' => 'https://openidp.feide.no',
              'saml:idp' => 'https://aai.sztaki.hu/idp-partners',
              'saml:idp' => 'https://aai.sztaki.hu/idp',
            ));
            */
         $this->url_idp = $simpleSAMLAuth->login();
         // Nothing happened after there, $simpleSAMLAuth->login() calls exit()
         /*
               $module = sfConfig::get('sf_login_module');
               if ($this->getModuleName() != $module)
               {
                 return $this->redirect($module.'/'.sfConfig::get('sf_login_action'));
               }
         
               $this->getResponse()->setStatusCode(401);
         */
     }
 }
Beispiel #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 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']));
 }
 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);
 }
 /**
  * @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']));
 }
 /**
  * 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');
 }
 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;
 }
Beispiel #8
0
 /**
  * @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']));
 }
 /**
  * @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);
 }
Beispiel #11
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';
         }
     }
 }
Beispiel #12
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;
 }
 protected function create_sf_user($fbProfile)
 {
     try {
         //die('creating');
         //doctrine, create record in sf_guard_user
         $NewFacebookUser = new sfGuardUser();
         $NewFacebookUser->first_name = $fbProfile['first_name'];
         $NewFacebookUser->last_name = $fbProfile['last_name'];
         $NewFacebookUser->email_address = $fbProfile['email'];
         $NewFacebookUser->username = $fbProfile['email'];
         $NewFacebookUser->save();
         $NewFacebookUser->setPassword('test');
         $NewFacebookUser->save();
         //get id
         $id = $NewFacebookUser->getId();
         //this part has been replace with a mysql trigger
         /*
                     //ensure id isn't already used, autoincremenet problem
                     $q = Doctrine_Query::create()
                     ->select("*")
                     ->from("RidAccounts")
                     //->where("email = ?", $this->user->getEmailAddress())
                     ->where("id = ?", $id)    
                     ->setHydrationMode(Doctrine::HYDRATE_ARRAY);
         
                     $results = $q->execute();
         
                     if(count($results) > 0) { die('id already used' . __LINE__ . __FILE__); }
                     
                     
                     //doctrine, create record in RidAccounts
                     $NewFacebookUserAccount = new RidAccounts();
                     $NewFacebookUserAccount->id = $id;
                     $NewFacebookUserAccount->first_name = $fbProfile['first_name'];
                     $NewFacebookUserAccount->last_name = $fbProfile['last_name'];
                     $NewFacebookUserAccount->email = $fbProfile['email'];
                     $NewFacebookUserAccount->save();
         */
         return $id;
     } catch (Exception $e) {
         echo $e->getType() . "<br />";
         echo $e->getMessage() . "<br />";
         sfContext::getInstance()->getLogger()->debug($e->getType());
         sfContext::getInstance()->getLogger()->debug($e->getMessage());
         die(__FILE__ . __LINE__);
     }
 }
Beispiel #14
0
 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();
     }
 }
 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());
         }
     }
 }
Beispiel #18
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();
 }
Beispiel #19
0
 protected function doSave($con = null)
 {
     //--------------------------------------------------------------------------
     // populate objects related to ReservationForm & ClientForm with posted data
     //--------------------------------------------------------------------------
     $this->updateObject();
     //--------------------------------------------------------------------------
     // get populated reservation object
     //--------------------------------------------------------------------------
     $reservation = $this->getObject();
     //--------------------------------------------------------------------------
     // if it's a new reservation we have to make sure to detect existing clients
     // and retrieve their client id if it's the case
     //--------------------------------------------------------------------------
     if ($this->isNew()) {
         if (isset($this->embeddedForms['client'])) {
             //----------------------------------------------------------------------
             // check if the client exists, if not, save and get new client id
             //----------------------------------------------------------------------
             $values = $this->getValue('client');
             if (null == ($client = Doctrine::getTable('Client')->getByEmail($values['email_address']))) {
                 //--------------------------------------------------------------------
                 // create login user
                 //--------------------------------------------------------------------
                 $sfGuardUser = new sfGuardUser();
                 $sfGuardUser->first_name = $values['firstname'];
                 $sfGuardUser->last_name = $values['lastname'];
                 $sfGuardUser->username = $values['email_address'];
                 $sfGuardUser->email_address = $values['email_address'];
                 $sfGuardUser->setPassword('admin');
                 $sfGuardUser->setIsActive(true);
                 $sfGuardUser->save();
                 //--------------------------------------------------------------------
                 // save object related to ClientForm
                 //--------------------------------------------------------------------
                 $client = $this->embeddedForms['client']->object;
                 $client->sf_guard_user_id = $sfGuardUser->id;
                 $client->save();
             }
             $reservation->client_id = $client->id;
         } else {
             $reservation->client_id = $this->getOption('client_id');
         }
         //------------------------------------------------------------------------
         // add the uniqe confirmation id and set initial status
         //------------------------------------------------------------------------
         $reservation->uniqid = 'pending';
         $reservation->status = 'open';
         $reservation->firstname = $values['firstname'];
         $reservation->lastname = $values['lastname'];
     } else {
         // triggered only when updating reservations
         self::$dispatcher->notify(new sfEvent($reservation, 'reservation.pre_update'));
     }
     //--------------------------------------------------------------------------
     // the price depends on destination, round_trip and no_pax
     //--------------------------------------------------------------------------
     $reservation->price = Doctrine::getTable('Transfer')->getPrice($reservation->destination_id, $reservation->round_trip, $reservation->no_pax);
     $reservation->save();
     $reservation->uniqid = strtoupper(base_convert((int) sprintf('1%07d', $reservation->id), 10, 36));
     $reservation->save();
     self::$dispatcher->notify(new sfEvent($reservation, $this->isNew() ? 'reservation.created' : 'reservation.post_update'));
 }
Beispiel #20
0
 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;
     }
 }
Beispiel #21
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());
 }
Beispiel #22
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');
     }
 }
 /**
  * Save client profile content
  * @param web request $request
  */
 public function executeUpdate($request)
 {
     /**login user infomation**/
     $sf_user = $this->getUser();
     $sf_guard_user = $sf_user->getGuardUser();
     $sf_user_profile = $sf_guard_user->getProfile();
     $sf_user_id = $sf_guard_user->getId();
     $branch_id = $sf_user->getUserBranch()->getId();
     $company_id = $sf_user->getUserCompany()->getId();
     $this->marketing_options = '';
     $this->cop_record_updated = '';
     $client_user_id = NULL;
     //    if($sf_ser->isBranchOwner($sf_user_id) && $sf_user->hasAttribute('branch_id'))
     if ($sf_user->isBranchOwner($sf_user_id)) {
         //        $client_user_id = $this->getRequestParameter('id');
         $client_profile_id = $this->getRequestParameter('id');
         if (!empty($client_profile_id)) {
             $client_user = ProfilePeer::retrieveByPK($client_profile_id);
             $client_user_id = $client_user->getUserId();
         }
         /*
          * available in case branch owner is handling more than branch
          * if the client is new that it need branch_id from url
          */
         if ($this->getRequestParameter('branch_id')) {
             $branch_id = $this->getRequestParameter('branch_id');
         } elseif ($client_user_id) {
             $client_branch = new Criteria();
             $client_branch->add(BranchUsersPeer::USER_ID, $client_user_id);
             $client_branch->setDistinct();
             $branchId = BranchUsersPeer::doSelect($client_branch);
             $branch_id = $branchId[0]->getBranchId();
         }
         $company_id = BranchPeer::getCompanyId($branch_id);
     }
     $parent = $request->getParameter('opportunity_parent_exist', 0);
     $this->logindetails = array();
     $this->logindetails['username'] = '';
     $this->logindetails['password'] = '';
     $this->logindetails['confirm_password'] = '';
     $this->logindetails['budget'] = '';
     $this->logindetails['expected_close_date'] = '';
     $this->getSignedContractDate = '';
     $this->another_contact_list = '';
     $this->another_contact_form = new anotherContactPersonForm();
     $this->client_leads = ClientLeadPeer::getClientLeadsList($branch_id);
     $login_details = $request->getParameter('logindetail');
     $branch_service = new BranchService($branch_id, $sf_user_id);
     $this->marketing_options = $branch_service->getMarketingOptionList();
     $this->is_showlead = $branch_service->isShowLead();
     $this->sub_opportunity_exist = null;
     if ($login_details) {
         $this->logindetails = $login_details;
         if ($this->logindetails['expected_close_date']) {
             $this->logindetails['expected_close_date'] = date('Y-m-d', strtotime($this->logindetails['expected_close_date'])) . ' ' . date('H:i:s');
         }
     }
     $this->getSignedContractDate = $this->logindetails['signed_contract_date'];
     /*
      * get current branch branch office staff list (any one of these should be the sales person)
      */
     $tempsale = array();
     $tempsale[$sf_user_id] = $sf_user->getProfile()->getFullname();
     $sales = ProfilePeer::getBranchUsers($branch_id, sfGuardGroupPeer::BRANCH_OFFICE_STAFF);
     foreach ($sales as $salesid) {
         $tempsale[$salesid->getUserId()] = $salesid->getFullname();
     }
     $this->sales_persons = $tempsale;
     $this->default_sales = $sf_user_id;
     $client_profile = '';
     $this->client_profile = '';
     $client_id = $request->getParameter('id');
     if ($client_id) {
         $client_profile = ProfilePeer::retrieveByPK($client_id);
         $client_user_id = $client_profile->getUserId();
         $this->client_ranks = clientRankPeer::getClientOpportunityList($branch_id);
         $this->default_rank = 0;
         $this->default_sub_rank = null;
         $this->default_lead = 0;
         if (!empty($client_profile)) {
             $this->default_rank = $client_profile->getRank() ? $client_profile->getRank() : 0;
             $this->default_sub_rank = $client_profile->getSubOpportunity() ? $client_profile->getSubOpportunity() : null;
         }
         $this->client_profile = $client_profile;
         if ($client_profile->getOther2() == '') {
             $ref = $this->genRandomString();
             $client_profile->setOther2($ref);
         }
         $this->form = new ClientQuickForm($client_profile);
         $client_login = sfGuardUserPeer::retrieveByPK($client_user_id);
         $this->client_login = $client_login;
         $c = new Criteria();
         $c->add(anotherContactPersonPeer::USER_ID, $client_user_id, Criteria::EQUAL);
         $this->another_contact_list = anotherContactPersonPeer::doSelect($c);
     } else {
         $ref = $this->genRandomString();
         $this->form = new ClientQuickForm();
         $this->form->setDefault('other2', $ref);
         $this->client_ranks = clientRankPeer::getClientOpportunityList($branch_id);
         $this->default_rank = 0;
         $this->default_sub_rank = null;
         $this->default_lead = 0;
         if (!empty($client_profile)) {
             $this->default_rank = $client_profile->getSubOpportunity() ? $client_profile->getSubOpportunity() : $client_profile->getRank();
             $this->default_lead = $client_profile->getLead();
         }
     }
     /*
      * save data to database
      */
     if ($request->isMethod('post')) {
         $form_data = $request->getParameter('profile');
         $prefered = null;
         if ($request->getParameter('preferedPhone')) {
             $prefered = $request->getParameter('preferedPhone');
         } elseif ($request->getParameter('preferedAfterHourPhone')) {
             $prefered = $request->getParameter('preferedAfterHourPhone');
         } elseif ($request->getParameter('preferedMobile')) {
             $prefered = $request->getParameter('preferedMobile');
         }
         $form_data['updated_at'] = date('Y-m-d H:i:s');
         $form_data['updated_by_id'] = $sf_user_id;
         $form_data['prefered_contact'] = $prefered;
         $form_data['user_id'] = $client_user_id;
         $sales_id = $form_data['sales_id'];
         if (!$sales_id) {
             $form_data['sales_id'] = $sf_user_id;
         } else {
             $form_data['sales_id'] = $sales_id;
         }
         if ($parent) {
             $sub_opportunity = $form_data['rank'];
             $sub_opportunities = SubOpportunityPeer::retrieveByPK($sub_opportunity);
             $opportunities = clientRankPeer::retrieveByPK($sub_opportunities->getOpportunityId());
             $form_data['rank'] = $opportunities->getRankId();
             $form_data['sub_opportunity'] = $sub_opportunity;
             if ($opportunities->getRankId() == 7) {
                 $form_data['lead'] = ClientLeadPeer::getBranchLostId($branch_id);
             }
         } else {
             $form_data['sub_opportunity'] = null;
         }
         $client_rank = $form_data['rank'] - 1;
         $this->project = null;
         if ($client_rank == 5) {
             $c = new Criteria();
             $c->add(pmProjectsPeer::CLIENT_ID, $client_user_id);
             $c->addDescendingOrderByColumn(pmProjectsPeer::CREATED_AT);
             $this->project = pmProjectsPeer::doSelectOne($c);
         }
         $this->form->bind($form_data);
         if ($this->form->isValid()) {
             $status = sfConfig::get('mod_client_opportunity_accountstatus');
             $form_data['account_status'] = accountStatusPeer::getStatusId($status[$client_rank]) + 1;
             if ($this->form->isNew()) {
                 $form_data['created_by_id'] = $sf_user_id;
                 $form_data['created_at'] = date('Y-m-d H:i:s');
                 $form_data['updated_at'] = date('Y-m-d H:i:s');
                 $form_data['updated_by_id'] = $sf_user_id;
                 /*
                  *  save client instance into sfguard
                  */
                 $sf_object = new sfGuardUser();
                 $tools_obj = new myTools();
                 /*
                  * login infomation
                  */
                 if (!array_key_exists('username', $login_details) || !$login_details['username']) {
                     $client_username = $tools_obj->RandomUsernameGenerator();
                     $sf_object->setUsername($client_username);
                 } else {
                     $sf_object->setUsername($login_details['username']);
                 }
                 if (!array_key_exists('password', $login_details) || !$login_details['password']) {
                     $sf_object->setPassword($tools_obj->randomPasswordGenerator());
                 } else {
                     $sf_object->setPassword($login_details['username']);
                 }
                 $sf_object->save();
                 $sf_object->addGroupByName('client');
                 $new_user_id = $sf_object->getId();
                 $form_data['user_id'] = $new_user_id;
                 $enquiry_details = new Inquiry();
                 $enquiry_details->setUserId($new_user_id);
                 if ($login_details['budget'] != '') {
                     $enquiry_details->setBudget($login_details['budget']);
                 }
                 if ($login_details['expected_close_date'] != '') {
                     $enquiry_details->setExpectedCloseDate(date('Y-m-d', strtotime($login_details['expected_close_date'])));
                 } elseif ($login_details['expected_close_date'] == '') {
                     $enquiry_details->setExpectedCloseDate(date('Y-m-d', strtotime(date('Y-m-01') . ' +6 month')));
                 }
                 $enquiry_details->save();
                 /*
                  *  save instance into branch users
                  */
                 $branch_object = new BranchUsers();
                 $branch_object->addBranchUser($new_user_id, $branch_id);
                 // set intance into company users
                 $company_object = new CompanyUsers();
                 $company_object->addCompanyUser($new_user_id, $company_id);
             } else {
                 $enquiry_id = InquiryPeer::getEnquiryId($client_user_id);
                 $enquiry_details = InquiryPeer::retrieveByPK($enquiry_id);
                 if ($enquiry_details) {
                     $enquiry_details->setBudget($login_details['budget']);
                     $enquiry_details->setExpectedCloseDate(date('Y-m-d', strtotime($login_details['expected_close_date'])));
                     $enquiry_details->save();
                 } else {
                     $enquiry_details = new Inquiry();
                     $enquiry_details->setUserId($client_login->getId());
                     if ($login_details['budget'] != '') {
                         $enquiry_details->setBudget($login_details['budget']);
                     }
                     if ($login_details['expected_close_date'] != '') {
                         $enquiry_details->setExpectedCloseDate(date('Y-m-d', strtotime($login_details['expected_close_date'])));
                     }
                     $enquiry_details->save();
                 }
                 if ($client_login) {
                     $client_login->setUsername($this->logindetails['username']);
                     if ($this->logindetails['password'] != '') {
                         $client_login->setPassword($this->logindetails['password']);
                     }
                     $client_login->save();
                     $new_user_id = $client_login->getId();
                 }
             }
             if ($login_details['signed_contract_value'] != '') {
                 $conn = Propel::getConnection();
                 //                    need update only one record in the furture
                 $cor = new Criteria();
                 $cor->add(pmProjectsPeer::CLIENT_ID, $client_user_id);
                 $cor->addDescendingOrderByColumn(pmProjectsPeer::CREATED_AT);
                 $cor_new = new Criteria();
                 $cor_new->add(pmProjectsPeer::ACTUAL_BUILD_COST, $login_details['signed_contract_value']);
                 $cor_new->add(pmProjectsPeer::UPDATED_BY_ID, $sf_user_id);
                 $cor_new->add(pmProjectsPeer::UPDATED_AT, date('Y-m-d H:i:s'));
                 BasePeer::doUpdate($cor, $cor_new, $conn);
             }
             /*
              * save the form to profile
              */
             $profile = $this->form->save();
             $profile->setUserId($new_user_id ? $new_user_id : $client_user_id);
             $profile->save();
             $old_opportunity_id = 0;
             $old_sub_opportunity_id = 0;
             $old_opportunity_id = $this->default_rank;
             $old_sub_opportunity_id = $this->default_sub_rank;
             $new_opp_record = false;
             $c_opp_record = new Criteria();
             $c_opp_record->add(ClientOpportunityRecordPeer::USER_ID, $client_user_id);
             if ($old_sub_opportunity_id) {
                 $c_opp_record->add(ClientOpportunityRecordPeer::SUB_OPPORTUNITY_ID, $old_sub_opportunity_id, Criteria::IN);
                 $opportunity_records = ClientOpportunityRecordPeer::doSelect($c_opp_record);
             } elseif ($old_opportunity_id) {
                 $c_opp_record->add(ClientOpportunityRecordPeer::OPPORTUNITY_ID, $old_opportunity_id, Criteria::IN);
                 $opportunity_records = ClientOpportunityRecordPeer::doSelect($c_opp_record);
             } else {
                 $opportunity_records = Null;
             }
             if (empty($opportunity_records)) {
                 $new_opp_record = true;
             }
             $new_opportunity_id = $profile->getRank();
             $new_sub_opportunity_id = $profile->getSubOpportunity();
             if ($new_opp_record) {
                 $client_opportunity_record = new ClientOpportunityRecord();
                 $client_opportunity_record->setOpportunityId($new_opportunity_id);
                 $client_opportunity_record->setSubOpportunityId($new_sub_opportunity_id);
                 $client_opportunity_record->setUserId($profile->getUserId());
                 $client_opportunity_record->setCreatedById($sf_user_id);
                 $client_opportunity_record->setUpdatedById($sf_user_id);
                 $client_opportunity_record->save();
             } else {
                 $conn = Propel::getConnection();
                 $client_opportunity_record_criteria = new Criteria();
                 $client_opportunity_record_criteria->add(ClientOpportunityRecordPeer::USER_ID, $profile->getUserId());
                 $client_opportunity_record_criteria->add(ClientOpportunityRecordPeer::OPPORTUNITY_ID, $new_opportunity_id);
                 $client_opportunity_record_criteria->add(ClientOpportunityRecordPeer::SUB_OPPORTUNITY_ID, $new_sub_opportunity_id);
                 $cor_new = new Criteria();
                 if ($new_opportunity_id == 6) {
                     if (!empty($this->getSignedContractDate)) {
                         $signed_updated_date = date('Y-m-d', strtotime($this->getSignedContractDate)) . ' ' . date('H:i:s');
                         $cor_new->add(ClientOpportunityRecordPeer::UPDATED_AT, $signed_updated_date);
                     }
                 } else {
                     $cor_new->add(ClientOpportunityRecordPeer::UPDATED_AT, date('Y-m-d H:i:s'));
                 }
                 $cor_new->add(ClientOpportunityRecordPeer::UPDATED_BY_ID, $sf_user_id);
                 BasePeer::doUpdate($client_opportunity_record_criteria, $cor_new, $conn);
             }
             if ($old_opportunity_id != $new_opportunity_id || $old_sub_opportunity_id != $new_sub_opportunity_id) {
                 $client_opportunity_log = new ClientOpportunityLog();
                 $client_opportunity_log->setUserId($profile->getUserId());
                 $client_opportunity_log->setOpportunityId($new_opportunity_id);
                 $client_opportunity_log->setSubOpportunityId($new_sub_opportunity_id);
                 $client_opportunity_log->setCreatedById($sf_user_id);
                 $client_opportunity_log->save();
             }
             /*
              *  delete record from another contact from current client
              */
             $c = new Criteria();
             $c->add(anotherContactPersonPeer::USER_ID, $profile->getUserId());
             $another = anotherContactPersonPeer::doDelete($c);
             // add record from client
             $another_details = $request->getParameter('contact_person');
             $no_of_fields = 5;
             $count_person_list = count($another_details) / $no_of_fields;
             $j = $no_of_fields;
             for ($i = 0; $i < $count_person_list - 1; $i++) {
                 $fname = $another_details[$j]['fname'];
                 $lname = $another_details[$j + 1]['lname'];
                 if ($fname != '' || $lname != '') {
                     $an_details = new anotherContactPerson();
                     $an_details->setUserId($profile->getUserId());
                     $an_details->setFname($another_details[$j++]['fname']);
                     $an_details->setLname($another_details[$j++]['lname']);
                     $an_details->setPhone($another_details[$j++]['phone']);
                     $an_details->setEmail($another_details[$j++]['email']);
                     $an_details->setMobile($another_details[$j++]['mobile']);
                     $an_details->save();
                 } else {
                     $j = $j + $no_of_fields;
                 }
             }
             if (!$request->getParameter('rdindex')) {
                 $profile_id = $profile->getId();
                 $profile_user_id = $profile->getUserId();
                 // save client details in the activity logs table
                 $modification_message = $this->form->isNew() ? 'Create Profile' : 'Update Profile';
                 $this->saveHistory($modification_message, $profile_user_id);
                 if ($this->form->isNew()) {
                     $reminder = sfConfig::get('mod_client_messages_msg4');
                     $sf_user->setFlash('notice', $reminder);
                     $this->redirect('client/show?id=' . $profile_id);
                 }
                 $client_info = sfConfig::get('mod_client_messages_msg2');
                 $sf_user->setFlash('notice', $client_info);
                 $this->redirect('client/show?id=' . $profile_id);
             }
             $profile_id = $profile->getId();
             $this->redirect('inquiry/edit?id=' . $profile_id);
         }
         if (isset($profile)) {
             $this->sub_opportunity_exist = $profile->getSubOpportunity() ? 1 : 0;
         }
         $this->setTemplate('edit');
     }
 }
Beispiel #24
0
 public function executeSignin($request)
 {
     $this->op = $request->getParameter('op');
     //echo $this->op;
     //die;
     $dialog = $request->getParameter('dialog', false);
     /* IF FB CONNECT */
     if ($this->op == 'fbc' && ($facebook_uid = VoFacebook::getUid())) {
         //echo "FBC";die;
         $c = new Criteria();
         $c->addJoin(SfGuardUserProfilePeer::USER_ID, SfGuardUserPeer::ID);
         $c->add(SfGuardUserProfilePeer::FACEBOOK_UID, $facebook_uid);
         $sfGuardUser = SfGuardUserPeer::doSelectOne($c);
         if (!$sfGuardUser instanceof sfGuardUser) {
             // Comprobación de que no existe ya el usuario con ese username (bug #734)
             $c = new Criteria();
             $c->add(sfGuardUserPeer::USERNAME, 'Facebook_' . $facebook_uid);
             $existingUser = sfGuardUserPeer::doSelectOne($c);
             if ($existingUser) {
                 $existingUser->setUsername('Facebook_' . $facebook_uid . '-' . time());
                 $existingUser->save();
             }
             $sfGuardUser = new sfGuardUser();
             $sfGuardUser->setUsername('Facebook_' . $facebook_uid);
             $sfGuardUser->save();
             $voProfile = $sfGuardUser->getProfile();
             $vanityUrl = SfVoUtil::encodeVanity('Facebook_' . $facebook_uid);
             $voProfile->setFacebookUid($facebook_uid);
             if (!$voProfile->getNombre()) {
                 $data = VoFacebook::getData($voProfile->getFacebookUid());
                 $voProfile->setNombre($data->first_name);
                 $voProfile->setApellidos($data->last_name);
             }
             $c2 = new Criteria();
             $c2->add(SfGuardUserProfilePeer::VANITY, "{$vanityUrl}%", Criteria::LIKE);
             $usuariosLikeMe = SfGuardUserProfilePeer::doSelect($c2);
             $counter = 0;
             foreach ($usuariosLikeMe as $usuarioLikeMe) {
                 if (preg_match("/^Facebook_{$facebook_uid}-([0-9]*)/i", $usuarioLikeMe->getVanity(), $matches)) {
                     $curIdx = $matches[1];
                     if ($curIdx > $counter) {
                         $counter = $curIdx + 1;
                     }
                 } else {
                     $counter++;
                 }
             }
             $voProfile->setVanity("{$vanityUrl}" . ($counter == 0 ? '' : "-{$counter}"));
             $voProfile->setMailsComentarios(0);
             $voProfile->setMailsNoticias(0);
             $voProfile->setMailsContacto(0);
             $voProfile->setMailsSeguidor(0);
             $voProfile->save();
         }
         $this->getUser()->signin($sfGuardUser, false);
         $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $this->getUser()->getReferer('@homepage'));
         $this->redirect($signinUrl);
     }
     /* FI FB CONNECT */
     $this->registrationform = new RegistrationForm();
     $this->signinform = new SigninForm();
     if ($request->isMethod('post') && !$dialog) {
         // Register
         if ($this->op == 'r') {
             $this->registrationform = new RegistrationForm();
             $this->registrationform->bind($request->getParameter('registration'));
             if ($this->registrationform->isValid()) {
                 $user = new sfGuardUser();
                 $user->setUsername($this->registrationform->getValue('username'));
                 $user->setPassword($this->registrationform->getValue('password'));
                 $user->setIsActive(0);
                 $user->setCreatedAt(time());
                 $c = new Criteria();
                 $c->add(sfGuardUserPeer::USERNAME, $user->getUsername());
                 sfGuardUserPeer::doInsert($user);
                 $user = sfGuardUserPeer::doSelect($c);
                 if (count($user) == 1) {
                     $profile = $user[0]->getProfile();
                     $profile->setNombre($this->registrationform->getValue('nombre'));
                     $profile->setApellidos($this->registrationform->getValue('apellidos'));
                     $profile->setPresentacion($this->registrationform->getValue('presentacion'));
                     $profile->setAnonymous($this->registrationform->getValue('anonymous'));
                     $profile->setCodigo(util::generateUID());
                     /* Generar vanity */
                     if ($profile->getVanity() == '') {
                         $vanityUrl = SfVoUtil::encodeVanity($profile->getNombre() . "-" . $profile->getApellidos());
                         $c2 = new Criteria();
                         $c2->add(SfGuardUserProfilePeer::VANITY, "{$vanityUrl}%", Criteria::LIKE);
                         $c2->add(SfGuardUserProfilePeer::ID, $user[0]->getId(), Criteria::NOT_EQUAL);
                         $usuariosLikeMe = SfGuardUserProfilePeer::doSelect($c2);
                         $counter = 0;
                         foreach ($usuariosLikeMe as $usuarioLikeMe) {
                             $counter++;
                         }
                         $profile->setVanity("{$vanityUrl}" . ($counter == 0 ? '' : "-{$counter}"));
                     }
                     /* Fin Generar vanity */
                     sfGuardUserProfilePeer::doInsert($profile);
                     $this->sendWelcome($user[0]);
                     $this->user = $user[0];
                     return "Registered";
                 }
             }
             /*
             else {
                   		$this->getUser()->setFlash('notice_type', 'error', false);
                   		$this->getUser()->setFlash('notice', sfVoForm::getFormNotValidMessage(), false);
             }
             */
         } else {
             $r = new SigninForm();
             $r->bind($request->getParameter('signin'));
             if ($r->isValid()) {
                 $r->addPostValidation();
                 $r->bind($request->getParameter('signin'));
                 if ($r->isValid()) {
                     $this->doSignin($request, $this->op);
                 }
             }
             /*
             	      else {
                   		$this->getUser()->setFlash('notice_type', 'error', false);
                   		$this->getUser()->setFlash('notice', sfVoForm::getFormNotValidMessage(), false);
             }
             */
             $this->signinform = $r;
         }
     }
     $this->title = sfContext::getInstance()->getI18N()->__('Acceso usuarios', array());
     $this->title .= ' - Voota';
     $this->response->setTitle($this->title);
     if ($this->op == 'fb') {
         return 'FB';
     }
 }
Beispiel #25
0
 public function executeJoin($request)
 {
     $userParams = $request->getParameter('user');
     $this->is_invited = false;
     $this->group = $request->getParameter('group');
     if ($this->group && $this->getUser()->isAuthenticated()) {
         $this->redirect('@groupView?name=' . $this->group);
     }
     //if there's an invitation code supplied, it should match an invitation generated by an invite
     if ($code = $request->getParameter('code')) {
         $profile = Doctrine_Query::create()->from('sfGuardUserProfile p')->where('p.invitation_code = ?', $code)->fetchOne();
         if ($profile) {
             $this->is_invited = true;
         }
     }
     if (!$this->is_invited) {
         $profile = new sfGuardUserProfile();
     }
     //if a network name is supplied
     if ($network_name = $request->getParameter('network')) {
         if ($network = LsListTable::getNetworkByDisplayName($network_name)) {
             $profile->home_network_id = $network["id"];
         }
     }
     $this->user_form = new UserJoinForm($profile);
     $this->profile = $profile;
     //if form is posted, validate
     if ($request->isMethod('post')) {
         //bind request params to form
         $captcha = array('recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'), 'recaptcha_response_field' => $request->getParameter('recaptcha_response_field'));
         $userParams = array_merge($userParams, array('captcha' => $captcha));
         $this->user_form->bind($userParams);
         //if public_name is valid, check that it's unique
         $errors = $this->user_form->getErrorSchema()->getErrors();
         if (!isset($errors['public_name'])) {
             $q = LsDoctrineQuery::create()->from('sfGuardUserProfile p')->where('p.public_name LIKE ?', $userParams['public_name']);
             if (in_array($userParams['public_name'], sfGuardUserProfileTable::$prohibitedPublicNames) || $q->count()) {
                 $validatorSchema = $this->user_form->getValidatorSchema();
                 $validatorSchema['public_name']->setMessage('invalid', 'Sorry, the public name you chose is already taken!');
                 $this->user_form->getErrorSchema()->addError(new sfValidatorError($validatorSchema['public_name'], 'invalid'), 'public_name');
             }
         }
         //look for user with duplicate email
         $q = LsDoctrineQuery::create()->from('sfGuardUserProfile p')->where('REPLACE(p.email, \'.\', \'\') = REPLACE(?, \'.\', \'\')', $userParams['email']);
         //if user was invited, the duplicate user shouldn't have the same code
         //if ($code)
         //{
         //  $q->addWhere('p.invitation_code <> ?', $code);
         //}
         if ($q->count()) {
             $request->setError('email', 'There is already a user with that email');
         }
         //proceed if there are no errors
         if ($this->user_form->isValid() && !$request->hasErrors()) {
             //if user is invited, consider user confirmed
             if ($this->is_invited) {
                 $user = $profile->User;
                 $user->is_active = true;
                 $profile->invitation_code = null;
                 $profile->is_visible = true;
                 $profile->is_confirmed = true;
             } else {
                 $user = new sfGuardUser();
                 //auto-approve?
                 $user->is_active = sfConfig::get('app_accounts_auto_approve') ? true : false;
             }
             $db = Doctrine_Manager::connection();
             try {
                 $db->beginTransaction();
                 //save submitted email as password
                 $user->username = $userParams['email'];
                 $user->algorithm = 'sha1';
                 $user->setPassword($userParams['password1']);
                 if (!$user->hasPermission('contributor')) {
                     $user->addPermissionByName('contributor');
                 }
                 if (!$user->hasPermission('editor')) {
                     $user->addPermissionByName('editor');
                 }
                 $user->save();
                 //save submitted profile fields
                 $profile->user_id = $user->id;
                 $profile->name_first = $userParams['name_first'];
                 $profile->name_last = $userParams['name_last'];
                 $profile->email = $userParams['email'];
                 $profile->reason = $userParams['reason'];
                 $profile->analyst_reason = $userParams['analyst_reason'];
                 $profile->public_name = $userParams['public_name'];
                 $profile->home_network_id = $userParams['home_network_id'];
                 //if not invited, generate code for email confirmation
                 if (!$this->is_invited) {
                     $code = substr(sha1($profile->email . time()), 0, 20);
                     $profile->confirmation_code = $code;
                 }
                 $profile->save();
                 //add user to group, if requested
                 if ($this->group) {
                     $db = Doctrine_Manager::connection();
                     $sql = 'SELECT id FROM sf_guard_group WHERE name = ?';
                     $stmt = $db->execute($sql, array($this->group));
                     if ($groupId = $stmt->fetch(PDO::FETCH_COLUMN)) {
                         $ug = new sfGuardUserGroup();
                         $ug->user_id = $user->id;
                         $ug->group_id = $groupId;
                         $ug->is_owner = 0;
                         $ug->save();
                     }
                 }
                 //send email to notify administrator of new account creation
                 $mailBody = $this->getPartial('accountcreatenotify', array('user' => $user, 'analyst' => $userParams['analyst_reason'], 'group' => $this->group));
                 if ($this->is_invited) {
                     $subject = 'LittleSis account invitation accepted by ' . $userParams['name_first'] . ' ' . $userParams['name_last'];
                 } else {
                     $subject = 'LittleSis account ' . ($user->is_active ? 'created' : 'requested') . ' by ' . $userParams['name_first'] . ' ' . $userParams['name_last'];
                 }
                 $mailer = new Swift(new Swift_Connection_NativeMail());
                 $message = new Swift_Message($subject, $mailBody, 'text/plain');
                 $address = new Swift_Address(sfConfig::get('app_mail_join_sender_address'), sfConfig::get('app_mail_join_sender_name'));
                 $mailer->send($message, sfConfig::get('app_mail_join_sender_address'), $address);
                 $mailer->disconnect();
                 //notify user that the account has been created/requested
                 $subject = $user->is_active ? 'Welcome to LittleSis!' : 'Your request to become a LittleSis analyst';
                 $mailBody = $this->getPartial($user->is_active ? 'accountcreatereceipt' : 'accountrequestreceipt', array('user' => $user, 'password' => $userParams['password1'], 'is_invited' => $this->is_invited));
                 $mailer = new Swift(new Swift_Connection_NativeMail());
                 $message = new Swift_Message('Welcome to LittleSis!', $mailBody, 'text/plain');
                 $address = new Swift_Address(sfConfig::get('app_mail_join_sender_address'), sfConfig::get('app_mail_join_sender_name'));
                 $mailer->send($message, $profile->email, $address);
                 $mailer->disconnect();
                 //if invited, sign in user and record login time
                 if ($this->is_invited) {
                     // signin user
                     $this->getUser()->setAttribute('user_id', $user->id, 'sfGuardSecurityUser');
                     $this->getUser()->setAuthenticated(true);
                     $this->getUser()->clearCredentials();
                     $this->getUser()->addCredentials($user->getAllPermissionNames());
                     // save last login
                     $user->last_login = date('Y-m-d H:i:s');
                     $user->save();
                 }
                 //commit changes
                 $db->commit();
             } catch (Exception $e) {
                 $db->rollback();
                 throw $e;
             }
             //redirect to requested or joined page
             if ($user->is_active) {
                 $this->redirect('home/joined' . ($this->is_invited ? '?conf=1' : ''));
             } else {
                 $this->redirect('home/requested');
             }
         }
     }
 }
Beispiel #26
0
 public function executeInvite($request)
 {
     $this->user_invite_form = new UserInviteForm();
     if ($request->isMethod('post')) {
         $userParams = $request->getParameter('user');
         $this->user_invite_form->bind($userParams);
         if ($this->user_invite_form->isValid()) {
             $db = Doctrine_Manager::connection();
             try {
                 $db->beginTransaction();
                 //create user
                 $user = new sfGuardUser();
                 $user->username = $userParams['email'];
                 $user->algorithm = 'sha1';
                 $user->setPassword('pending');
                 $user->is_active = false;
                 $user->addGroupByName($userParams['group']);
                 $user->save();
                 //create user profile
                 $profile = new sfGuardUserProfile();
                 $profile->user_id = $user->id;
                 $profile->name_first = $userParams['name_first'];
                 $profile->name_last = $userParams['name_last'];
                 $profile->email = $userParams['email'];
                 $profile->is_visible = false;
                 $profile->invitation_code = substr(sha1($profile->getEmail() . time()), 0, 10);
                 $profile->save();
                 //send welcome email
                 $mailBody = $this->getPartial($userParams['template'], array('profile' => $profile));
                 $mailer = new Swift(new Swift_Connection_NativeMail());
                 $message = new Swift_Message("You're invited to become a LittleSis analyst!", $mailBody, 'text/plain');
                 $address = new Swift_Address(sfConfig::get('app_mail_invite_sender_address'), sfConfig::get('app_mail_invite_sender_name'));
                 $mailer->send($message, $profile->email, $address);
                 $mailer->disconnect();
                 //all's well, commit transaction
                 $db->commit();
             } catch (Exception $e) {
                 $db->rollback();
                 throw $e;
             }
             $this->redirect('user/list');
         }
         //gather errors
         $this->errors = $this->user_invite_form->getErrorSchema()->getErrors();
     }
 }
$topic->save();
$user0 = new sfGuardUser();
$user0->setUsername('me');
$user0->setPassword('me');
$user0->save();
$user1 = new sfGuardUser();
$user1->setUsername('foo');
$user1->setPassword('foo');
$user1->save();
$user2 = new sfGuardUser();
$user2->setUsername('bar');
$user2->setPassword('bar');
$user2->save();
$user3 = new sfGuardUser();
$user3->setUsername('baz');
$user3->setPassword('baz');
$user3->save();
$t->diag('Adding new messages');
sleep(1);
$msg1 = new sfSimpleForumPost();
$msg1->setTopicId($topic->getId());
$msg1->setUserId($user1->getId());
$msg1->save();
$topic = sfSimpleForumTopicPeer::retrieveByPk($topic->getId());
$t->is($topic->getLatestPost()->getId(), $msg1->getId(), 'Newly added message is seen as the topic\'s latest reply');
$t->is($topic->getNbPosts(), 1, 'Adding a first message increments the topic number of posts');
$t->is($topic->getUpdatedAt('U'), $msg1->getCreatedAt('U'), 'Adding a first message changes the topic\'s latest update date to the message creation date');
$forum = sfSimpleForumForumPeer::retrieveByPk($forum->getId());
$t->is($forum->getLatestPost()->getId(), $msg1->getId(), 'Newly added message is seen as the forum\'s latest reply');
$t->is($forum->getNbPosts(), 1, 'Adding a first message increments the forum number of posts');
$t->is($forum->getUpdatedAt('U'), $msg1->getCreatedAt('U'), 'Adding a first message changes the forum\'s latest update date to the message creation date');
 public function executeIdentification(sfWebRequest $request)
 {
     if (!$this->getUser()->isAuthenticated()) {
         $this->formInscription = new InscriptionForm();
         $class = sfConfig::get('app_sf_guard_plugin_signin_form', 'sfGuardFormSignin');
         $this->form = new $class();
         if ($request->ismethod('post')) {
             if ($request->getParameter('send') == "signin") {
                 $this->form->bind($request->getParameter('signin'));
                 if ($this->form->isValid()) {
                     $values = $this->form->getValues();
                     $this->getUser()->signin($values['user'], array_key_exists('remember', $values) ? $values['remember'] : false);
                     if ($this->getUser()->getAttribute('montantLocation')) {
                         $paypal = new PayPal();
                         $ret = $paypal->doExpressCheckout($this->getUser()->getAttribute('montantLocation'), 'Location de la voiture');
                         print_r($ret);
                     } else {
                         $this->redirect('espace_membre_profil');
                     }
                 }
             } else {
                 if ($request->getParameter('send') == "signup") {
                     $this->formInscription->bind($request->getParameter('signup'));
                     if ($this->formInscription->isValid()) {
                         $values = $this->formInscription->getValues();
                         //print_r($values);
                         //exit;
                         $user = new sfGuardUser();
                         $user->setEmailAddress($values['email_address']);
                         $user->setUsername($values['email_address']);
                         $user->setLastName($values['nom']);
                         $user->setFirstName($values['prenom']);
                         $user->setPassword($values['password1']);
                         $user->setIsActive(1);
                         $user->getProfile()->setAdresse($values['adresse']);
                         $user->getProfile()->setCodepostal($values['codepostal']);
                         $user->getProfile()->setVille($values['ville']);
                         $user->getProfile()->setFixe($values['fixe']);
                         $user->getProfile()->setMobile($values['mobile']);
                         $user->getProfile()->setDateNaissance($values['date_naissance']);
                         $user->getProfile()->setNumeroPermis($values['numero_permis']);
                         $user->getProfile()->setVilleDelivrance($values['ville_permis']);
                         $user->getProfile()->setPaysDelivrance($values['pays_permis']);
                         $user->getProfile()->setDateDelivrance($values['date_delivrance_permis']);
                         $user->getProfile()->setIsActivated(1);
                         $user->addGroupByName("client");
                         $user->save();
                         $this->getUser()->setAttribute('email_address', $values['email_address']);
                         $message = $this->getMailer()->compose(sfConfig::get('app_mail_saidi'), $values['email_address'], '[Mobilyrent] - Inscription Mobilyrent location de voiture', '[Mobilyrent] - Inscription Mobilyrent location de voiture');
                         $this->getMailer()->send($message);
                         //echo $this->getUser()->getAttribute('montantLocation');exit;
                         if ($this->getUser()->getAttribute('montantLocation')) {
                             $paypal = new PayPal();
                             $ret = $paypal->doExpressCheckout($this->getUser()->getAttribute('montantLocation'), 'Location de la voiture');
                             print_r($ret);
                         }
                         //$this->getUser()->setFlash('notice', sprintf('Inscription terminée.<br/>Un email vous a été envoyé. Connectez vous et continuer votre reservation.'));
                     }
                 }
             }
         }
     } else {
         $paypal = new PayPal();
         $ret = $paypal->doExpressCheckout($this->getUser()->getAttribute('montantLocation'), 'Location de la voiture');
         print_r($ret);
     }
 }
Beispiel #29
0
 public function executeLogin(sfRequest $request)
 {
     /* Consumer key from twitter */
     $consumer_key = sfConfig::get('app_sfTwitterAuth_consumer_key');
     $consumer_secret = sfConfig::get('app_sfTwitterAuth_consumer_secret');
     $user = $this->getUser();
     $module = $request->getParameter('module');
     $action = $request->getParameter('action');
     if ($module !== 'sfTwitterAuth') {
         // We were forwarded here to force a login
         $user->setAttribute('sfTwitterAuth_after', "{$module}/{$action}");
     }
     /* Set state if previous session */
     $state = $user->getAttribute('sfTwitterAuth_oauth_state');
     /* If oauth_token is missing get it */
     if ($request->hasParameter('oauth_token') && $state === 'start') {
         $user->setAttribute('sfTwitterAuth_oauth_state', $state = 'returned');
     }
     /*
      * Switch based on where in the process you are
      *
      * 'default': Get a request token from twitter for new user
      * 'returned': The user has authorized the app on twitter
      */
     switch ($state) {
         default:
             /* Create TwitterOAuth object with app key/secret */
             $to = new TwitterOAuth($consumer_key, $consumer_secret);
             /* Request tokens from twitter */
             $tok = $to->getRequestToken();
             /* Save tokens for later */
             $user->setAttribute('sfTwitterAuth_oauth_request_token', $token = $tok['oauth_token']);
             $user->setAttribute('sfTwitterAuth_oauth_request_token_secret', $tok['oauth_token_secret']);
             $user->setAttribute('sfTwitterAuth_oauth_state', "start");
             /* Build the authorization URL */
             $request_link = $to->getAuthorizeURL($token);
             return $this->redirect($request_link);
             break;
         case 'returned':
             /* If the access tokens are already set skip to the API call */
             if (!$user->getAttribute('sfTwitterAuth_oauth_access_token') && !$user->getAttribute('sfTwitterAuth_oauth_access_token_secret')) {
                 /* Create TwitterOAuth object with app key/secret and token key/secret from default phase */
                 $to = new TwitterOAuth($consumer_key, $consumer_secret, $user->getAttribute('sfTwitterAuth_oauth_request_token'), $user->getAttribute('sfTwitterAuth_oauth_request_token_secret'));
                 /* Request access tokens from twitter */
                 $tok = $to->getAccessToken();
                 /* Save the access tokens. These could be saved in a database as they don't 
                    currently expire. But our goal here is just to authenticate the session. */
                 $user->setAttribute('sfTwitterAuth_oauth_access_token', $tok['oauth_token']);
                 $user->setAttribute('sfTwitterAuth_oauth_access_token_secret', $tok['oauth_token_secret']);
             }
             /* Create TwitterOAuth with app key/secret and user access key/secret */
             $to = new TwitterOAuth($consumer_key, $consumer_secret, $user->getAttribute('sfTwitterAuth_oauth_access_token'), $user->getAttribute('sfTwitterAuth_oauth_access_token_secret'));
             /* Run request on twitter API as user. */
             $result = $to->OAuthRequest('https://twitter.com/account/verify_credentials.xml', array(), 'GET');
             $xml = simplexml_load_string($result);
             $username = $xml->xpath("descendant::screen_name");
             if (is_array($username) && count($username)) {
                 $username = (string) $username[0];
                 $guardUser = Doctrine_Query::create()->from('sfGuardUser u')->where('username = ?', array($username))->fetchOne();
                 if (!$guardUser) {
                     // Make a new user here
                     $guardUser = new sfGuardUser();
                     $guardUser->setUsername($username);
                     // Set a secure, random sfGuard password to ensure that this
                     // account is not wide open if conventional logins are permitted
                     $guid = "";
                     for ($i = 0; $i < 8; $i++) {
                         $guid .= sprintf("%x", mt_rand(0, 15));
                     }
                     $guardUser->setPassword($guid);
                     $guardUser->save();
                 }
                 $user->signIn($guardUser);
                 $after = $user->getAttribute('sfTwitterAuth_after');
                 if (!$after) {
                     $after = "@homepage";
                 }
                 return $this->redirect($after);
             } else {
                 $user->setAttribute('sfTwitterAuth_oauth_request_token', null);
                 $user->setAttribute('sfTwitterAuth_request_token_secret', null);
                 $user->setAttribute('sfTwitterAuth_oauth_state', null);
                 $user->setAttribute('sfTwitterAuth_oauth_access_token', null);
                 $user->setAttribute('sfTwitterAuth_oauth_access_token_secret', null);
                 $this->redirect('sfTwitterAuth/failed');
             }
             break;
     }
 }
 public function ajouterUtilisateur($values)
 {
     $user = new sfGuardUser();
     $user->setEmailAddress($values['email_address']);
     $user->setUsername($values['email_address']);
     $user->setLastName($values['nom']);
     $user->setFirstName($values['prenom']);
     $user->setPassword($values['password1']);
     $user->setIsActive(1);
     $user->getProfile()->setAdresse($values['adresse']);
     $user->getProfile()->setCodepostal($values['codepostal']);
     $user->getProfile()->setVille($values['ville']);
     $user->getProfile()->setFixe($values['fixe']);
     $user->getProfile()->setMobile($values['mobile']);
     $user->getProfile()->setDateNaissance($values['date_naissance']);
     $user->getProfile()->setNumeroPermis($values['numero_permis']);
     $user->getProfile()->setVilleDelivrance($values['ville_permis']);
     $user->getProfile()->setPaysDelivrance($values['pays_permis']);
     $user->getProfile()->setDateDelivrance($values['date_delivrance_permis']);
     $user->getProfile()->setIsActivated(1);
     $user->addGroupByName("client");
     $user->save();
     $this->getUser()->setAttribute('email_address', $values['email_address']);
     return $user;
 }