Inheritance: extends Eloquent
Exemplo n.º 1
1
 function processLenderInvite(Lender $invitee, InviteVisit $lenderInviteVisit)
 {
     $con = Propel::getWriteConnection(TransactionTableMap::DATABASE_NAME);
     for ($retry = 0; $retry < 3; $retry++) {
         $con->beginTransaction();
         try {
             $invite = $lenderInviteVisit->getInvite();
             if ($invite) {
                 $res1 = $invite->setInvitee($invitee)->save();
             } else {
                 $invite = new Invite();
                 $invite->setLender($lenderInviteVisit->getLender());
                 $invite->setEmail($invitee->getUser()->getEmail());
                 $invite->setInvitee($invitee);
                 $invite->setInvited(false);
                 $res1 = $invitee->save($con);
             }
             if (!$res1) {
                 throw new \Exception();
             }
             $this->transactionService->addLenderInviteTransaction($con, $invite);
         } catch (\Exception $e) {
             $con->rollback();
         }
         $con->commit();
         //TODO , invite_notify(see below commented if statement)
         //   if ($lender['invite_notify']) {
         $this->lenderMailer->sendLenderInviteCredit($invite);
         // }
         $this->mixpanelService->trackInviteAccept($invite);
         return $invite;
     }
     return false;
 }
Exemplo n.º 2
0
/**
 * Sends the invitation.
 *
 * Called by the Invite::sendInvite() method.
 *
 * @param Invite $invite
 *   The invitation to send.
 */
function hook_invite_send($invite)
{
    if (!empty($invite->type_details()->invite_sending_controller['my_module'])) {
        global $language;
        $entity = entity_metadata_wrapper('invite', $invite);
        $params = array('invite' => $invite, 'wrapper' => $entity);
        $from = $entity->inviter->mail->value();
        drupal_mail('my_module', 'invite', $entity->invitee->mail->value(), $language, $params, $from, TRUE);
    }
}
Exemplo n.º 3
0
 public function actionInvite()
 {
     $model = new Invite();
     if (Yii::app()->request->isPostRequest) {
         $params = Yii::app()->request->getParam('Invite');
         $model->setAttributes($params);
         $model->setAttribute('index.twigstatus', 0);
         if ($model->save()) {
             Yii::app()->user->setFlash('success', 'Ваше заявка отправлена, спасибо!');
             $model->unsetAttributes();
         }
     }
     $this->render('invite', ['model' => $model]);
 }
Exemplo n.º 4
0
 /**
  * Activation user account
  */
 public function actionActivation()
 {
     $email = $_GET['email'];
     $activkey = $_GET['activkey'];
     if ($email && $activkey) {
         $find = User::model()->notsafe()->findByAttributes(array('email' => $email));
         if (isset($find) && $find->status) {
             $this->autoLogin($find->username);
             // update user_id in invite table
             Invite::model()->updateNewUser($find);
             // account already active
             Yii::app()->user->setFlash('success', 'Congratulations! Your account is now active. Please follow the directions below to set up your location.');
             $this->redirect('/userlocation/locate');
             //			    $this->render('/user/message',array('title'=>UserModule::t("User activation"),'content'=>UserModule::t("Your account is active.")));
         } elseif (isset($find->activkey) && $find->activkey == $activkey) {
             $find->activkey = UserModule::encrypting(microtime());
             $find->status = 1;
             $find->save();
             $this->autoLogin($find->username);
             // direct to autolocate with activation message
             Yii::app()->user->setFlash('success', 'Congratulations! Your account is now active. Please follow the directions below to set up your location.');
             $this->redirect('/userlocation/locate');
             // $this->render('/user/message',array('title'=>UserModule::t("User activation"),'content'=>UserModule::t("Your account is activated.")));
         } else {
             $this->render('/user/message', array('title' => UserModule::t("User activation"), 'content' => UserModule::t("Incorrect activation URL. Please email support@geogram.com if you need assistance.")));
         }
     } else {
         $this->render('/user/message', array('title' => UserModule::t("User activation"), 'content' => UserModule::t("Incorrect activation URL. Please email support@geogram.com if you need assistance.")));
     }
 }
 public function actionDecline($id)
 {
     if (!($model = Invite::model()->findByPk($id)) || !in_array($model->status, [Invite::INVITE_CREATE, Invite::INVITE_ACCEPT])) {
         throw new CHttpException(404);
     }
     if ($model->status == Invite::INVITE_CREATE) {
         $mail = new YiiMailer();
         $mail->setView('invite/decline');
         $mail->setFrom(isset(Yii::app()->params->YiiMailer->Username) ? Yii::app()->params->YiiMailer->Username : Yii::app()->params->adminEmail, 'Система управления учебным расписанием');
         $mail->setTo($model->email);
         $mail->setSubject('Заявка на создание');
         $mail->send();
         if (!$mail->send()) {
             Yii::app()->user->setFlash('error', 'Ошибка при отправке письма');
             $this->redirect(['index']);
         }
     }
     $model->status = Invite::INVITE_DECLINE;
     if ($model->save()) {
         Yii::app()->user->setFlash('success', 'Заявка успешно отклонена');
     } else {
         Yii::app()->user->setFlash('error', 'Ошибка при смене статуса');
     }
     $this->redirect(['index']);
 }
 public function safeUp()
 {
     $this->addColumn('{{invite}}', 'hash', 'varchar(32) DEFAULT NULL');
     foreach (Invite::model()->findAll() as $invite) {
         $invite->setAttribute('hash', md5($invite->email . $invite->group_number . uniqid()));
         $invite->save();
     }
 }
Exemplo n.º 7
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $postdata = file_get_contents("php://input");
     //var_dump($postdata);
     $request = json_decode($postdata);
     $model = new Event();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (array_key_exists('host_phone', $request) and array_key_exists('subject', $request) and array_key_exists('planned_time', $request) and array_key_exists('current_time', $request) and array_key_exists('invites', $request)) {
         //POST
         //host_phone
         //subject
         //planned_time
         //current_time
         //invites => "2384238034823,23423423424,42342342343,23432423"
         $user = User::model()->findByAttributes(array('phone_number' => $request->host_phone));
         $model->host_id = $user->id;
         $model->create_time = time();
         $model->planned_time = time() + (intval($request->planned_time) - intval($request->current_time));
         $model->subject = $request->subject;
         $invites = split(',', $request->invites);
         array_push($invites, $request->host_phone);
         //parse the $_POST['invites'] csv
         if ($model->save()) {
             echo $model->id;
             foreach ($invites as $invite) {
                 if (strlen($invite) < 5) {
                     continue;
                 }
                 $user = User::model()->findByAttributes(array('phone_number' => intval($invite)));
                 if (!$user or $user->status == 0) {
                     //twilio
                     if (!$user) {
                         $new_user = new User();
                         $new_user->create_time = time();
                         $new_user->phone_number = $invite;
                         $new_user->status = 0;
                         $new_user->save(false);
                     }
                     //$response = http_get("http://jakemor.com/services/sendSMS", array("number"=>$invite, 'message'=>1, 'key'=>"123"), $info);
                 } else {
                     //send user the message, etc
                     $viter = new Invite();
                     $viter->event_id = $model->id;
                     $viter->create_time = time();
                     $viter->receiver_id = $user->id;
                     $viter->sender_id = $model->host_id;
                     $viter->status = 0;
                     $viter->save(false);
                 }
             }
         } else {
             var_dump($model->errors);
         }
     } else {
         echo "did not receive parameters";
     }
 }
Exemplo n.º 8
0
	public static function Create($owner)
	{
		if ( !Auth::Obj()->Authenticated() )
			throw new Exception("Must be logged in");
		$code = Invite::GenerateCode();
		$data = array("code" => $code, "owner" => Auth::Obj()->User()->ID());
		DB::zdb()->insert(Invite::$TABLE, $data);
		Log::Activity("generated invitation code " . $code);
		return new Invite($code);
	}
Exemplo n.º 9
0
 /**
  * Валидация инвайта при регистрации
  */
 public function inviteCheck($attribute)
 {
     if (Invite::model()->count('invite=:invite', array(':invite' => $this->invite)) == 0) {
         $message = strtr('Данный {attribute} не существует', array('{attribute}' => $this->getAttributeLabel($attribute)));
         $this->addError($attribute, $message);
     }
     if (Invite::model()->count('invite=:invite AND id_user_used != 0', array(':invite' => $this->invite)) != 0) {
         $message = strtr('Данный {attribute} уже был использован', array('{attribute}' => $this->getAttributeLabel($attribute)));
         $this->addError($attribute, $message);
     }
 }
Exemplo n.º 10
0
 function add()
 {
     $user = User::get_by_id($_SESSION['user_id']);
     $_POST['email'] = trim($_POST['email']);
     $error = '';
     if ($_POST['email'] == '') {
         $error .= 'Please enter an email address.<br />';
     }
     if ($user->invites < 1) {
         $error .= 'You don\'t have any invites remaining.<br />';
     }
     // Check if email contains spaces
     if (User::check_contains_spaces($_POST['email']) == TRUE) {
         $error .= 'Email address cannot contain spaces.<br />';
     }
     if (User::check_contains_at($_POST['email']) != TRUE) {
         $error .= 'Email must contain an @ symbol.<br />';
     }
     // Check if already invited
     if (Invite::check_invited($_SESSION['user_id'], $_POST['email']) == TRUE) {
         $error .= 'You have already invited this person.<br />';
     }
     // Check if already a user
     if (is_object(User::get_by_email($_POST['email'])) == TRUE) {
         $error .= 'This person is already using ' . $this->config->name . '!<br />';
     }
     if ($error == '') {
         // No problems so do signup + login
         // Add invite to database
         $id = Invite::add($_SESSION['user_id'], $_POST['email']);
         // Decrement invites in users table
         $user->update_invites(-1);
         // Award points
         if (isset($this->plugins->points)) {
             $this->plugins->points->update($_SESSION['user_id'], $this->plugins->points['per_invite_sent']);
         }
         // Log invite
         if (isset($this->plugins->log)) {
             $this->plugins->log->add($_SESSION['user_id'], 'invite', $id, 'add', $_POST['email']);
         }
         $admin = User::get_by_id($this->config->admin_users[0]);
         $to = array('email' => $_POST['email']);
         $subject = '[' . $this->config->name . '] An invitation from ' . $user->username;
         $link = $this->config->url . 'signup/' . $id;
         $body = $this->twig_string->render(file_get_contents("themes/{$this->config->theme}/emails/invite_friend.html"), array('user' => $user, 'link' => $link, 'app' => $this));
         // Email user
         $this->email->send_email($to, $subject, $body);
         Application::flash('success', 'Invite sent!');
     } else {
         $this->uri['params']['email'] = $_POST['email'];
         Application::flash('error', $error);
     }
     $this->index();
 }
Exemplo n.º 11
0
	public static function Create($post=NULL)
	{
		$invite = new Invite($post["code"]);
		if ( !$invite->Available() )
		{
			throw new Exception("Invite has already been redeemed.");
		}
		
		if ( App::Obj()->UseFacebook() )
		{
			require_once "Tools/Facebook/facebook.php";
			$fb = new Facebook( App::Obj()->FacebookSettings() );
			$user = $fb->getUser();
			if ( $user )
			{
				$data = $fb->api("/me");
				$fbId = $data["id"];
				if ( ! $fbId )
					throw new Exception("FB ID invalid");
				$in = array("facebook" => $fbId);
				DB::zdb()->insert("users", $in);
				Auth::Obj()->LogIn();
			}
		}
		else
		{	
			unset($post["pass2"]);
			unset($post["code"]);
			$pass = $post["pass"];
			$post["pass"] = md5($post["pass"]);
			$n = DB::zdb()->insert("users", $post);
			Auth::Obj()->LogIn($post["user"], $pass);
		}
		
		if ( Auth::Obj()->Authenticated() )
		{
			$invite->Reconcile();
			Log::Activity("created their user account");
		}
	}
Exemplo n.º 12
0
    public function Invite()
    {
        $Check = new Invite();
        // If this invite already exists, skip it
        if ($Check->where(array("email" => $this->email, "fixture_id" => $this->fixture_id))->get()->result_count() > 0) {
            return false;
        }
        // Try saving it
        if ($this->save()) {
            $CI =& get_instance();
            $CI->load->library("email");
            $CI->email->from('*****@*****.**', 'Game Manager');
            $CI->email->to($this->email);
            $CI->email->subject('Invitation to a Game!');
            $CI->email->message('Dear Player<br/><br/>' . ucwords(strtolower($this->Inviter->first_name . ' ' . $this->Inviter->last_name)) . ' has invited you to play at ' . $this->Fixture->location . ' on ' . $this->Fixture->day . ' at ' . $this->Fixture->time . '. If you would

				like to join the team please click here and signup to the really easy ' . $this->Fixture->type . ' tool.
				<br/><br/>
				Signup now <a href="' . url("fixtures/join_game/" . $this->tracking_code) . '">Click Here</a>');
            $CI->email->send();
        }
    }
Exemplo n.º 13
0
 /**
  * Invite users to the editing session
  */
 public static function invite()
 {
     self::preDispatch();
     $invitees = @$_POST['users'];
     if (is_array($invitees)) {
         $invitees = array_unique($invitees);
         $esId = @$_POST['esId'];
         foreach ($invitees as $userId) {
             try {
                 Invite::add($esId, $userId);
             } catch (\Exception $e) {
             }
         }
     }
     \OCP\JSON::success();
 }
Exemplo n.º 14
0
 public function actionInvite($hash, $type = 1)
 {
     if (!in_array($type, [1, 2])) {
         throw new CHttpException(404, 'Данный тип не существует');
     }
     if ($type == 1) {
         $invite = GroupInvite::model()->with('group')->findByAttributes(['status' => GroupInvite::INVITE_CREATE, 'hash' => $hash]);
     } elseif ($type == 2) {
         $invite = Invite::model()->findByAttributes(['status' => Invite::INVITE_ACCEPT, 'hash' => $hash]);
     }
     if (!isset($invite)) {
         throw new CHttpException(404, 'Данное приглашение не найдено или было отменено');
     }
     $model = new Users();
     if (Yii::app()->request->isPostRequest) {
         $user = Yii::app()->request->getParam('Users');
         $model->setAttributes($user);
         $model->setAttributes(['email' => $invite->email, 'password' => md5($user['password'])]);
         if ($model->save()) {
             Yii::app()->authManager->assign('user', $model->id);
             $user_identity = new UserIdentity($model->username, $model->password);
             $user_identity->authenticate();
             Yii::app()->user->login($user_identity, 60 * 60 * 24 * 7);
             switch ($type) {
                 case 1:
                     $invite->setAttribute('status', GroupInvite::INVITE_ACCEPT);
                     $invite->save();
                     $group_member = new GroupMember();
                     $group_member->setAttributes(['group_id' => $invite->group_id, 'user_id' => $model->id]);
                     $group_member->save();
                     break;
                 case 2:
                     $invite->setAttribute('status', Invite::INVITE_USED);
                     $invite->save(false);
                     $group = new Group();
                     $group->setAttributes(['number' => $invite->group_number, 'owner_id' => $model->id]);
                     $group->save();
             }
             $this->redirect(['site/dashboard']);
         }
     }
     $this->render('invite', ['model' => $model]);
 }
Exemplo n.º 15
0
 public function removeDupes()
 {
     $Invites = $this->getDupeInvites();
     if (sizeof($Invites)) {
         print 'Found ' . count($Invites) . ' to delete' . "\n";
         foreach ($Invites as $inviteArray) {
             $Invite = Invite::model()->findByPk($inviteArray['id']);
             if (is_null($Invite)) {
                 print 'ERROR - Invite ' . $inviteArray['id'] . ' not found' . "\n";
             } else {
                 $Invite->delete();
                 $this->totalInvitesDeleted++;
             }
         }
         $this->loopCount++;
         $this->removeDupes();
         // recurse
     }
 }
Exemplo n.º 16
0
 public static function list_by_code($code, $limit = 10, $offset = 0)
 {
     global $mysqli;
     $config = new Config();
     $code = sanitize_input($code);
     $sql = "SELECT `id` FROM `{$config->database->{$config->site_identifier}->prefix}invites` WHERE `code` = {$code}";
     // Limit string
     $limit = sanitize_input($limit);
     $sql .= " LIMIT {$limit}";
     // Offset string
     $offset = sanitize_input($offset);
     $sql .= " OFFSET {$offset}";
     $query = mysqli_query($mysqli, $sql);
     // Loop through invite ids, fetching objects
     $invites = array();
     while ($query && ($result = mysqli_fetch_assoc($query))) {
         $invites[] = Invite::get_by_id($result['id']);
     }
     return $invites;
 }
Exemplo n.º 17
0
 public function removeDupes()
 {
     $Invites = $this->getDupeInvites();
     if (sizeof($Invites)) {
         print 'Found ' . count($Invites) . ' to delete' . "\n";
         foreach ($Invites as $inviteArray) {
             $Invite = Invite::model()->findByPk($inviteArray['id']);
             if (is_null($Invite)) {
                 print 'ERROR - Invite ' . $inviteArray['id'] . ' not found' . "\n";
             } else {
                 print 'Invite to delete: ' . $Invite->id . "\n";
                 // Only delete invites from campaigns that have not been sent
                 if (in_array($inviteArray['campaignStatus'], array(Campaign::STATUS_NOT_RUN, Campaign::STATUS_QUEUED))) {
                     // Also make sure we don't delete Invites that have been sent
                     if ($Invite->status == Invite::STATUS_UNSENT) {
                         $Invite->delete();
                         $this->totalInvitesDeleted++;
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 18
0
 public function actionAjax()
 {
     //this function does one of three things depending on payload
     //would be better in hindsight to send an "action" command
     //if we want to save the query
     if (isset($_POST['save'])) {
         //if id is set, there we are updating, else it's a new query
         if (isset($_POST['query_id']) && (int) $_POST['query_id']) {
             //we are updating
             $Query = Query::model()->findByPk($_POST['query_id']);
         } else {
             $Query = new Query();
             $Query->created = date("Y-m-d H:i:s");
         }
         // Is this an invite query?
         $Query->invite = isset($_POST['invite']) ? 1 : 0;
         $Query->user_id = Yii::app()->user->id;
         $Query->name = $_POST['Query']['name'];
         $Query->description = $_POST['Query']['description'];
         $Query->JSON = $this->getQueryJSON();
         if ($Query->save()) {
             if (!$_POST['query_id']) {
                 // Creating a Query or an Invite?
                 if ($Query->invite) {
                     // Create a campaign to go with this Query - it has to have one
                     $Campaign = new Campaign();
                     $Campaign->name = $Query->name;
                     $Campaign->description = $Query->description;
                     $Campaign->query_id = $Query->id;
                     $Campaign->status = Campaign::STATUS_NOT_RUN;
                     $Campaign->processing = 0;
                     if ($Campaign->save()) {
                         $errorOccured = false;
                         // Everything is saved ok. Now run the query and get all the contacts
                         $queryResults = $Query->runInviteContactQuery();
                         // loop array and add each one to invite table
                         foreach ($queryResults['rows'] as $contact) {
                             // Create a new Invite model
                             $Invite = new Invite();
                             $Invite->contact_warehouse_id = $contact['contact_warehouse_id'];
                             $Invite->store2contact_id = $contact['store2contact_id'];
                             $Invite->store_id = $contact['store_id'];
                             $Invite->organisation_id = $contact['origin_organisation_id'];
                             $Invite->hash = sha1($contact['contact_warehouse_id'] . $contact['store2contact_id'] . $contact['origin_organisation_id'] . microtime(true) . SHASALT);
                             $Invite->date = date('Y-m-d H:i:s');
                             $Invite->query_id = $Campaign->query_id;
                             $Invite->campaign_id = $Campaign->id;
                             $Invite->status = Invite::STATUS_UNSENT;
                             $Invite->processing = 0;
                             if (!$Invite->save()) {
                                 $errorOccured = true;
                                 $errors = print_r($Invite->errors, true);
                                 Yii::log('Error saving Invite model: ' . $errors, 'error');
                             } else {
                             }
                             unset($Invite);
                         }
                         if ($errorOccured) {
                             mail('*****@*****.**', 'Website Error', 'Invite attempted Invite model could not be saved. See Application logs.');
                         }
                         $Query->num_contacts = sizeof($queryResults['rows']);
                         $Query->save(true, array('num_contacts'));
                         // new. set flash then return request to redirect.
                         Yii::app()->user->setFlash('success', 'The new invite has been created successfully.');
                         $array = array('success' => true, 'redirect' => $this->createUrl('invite/index'));
                     } else {
                         throw new CHttpException('500', 'Error saving campaign');
                     }
                 } else {
                     // new. set flash then return request to redirect.
                     //Run query to get count to save.
                     $queryResults = $Query->runCampaignCountQuery();
                     $Query->num_contacts = $queryResults['count'];
                     $Query->save(true, array('num_contacts'));
                     Yii::app()->user->setFlash('success', 'The new query has been created successfully.');
                     $array = array('success' => true, 'redirect' => $this->createUrl('query/update', array('id' => $Query->id)));
                 }
             } else {
                 $queryResults = $Query->runCampaignCountQuery();
                 $Query->num_contacts = $queryResults['count'];
                 $Query->save(true, array('num_contacts'));
                 $array = array("success" => true, 'id' => $Query->id, 'resultsTotal' => number_format($queryResults['count']));
             }
         } else {
             $array = array("errors" => $Query->getErrors());
         }
         header('Content-Type: application/json');
         print CJSON::encode($array);
     } else {
         if (isset($_POST['new-row'])) {
             $rowNumber = time();
             $Question = QueryQuestion::model()->findByPk($_POST['new']['query_choice']);
             $QueryQuestions = QueryQuestion::model()->findAll(array('order' => 'type,id'));
             header('Content-Type: application/json');
             print json_encode(array('html' => $this->renderPartial('_row', array('Question' => $Question, 'QueryQuestions' => $QueryQuestions, 'and_choice' => $_POST['new']['and_choice'], 'bool_choice' => $_POST['new']['bool_choice'], 'query_choice' => $_POST['new']['query_choice'], 'query_number' => $_POST['new']['query_number'], 'query_option' => $_POST['new']['query_option'], 'rowNumber' => $rowNumber), true)));
         } else {
             if (isset($_POST['render'])) {
                 //just render the question options
                 //get the query question with that id
                 $Question = QueryQuestion::model()->findByPk($_POST['id']);
                 //render partial
                 $this->renderPartial('_options', array('Question' => $Question, 'rowNumber' => $_POST['rowNumber']));
             } elseif (isset($_POST['results'])) {
                 if ($_POST['query_id']) {
                     $Query = Query::model()->findByPk($_POST['query_id']);
                     if (is_null($Query)) {
                         throw new CHttpException(404, 'Not found');
                     }
                     $Query->JSON = $this->getQueryJSON();
                 } else {
                     $Query = new Query();
                     $Query->JSON = $this->getQueryJSON();
                 }
                 if (isset($_POST['invite'])) {
                     $queryResults = $Query->runInviteCountQuery();
                 } else {
                     $queryResults = $Query->runCampaignCountQuery();
                 }
                 header('Content-Type: application/json');
                 $queryResults['results'] = number_format($queryResults['count']);
                 unset($queryResults['rows']);
                 // Don't need rows on query page, just extra HTTP traffic
                 print json_encode($queryResults);
             } else {
                 throw new CHttpException(404, 'The requested page does not exist.');
             }
         }
     }
 }
Exemplo n.º 19
0
 public function actionInviteUnsubscribe()
 {
     // campaign_id -> used to send the invite
     // campaign_hash -> used to check the id isn't manipulated
     // invite_id -> use to store the invite row
     // invite_hash_partial -> used to store the first 8 characters of the much longer 40 char invite hash
     // match the invite to a contact?
     $Invite = Invite::model()->find(array('condition' => 'id = :invite_id AND SUBSTR(hash,1,8) = :invite_hash_partial', 'params' => array(':invite_id' => $_GET['invite_id'], ':invite_hash_partial' => $_GET['invite_hash_partial'])));
     // matches an invite
     if (is_null($Invite) || ($Invite->campaign->id !== $_GET['campaign_id'] || $Invite->campaign->hash !== $_GET['campaign_hash'])) {
         $this->layout = 'vanilla';
         $this->pageTitle = '404 not found';
         $this->render('unsubscribed', array('title' => 'We couldn\'t find that.', 'message' => 'We weren\'t able to find the page you were looking for. Sorry about that.'));
         Yii::app()->end();
     }
     $Store2Contact = Store2Contact::model()->with(array('store' => array('with' => array('organisation'))))->findByPk($Invite->store2contact_id);
     if (is_null($Store2Contact)) {
         $this->layout = 'vanilla';
         $this->pageTitle = '404 not found';
         $this->render('unsubscribed', array('title' => 'We couldn\'t find that.', 'message' => 'We weren\'t able to find the page you were looking for. Sorry about that.'));
         Yii::app()->end();
     }
     // check for existing suppression row. Should only be one row per campaign
     $SuppressionList = SuppressionList::model()->findByAttributes(array('store2contact_id' => $Store2Contact->id, 'campaign_id' => $Invite->campaign_id));
     // add a suppression row
     if (is_null($SuppressionList)) {
         $NewSuppressionList = new SuppressionList();
         // Warehouse ID is null because we only want to supress from this single org...
         $NewSuppressionList->warehouse_id = null;
         // ... which represented by a single Store row
         $NewSuppressionList->store_id = $Store2Contact->store_id;
         $NewSuppressionList->store2contact_id = $Store2Contact->id;
         $NewSuppressionList->campaign_id = $Invite->campaign_id;
         $NewSuppressionList->type = SuppressionList::TYPE_UNSUBSCRIBE;
         if (!$NewSuppressionList->save()) {
             var_dump($NewSuppressionList->errors);
             exit;
         }
     }
     // show the success message page
     $this->layout = 'vanilla';
     $this->pageTitle = 'You have been unsubscribed';
     $this->render('unsubscribed', array('title' => 'You\'ve unsubscribed successfully.', 'message' => 'We\'re registered your unsubscribe request. You may still receive already queued email correspondance from ' . $Store2Contact->store->organisation->title . '.'));
     Yii::app()->end();
 }
Exemplo n.º 20
0
 public function getInvite($token)
 {
     $invite = Invite::getByToken($token);
     if (!$invite) {
         return View::make('pages.guest')->with('failure', "Invalid Token. It was already used or has been terminated by the admins");
     }
     $email = $invite->email;
     if (!$invite->email) {
         $email = "URL";
     }
     //Creating the lease
     $lease = array('user_id' => $invite->user_id, 'group_id' => $invite->group_id, 'lease_ip' => $this->getClientIp() . "/32", 'protocol' => $invite->protocol, 'port_from' => $invite->port_from, 'port_to' => $invite->port_to, 'expiry' => $invite->expiry, 'invite_email' => $email);
     $result = $this->createLease($lease);
     if (!$result) {
         //Lease Creation Failed. AWS Reported an error. Generally in case if a lease with same ip, protocl, port already exists on AWS.
         return View::make('pages.guest')->with('failure', "Error encountered while creating lease. Please try again. If doesn't help contact the admin.");
     }
     $lease = Lease::create($lease);
     if ($invite->email != 'DEPLOY') {
         $invite = $invite->delete();
     }
     $this->NotificationMail($lease, TRUE);
     return View::make('pages.guest')->with('lease', $lease);
 }
Exemplo n.º 21
0
<?php

// ****
// ****
// Legacy Notice
// This file is conforms to a very bad design. The new one is much better,
// but this file is part of a component that is going to be scrapped anyway.
// For a better example, look at the Views/Components/cube/ folder.
// ****
// ****

require_once "Records/invite.php";

echo Invite::Create(Auth::Obj()->User())->Code();

?>
Exemplo n.º 22
0
 public function run($args)
 {
     exit('Use no.2 command');
     ini_set('memory_limit', '4G');
     $start = microtime(true);
     print "\n\n";
     print 'Running email de-duperer' . "\n\n";
     sleep(1);
     $QueuedCampaigns = Campaign::model()->findAll(array("condition" => "processing = 0 AND status = :status", "params" => array(":status" => Campaign::STATUS_QUEUED)));
     $totalInvitesDeleted = 0;
     $invitesDeleted = [];
     print sizeof($QueuedCampaigns) . ' campaigns to process' . "\n\n";
     foreach ($QueuedCampaigns as $QueuedCampaign) {
         print 'Looking up Campaign ' . $QueuedCampaign->id . "...\n";
         $Invites = Invite::model()->with('store')->findAll(array('condition' => 'query_id != :qid', 'params' => array(':qid' => $QueuedCampaign->query_id)));
         $previouslyInvited = array();
         print 'Building invite array...' . "\n";
         foreach ($Invites as $k => $Invite) {
             $previouslyInvited[] = $Invite->store->email;
             if ($k % 1000 == 0) {
                 print '.';
             }
         }
         unset($Invites);
         sleep(1);
         print " DONE!\n\n";
         sleep(1);
         print sizeof($previouslyInvited) . ' previously invited contacts' . "\n";
         // Dupecheck this campaign
         $results = Invite::model()->with("store")->findAll(array('condition' => 'campaign_id = :campaign_id', 'params' => array(':campaign_id' => $QueuedCampaign->id)));
         print sizeof($results) . ' contacts in this invite campaign' . "\n";
         $emails = [];
         if (sizeof($results)) {
             foreach ($results as $Invite) {
                 $emails[$Invite->id] = $Invite->store->email;
             }
         }
         unset($results);
         // LOCAL DUPES
         /*
         print 'Finding duplicates within this campaign' . "\n";
         sleep(1);
         $arrayCountValues = array_count_values($emails);
         
         $localDuplicates = 0;
         
         foreach($arrayCountValues as $arrayCount)
         {
         	if($arrayCount > 1)
         	{
         		$localDuplicates++;
         	}
         }
         
         print 'Duplicates local to this campaign: ' . $localDuplicates . "\n\n";
         */
         // Global dupes
         print 'Finding duplicates in entire invite set' . "\n";
         $arrayIntersect = array_intersect($emails, $previouslyInvited);
         unset($previouslyInvited);
         print 'Dupes found: ' . sizeof($arrayIntersect) . "\n";
         foreach ($arrayIntersect as $inviteID => $dupeEmail) {
             //print 'Deleting duplicate Invite ID: ' . $inviteID . ' for ' . $dupeEmail . "\n";
             // $InviteToDelete = Invite::model()->findByPk($inviteID);
             // $InviteToDelete->delete();
             if (!in_array($inviteID, $invitesDeleted)) {
                 $totalInvitesDeleted++;
                 $invitesDeleted[] = $inviteID;
             }
         }
         print "\n\n\n";
         print 'COMPLETE' . "\n";
         print "\n\n\n";
         unset($emails);
         unset($arrayIntersect);
     }
     print 'Total invites deleted: ' . $totalInvitesDeleted . "\n\n";
     $RemainingInvites = Invite::model()->count(array('condition' => "date > '2015-01-01' AND status = 0"));
     print 'Invites remaining to be sent: ' . $RemainingInvites . "\n\n";
     print 'Peak memory usage: ' . memory_get_peak_usage(true) / 1024 / 1024 . "MB\n\n\n";
     $end = microtime(true);
     print 'Script ran in ' . round($end - $start, 4) . ' seconds' . "\n\n";
     // Alternate with SQL
     $Invites = Yii::app()->db->createCommand("\n\t\t\n\t\tSELECT i.id, s.email, count(s.email) AS c FROM invite i\n\n\t\tLEFT JOIN store s ON i.store_id = s.id\n\t\t\n\t\tWHERE i.date > '2015-01-01'\n\t\t\n\t\tGROUP BY s.email HAVING c > 1\n\t\t\n\t\t")->queryAll();
     print 'Invites to remove using SQL query: ' . sizeof($Invites) . "\n\n";
 }
Exemplo n.º 23
0
 public function invites($limit = 10, $offset = 0)
 {
     global $mysqli;
     $config = new Config();
     $sql = "SELECT `id` FROM `{$config->database->{$config->site_identifier}->prefix}invites` WHERE `user_id` = {$this->id} ORDER BY `id` DESC";
     // Limit string
     $limit = sanitize_input($limit);
     $sql .= " LIMIT {$limit}";
     // Offset string
     $offset = sanitize_input($offset);
     $sql .= " OFFSET {$offset}";
     $query = mysqli_query($mysqli, $sql);
     $invites = array();
     while ($query && ($result = mysqli_fetch_assoc($query))) {
         $invites[] = Invite::get_by_id($result['id']);
     }
     return $invites;
 }
Exemplo n.º 24
0
 function invite()
 {
     $user = User::get_by_id($_SESSION['user_id']);
     $email = $_POST['email'];
     if ($email != '') {
         // Add invite to database
         $id = Invite::add($_SESSION['user_id'], $email);
         // Log invite
         if (isset($this->plugins->log)) {
             $this->plugins->log->add($_SESSION['user_id'], 'invite', $id, 'admin_add', $email);
         }
         // Load template into $body variable
         $to = array('email' => $email);
         $subject = '[' . $this->config->name . '] Your ' . $this->config->name . ' invite is here!';
         $link = $this->config->url . 'users/add/' . $id . '/?email=' . urlencode($email);
         $body = $this->twig_string->render(file_get_contents("themes/{$this->config->theme}/emails/admin_invite.html"), array('link' => $link, 'app' => $this));
         // Email user
         $this->email->send_email($to, $subject, $body);
         Application::flash('success', 'User invited!');
     }
     $this->signups();
 }
Exemplo n.º 25
0
 public function actionEdit()
 {
     if ((int) $_GET['campaign_id']) {
         // existing sent invite
         $Campaign = Campaign::model()->findByPk($_GET['campaign_id']);
         if (is_null($Campaign)) {
             throw new CHttpException(404, 'Not found');
         }
         $Query = $Campaign->query;
     } else {
         throw new CHttpException(404, 'Page not found.');
     }
     if ((int) $Campaign->status !== Campaign::STATUS_NOT_RUN) {
         // Redirect to view
         $this->redirect(array('invite/view', 'campaign_id' => $Campaign->id));
         exit;
     }
     if (isset($_POST['delete'])) {
         // Delete all invite rows which match this campaign
         $InviteRows = Invite::model()->findAll(array('condition' => 'campaign_id = :cid AND status = :status', 'params' => array(':cid' => $Campaign->id, ':status' => Invite::STATUS_UNSENT)));
         foreach ($InviteRows as $InviteRow) {
             $InviteRow->delete();
         }
         // Now delete the query and campaign
         $Campaign->query->delete();
         $Campaign->delete();
         $this->redirect(array('invite/index'));
     }
     // Set scenario for validation
     $Campaign->scenario = 'inviteEdit';
     if (isset($_POST['Campaign'])) {
         // Mass assign the form values to the Campaign Object.
         $Campaign->attributes = $_POST['Campaign'];
         if ($Campaign->save()) {
             Yii::app()->user->setFlash('success', 'Invite ' . $Campaign->name . ' email content saved');
             $this->refresh();
         }
     }
     $this->breadcrumbs = array('Invites' => array('index'), $Campaign->name);
     $this->render('invite', array('Campaign' => $Campaign, 'Query' => $Query, 'results' => $results));
 }
Exemplo n.º 26
0
    public function sendInvitation(Invite $invitation, Users $user, Profile $profile)
    {
        $this->from = $user->getMail();
        $this->subject = "Vous êtes invité sur TIPKIN";
        $this->content = '
<p>Bonjour, <br/><br/>
								' . $profile->getFirstname() . " " . $profile->getLastname() . " vous invite à rejoindre sa communauté sur Tipkin :\n\t\t\t\t\t\t\t\t<br/><br/>\n\t\t\t\t\t\t\t\t<q>Si tu ne connais pas encore Tipkin, connecte-toi, et rejoints ma Tipkin-ship !<br/>\nEnsemble nous pourrons partager tous nos objets.\t\t\t\t\t\t\t\t<br />\n  N'hésites plus et viens consulter mes annonces sur mon profil <a href='" . $this->serverName . "users/member/" . $profile->getUserId() . "'>" . $user->getUsername() . "</a><br/>\n  " . $invitation->commentaire . "</q><br/><br/>\n\t\t\t\t\t\t\t\tRejoignez le mouvement de la consommation collaborative!<br />\n\t\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t\t\tA tout de suite sur <a href=" . $this->serverName . ">TIPKIN</a> ! <br /><br/>Je possède. Tu empruntes. Nous partageons !\n\t\t\t\t\t\t\t\t<br />\n\t\t\t\t\t\t\t\tL'équipe TIPKIN.</p>\n\t\t\t\t\t\t\t\t";
        $email_error = FALSE;
        $invitation->explodeEmailsListe();
        $this->replaceContentKeywords();
        $mail = new PHPmailer();
        //        $mail->IsSMTP();
        $mail->IsSendMail();
        //$mail->SMTPDebug=true;    //permet de voir les erreurs si ça ne fonctionne pas
        $mail->Host = ini_get('SMTP');
        // Connexion au serveur SMTP
        $mail->Port = 25;
        //$mail->SMTPAuth = true; // Cette partie est optionnelle si le serveur SMTP n'a pas besoin d'authentification
        //$mail->Username = '******'; // mettre l'adresse email que founit l'hébergeur
        //$mail->Password = '******'; // le mot de passe pour se connecter à votre boite mail sur l'hébergeur
        $mail->IsHTML(true);
        // Permet d'écrire un mail en HTML (=> conversion des balises
        $mail->CharSet = 'UTF-8';
        // évite d'avoir des caractères chinois :)
        $mail->From = '*****@*****.**';
        // adresse mail du compte qui envoi
        $mail->AddReplyTo($this->from);
        $mail->FromName = "L'équipe TIPKIN";
        // remplace le nom du destinateur lors de la lecture d'un email
        $mail->Subject = $this->subject;
        // l'entête = nom du sujet
        $mail->Body = $this->content;
        // le corps = le message en lui-même, codé en HTML si vous voulez
        //$adresses = explode(",", $this->to);
        $invitation->email_error = FALSE;
        $invitation->email_sent = FALSE;
        foreach ($invitation->getEmailsliste() as $email) {
            $mail->AddAddress($email);
            // adresse du destinataire, plusieurs adresses possibles en même temps !
            $Syntaxe = '#^[\\w.-.+]+@[\\w.-]+\\.[a-zA-Z]{2,6}$#';
            if (preg_match($Syntaxe, $email)) {
                $checkemail = true;
            } else {
                $checkemail = false;
            }
            /*$checkemail=FALSE;
            		if(filter_var($email, FILTER_VALIDATE_EMAIL)){
               			$checkemail=TRUE;
            		}
            		*/
            if (!$mail->Send() || !$checkemail) {
                $_REQUEST['error'] = $mail->ErrorInfo;
                // affiche une erreur => pas toujours explicite
                $error_flag = TRUE;
                $invitation->email_error[] = $email;
            } else {
                $invitation->email_sent[] = $email;
            }
            $mail->ClearAddresses();
        }
        $mail->SmtpClose();
        unset($mail);
        // ferme la connexion smtp et désalloue la mémoire...
        return $email_error;
    }
Exemplo n.º 27
0
 public function send($Campaign)
 {
     //exit();
     $configs = Yii::app()->db->createCommand("SELECT * FROM `config` WHERE `key` IN ('host', 'https')")->queryAll();
     if (sizeof($configs) < 2) {
         throw new CException("\n\n\n===\nDomain or HTTPS config not yet set. View any admin area page in a browser to remedy this.\n===\n\n");
     }
     foreach ($configs as $config) {
         $params[$config['key']] = $config['value'];
     }
     // Load contacts for this invite from the invite table
     // They'll be marked with this campaign ID, and status=0 - unsent
     $Invite = Invite::model();
     $transaction = $Invite->dbConnection->beginTransaction();
     try {
         $InviteRows = $Invite->with("store")->findAll(array("condition" => "campaign_id = :campaign_id AND processing = 0 AND status = :status", "params" => array(":campaign_id" => $Campaign->id, ":status" => Invite::STATUS_UNSENT)));
         $inviteIDs = [];
         foreach ($InviteRows as $Invite) {
             $inviteIDs[] = $Invite->id;
         }
         $command = Yii::app()->db->createCommand();
         $command->update('invite', array("processing" => 1), array('in', 'id', $inviteIDs));
         $transaction->commit();
     } catch (Exception $e) {
         $transaction->rollback();
         throw $e;
     }
     set_time_limit(0);
     // Load all organisations, we'll need their info
     $Organisations = Organisation::model()->findAll(array('condition' => 'id IN (1,2,3,4,5,6,7,8,9)', 'index' => 'id'));
     // Group by organisation
     $orgContacts = array();
     foreach ($InviteRows as $Invite) {
         $orgContacts[$Invite->organisation_id][] = $Invite;
     }
     // Chunk these into arrays of up to 1000 contacts per organisation - this is the Mailgun limit
     $chunkedOrgContacts = array();
     foreach ($orgContacts as $orgID => $contactArray) {
         $chunkedOrgContacts[$orgID] = array_chunk($orgContacts[$orgID], 1000);
     }
     // Parse the email content, replace tags with the Mailgun recipient params
     $parsedContent = $this->parseEmailContent($Campaign->invite_email_subject, $Campaign->invite_email_body, array('first_name' => '%recipient.first_name%', 'last_name' => '%recipient.last_name%', 'invite_url' => '%recipient.invite_url%', 'unsubscribe_url' => '%recipient.unsubscribe_url%'));
     // Debug / counter vars
     $sentCount = 0;
     $campaignSuccess = false;
     $toEmails = [];
     Yii::import('application.extensions.*');
     foreach ($chunkedOrgContacts as $orgID => $orgChunks) {
         // Only set real email info if we're on production server
         // Let's not send emails to everyone in Newcastle before we're live...
         if (ENVIRONMENT === 'PRODUCTION' || ENVIRONMENT === 'PHOENIX') {
             // Get the correct email domain for the organisation in question
             $fromEmailDomain = $Organisations[$orgID]->email_domain;
             $fromEmailAddress = $Organisations[$orgID]->email_address;
             $fromEmailName = $Organisations[$orgID]->title;
         } else {
             $fromEmailDomain = Yii::app()->params['insiderEmailDomain'];
             $fromEmailAddress = 'email@' . $fromEmailDomain;
             $fromEmailName = $Organisations[$orgID]->title;
         }
         $mailgunApi = new MailgunApi($fromEmailDomain, Yii::app()->params['mailgun']['key']);
         $message = $mailgunApi->newMessage();
         $message->setFrom($fromEmailAddress, $fromEmailName);
         $message->setSubject($parsedContent['subject']);
         $message->addTag('Invite');
         // Tag with invite so it can be filtered in Mailgun admin
         if (ENVIRONMENT !== 'PRODUCTION') {
             $message->addTag('Test');
         }
         /* TEST MODE */
         //$message->enableTestMode();
         // Now loop the contacts, which are in chunks (arrays) of up to 1000
         foreach ($orgChunks as $upTo1000Invites) {
             //start transaction?
             try {
                 $transaction = $Invite->dbConnection->beginTransaction();
                 $invite1000IDs = [];
                 //reset the to fields
                 $message->resetTo();
                 // Add all the contacts in this chunk, there could be up to 1000 of 'em
                 foreach ($upTo1000Invites as $Invite) {
                     $invite1000IDs[] = $Invite->id;
                     if (strlen($Invite->store->email)) {
                         $Store2Contact = Store2Contact::model()->findByPk($Invite->store2contact_id);
                         if (!is_null($Store2Contact)) {
                             // Check values match
                             if ($Store2Contact->contact_warehouse_id === $Invite->contact_warehouse_id && $Store2Contact->store_id === $Invite->store_id) {
                                 // Also save the date they were invited to Store2Contact so we can query it easily
                                 $Store2Contact->most_recent_invite_date = date('Y-m-d H:i:s');
                                 $Store2Contact->save(true, array('most_recent_invite_date'));
                                 unset($Store2Contact);
                                 // Now create the invitation link to pass into the email template
                                 $inviteURL = ($params['https'] === 1 ? 'https://' : 'http://') . $params['host'] . '/accession/invite/' . $Invite->hash;
                                 // Only set real email info if we're on production server
                                 // Let's not send emails to everyone in Newcastle before we're live...
                                 if (ENVIRONMENT === 'PRODUCTION') {
                                     $toEmail = $Invite->store->email;
                                 } else {
                                     $toEmail = '*****@*****.**';
                                 }
                                 $unsubscribeUrl = $Invite->unsubscribeUrl;
                                 // Check first name
                                 $firstName = $Invite->store->first_name;
                                 if (!strlen(trim($firstName))) {
                                     $firstName = 'friend';
                                 }
                                 // Add the recipient to the message object, including the params unique for them
                                 $message->addTo($toEmail, $Invite->store->first_name . ' ' . $Invite->store->last_name, array('first_name' => $firstName, 'last_name' => $Invite->store->last_name, 'invite_url' => $inviteURL, 'unsubscribe_url' => $unsubscribeUrl));
                                 //$toEmails[] = 'Email: ' . $toEmail . " - " . $contact['first_name'] . ' ' . $lastName . '('.$fromEmailName.')' . "\n\n";
                                 // Increment the counter
                                 $sentCount++;
                             } else {
                                 $contactInfo = print_r($contact, true);
                                 mail('*****@*****.**', 'Invite attempted but store2contact row did not match contact found in query', $contactInfo);
                             }
                         } else {
                             $contactInfo = print_r($contact, true);
                             mail('*****@*****.**', 'Invite attempted but store2contact could not be found', $contactInfo);
                         }
                     } else {
                         $contactInfo = print_r($contact, true);
                         mail('*****@*****.**', 'Invite attempted with no email address', $contactInfo);
                     }
                 }
                 // foreach upTo1000Invites
             } catch (Exception $e) {
                 $transaction->rollback();
                 $campaignSuccess = false;
             }
             // Now we have the data for our 1000 contacts set up, render the template for the organisation
             $Controller = new Controller('foo');
             $renderedView = $Controller->renderInternal(Yii::app()->basePath . '/views/mail/organisation-templates/' . $Organisations[$orgID]->email_template . ".php", array('body' => $parsedContent['body']), true);
             $message->setHtml($renderedView);
             // SEND THE MESSAGE
             if (sizeof($message->getTo())) {
                 try {
                     $response = $message->send();
                     $command = Yii::app()->db->createCommand();
                     $command->update('invite', array("status" => Invite::STATUS_SENT, "processing" => 0), array('in', 'id', $invite1000IDs));
                     $transaction->commit();
                     $campaignSuccess = true;
                 } catch (Exception $e) {
                     print $e->getMessage();
                     // mailgun returned an error - we rollback the transaction and remove the number of failed ids from the sent count
                     // consider mainatining a fail count??
                     $sentCount -= count($invite1000IDs);
                     $command = Yii::app()->db->createCommand();
                     $command->update('invite', array("status" => Invite::STATUS_MAILGUN_ERROR, "processing" => 0), array('in', 'id', $invite1000IDs));
                     $transaction->commit();
                     $msg = print_r($e, true);
                     $msg .= print_r($message, true);
                     mail('*****@*****.**', 'Mailgun error', $msg);
                 }
             }
         }
         // end of org 1000 chunk
     }
     // foreach organisations
     if ($campaignSuccess) {
         $Campaign->status = Campaign::STATUS_HAS_BEEN_RUN;
     } else {
         $Campaign->status = Campaign::STATUS_ERROR_SEND;
     }
     $Campaign->save(true, array("status"));
 }
Exemplo n.º 28
0
 public function Join($block = 0)
 {
     Auth::RequireLogin(true);
     if (!$this->auth->isLogged()) {
         $this->json->error("You need to be logged in.");
     }
     $this->Block = new Game_Block($block);
     // Make sure the game exists
     if (!$this->Block->exists()) {
         $this->json->error("Block could not be found.");
     }
     // Make sure the game is not in the past
     if ($this->Block->time != 0 && $this->Block->time < time()) {
         $this->json->error("This block is already in the past.");
     }
     $this->Account = new Account(Auth::Get("id"));
     if (!$this->Account->exists()) {
         $this->json->error("Your account could not be loaded.");
     }
     $this->Related_Account = $this->Block->account->where("id", Auth::Get("id"))->include_join_fields()->get();
     if ($this->Related_Account->exists() && $this->Related_Account->join_active) {
         $this->json->error("You are already playing this block.");
     }
     // Get the Fixture
     $this->Fixture = $this->Block->fixture->get();
     // Make sure the fixture exists
     if (!$this->Fixture->exists()) {
         $this->json->error("Fixture could not be loaded.");
     }
     // Check the limit of this block
     $this->PlayersCount = $this->Block->account->include_join_fields()->where(array("active" => 1))->count();
     if ($this->PlayersCount >= (int) $this->Fixture->type * 2) {
         $this->json->error("This game is already full!");
     }
     if ($this->Fixture->payp_cost > 0 && (!$this->Related_Account->exists() || $this->Related_Account->join_type == "game")) {
         $this->Account->credits -= $this->Fixture->payp_cost;
         $this->Account->save();
         // Add Payment Record
         $payment = new Payment();
         $payment->account_id = Auth::Get("id");
         $payment->game_block_id = $this->Block->id;
         $payment->amount = $this->Fixture->payp_cost;
         $payment->date = time();
         $payment->type = "game";
         $payment->fixture_id = $this->Fixture->id;
         $payment->paid = 0;
         $payment->status = "active";
         $payment->save();
     }
     // Cancel refund if there is one
     if ($this->Related_Account->exists() && $this->Related_Account->join_type == "block") {
         $this->LastPayment = new Payment();
         $this->LastPayment->where(array("account_id" => Auth::Get("id"), "game_block_id" => $this->Block->id, "amount <" => 0))->order_by("id", "DESC")->limit(1)->get();
         if ($this->LastPayment->exists()) {
             $this->LastPayment->status = "canceled";
             $this->LastPayment->save();
         }
     }
     // Make all invites inactive for this fixture
     $Invite = new Invite();
     $Invite->where(array("email" => Auth::Get("email"), "fixture_id" => $this->Fixture->id, "valid" => 1, "joined" => 0))->limit(1)->get();
     // Check for Invitation
     if ($Invite->exists()) {
         $Invite->joined = 1;
         $Invite->valid = 0;
         $Invite->joined_on = time();
         $Invite->joined_account = Auth::Get("id");
         // If invitation exists, mark it as accepted
         $Invite->save();
     }
     // Relate this player with a manager
     $this->PlayerManager = new Player_Manager();
     $this->PlayerManager->player_id = Auth::Get("id");
     $this->PlayerManager->manager_id = $this->Fixture->owner;
     $this->PlayerManager->save();
     // Relate Account
     $this->Block->save($this->Account);
     $this->Block->set_join_field($this->Account, "active", 1);
     if (!$this->Related_Account->exists()) {
         $this->Block->set_join_field($this->Account, "type", "game");
     }
     // Send success response
     $this->json->success();
 }
Exemplo n.º 29
0
 case validateRoute('POST', 'bonus-shop/\\d+'):
     $mailbox = new Mailbox($db, $user);
     $bonusShop = new BonusShop($db, $user, $mailbox);
     $bonusShop->buy((int) $params[1], $postdata);
     httpResponse();
     break;
 case validateRoute('GET', 'invites'):
     $invite = new Invite($db, $user);
     httpResponse($invite->query());
     break;
 case validateRoute('POST', 'invites'):
     $invite = new Invite($db, $user);
     httpResponse($invite->create());
     break;
 case validateRoute('DELETE', 'invites/\\d+'):
     $invite = new Invite($db, $user);
     httpResponse($invite->delete((int) $params[1]));
     break;
 case validateRoute('GET', 'friends'):
     $friends = new Friends($db, $user);
     httpResponse($friends->query());
     break;
 case validateRoute('POST', 'friends'):
     $friends = new Friends($db, $user);
     httpResponse($friends->create($postdata));
     break;
 case validateRoute('DELETE', 'friends/\\d+'):
     $friends = new Friends($db, $user);
     httpResponse($friends->delete((int) $params[1]));
     break;
 case validateRoute('PATCH', 'friends/\\d+'):
Exemplo n.º 30
0
 private function signup_full()
 {
     $error = '';
     // Check email
     $_POST['email'] = trim($_POST['email']);
     $email_check = $this->check_email($_POST['email']);
     if ($email_check !== TRUE) {
         $error .= $email_check;
     }
     // Check username
     $username_check = $this->check_username($_POST['username']);
     if ($username_check !== TRUE) {
         $error .= $username_check;
     }
     // Check password
     $password_check = $this->check_password($_POST['password1'], $_POST['password2']);
     if ($password_check !== TRUE) {
         $error .= $password_check;
     }
     // Error processing
     if ($error == '') {
         // No error so proceed...
         // First check if user added
         $user = User::get_by_email($_POST['email']);
         // If not then add
         if ($user == NULL) {
             $user_id = User::add($_POST['email']);
             $user = User::get_by_id($user_id);
         }
         // Do signup
         User::signup($user->id, $_POST['username'], $_POST['password1'], $this->config->encryption_salt);
         if ($this->config->send_emails == TRUE) {
             // Send 'thank you for signing up' email
             $admin = User::get_by_id($this->config->admin_users[0]);
             $to = array('name' => $_POST['username'], 'email' => $_POST['email']);
             $subject = '[' . $this->config->name . '] Welcome to ' . $this->config->name . '!';
             $body = $this->twig_string->render(file_get_contents("themes/{$this->config->theme}/emails/signup.html"), array('username' => $_POST['username'], 'app' => $this));
             // Email user
             $this->email->send_email($to, $subject, $body);
         }
         // Log signup
         if (isset($this->plugins->log)) {
             $this->plugins->log->add($user->id, 'user', NULL, 'signup');
         }
         // Admin alert email
         if ($this->config->send_emails && $this->config->signup_email_notifications == TRUE) {
             $admin = User::get_by_id($this->config->admin_users[0]);
             $to = array('name' => $admin->username, 'email' => $admin->email);
             $subject = '[' . $this->config->name . '] New signup on ' . $this->config->name . '!';
             $link = substr($this->config->url, 0, -1) . $this->url_for('users', 'show', $user->id);
             $body = $this->twig_string->render(file_get_contents("themes/{$this->config->theme}/emails/admin_signup_notification.html"), array('link' => $link, 'app' => $this));
             // Email user
             $this->email->send_email($to, $subject, $body);
         }
         // Start session
         $_SESSION['user_id'] = $user->id;
         // Check invites are enabled and the code is valid
         if ($this->config->invites->enabled == TRUE && Invite::check_code_valid($_POST['code'], $_POST['email']) == TRUE) {
             // Get invites
             $invites = Invite::list_by_code($_POST['code']);
             if (is_array($invites)) {
                 foreach ($invites as $invite) {
                     // Update invites
                     $invite->update();
                     // Log invite update
                     if (isset($this->plugins->log)) {
                         $this->plugins->log->add($_SESSION['user_id'], 'invite', $invite->id, 'accept');
                     }
                     // Update points (but only if inviting user is not an admin)
                     if (isset($this->plugins->points) && in_array($invite->user_id, $this->config->admin_users) != TRUE) {
                         // Update points
                         $this->plugins->points->update($invite->user_id, $this->plugins->points['per_invite_accepted']);
                         // Log points update
                         if (isset($this->plugins->log)) {
                             $this->plugins->log->add($invite->user_id, 'points', NULL, $this->plugins->points['per_invite_accepted'], 'invite_accepted = ' . $invite->id);
                         }
                     }
                 }
                 // end foreach
             }
             // end if is_array
         }
         // Log login
         if (isset($this->plugins->log)) {
             $this->plugins->log->add($_SESSION['user_id'], 'user', NULL, 'login');
         }
         // If redirect_to is set then redirect
         if ($this->uri['params']['redirect_to']) {
             header('Location: ' . $this->uri['params']['redirect_to']);
             exit;
         }
         // Set welcome message
         Application::flash('success', 'Welcome to ' . $this->config->name . '!');
         // Go forth!
         header('Location: ' . $this->config->url);
         exit;
     } else {
         // There was an error
         // Propagate get vars to be picked up by the form
         $this->uri['params']['email'] = $_POST['email'];
         $this->uri['params']['username'] = $_POST['username'];
         if (isset($_POST['code'])) {
             $this->code = $_POST['code'];
         }
         // Show error message
         Application::flash('error', $error);
         // Show signup form
         $this->loadView('users/add', array('title' => 'Signup'));
     }
 }