text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```php
<?php
if ( ! function_exists('clean_whitespace')) {
/**
* ToDo remove this and sanitise on output
*/
function sanitise($str) {
return clean($str . '', 'strip_all');
}
/**
* Remove Whitespace
*
* @param string $input
* @return string
*/
function clean_whitespace($input)
{
$clear = preg_replace('~[\r\n\t]+~', ' ', trim($input));
$clear = preg_replace('/ +/', ' ', $clear);
return $clear;
}
/**
* Remove any HTML or PHP content for cleanliness
* not for security/XSS use md_to_html() instead
*
* @param string $markdown
* @return string untrusted markdown
*/
function prepare_markdown($markdown)
{
// return strip_tags($markdown);
return urldecode(html_entity_decode(clean($markdown . '', 'strip_all')));
}
/**
* Convert markdown to HTML and sanitise HTML through a whitelist (htmlpurifier)
*
* @param string $markdown
* @return string sanitised html
*/
function md_to_html($markdown)
{
return clean(Markdown::convertToHtml($markdown . ''));
}
/**
* Convert markdown to Plain Text. Removes Markdown/HTML/PHP tags
*
* @param string $markdown
* @return string
*/
function md_to_str($markdown)
{
return clean_whitespace(clean(Markdown::convertToHtml($markdown . ''), 'strip_all'));
}
}
``` | /content/code_sandbox/app/Helpers/strings.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 347 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of DateFormat.
*
* @author Dave
*/
class DateFormat extends \Illuminate\Database\Eloquent\Model
{
/**
* Indicates whether the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = false;
/**
* Indicates whether the model should use soft deletes.
*
* @var bool $softDelete
*/
protected $softDelete = false;
}
``` | /content/code_sandbox/app/Models/DateFormat.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 114 |
```php
<?php
namespace App\Console\Commands;
use App\Models\Account;
use App\Models\Timezone;
use App\Models\User;
use DB;
use Hash;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use PhpSpec\Exception\Exception;
class Install extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'attendize:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install Attendize';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$version = file_get_contents(base_path('VERSION'));
try {
DB::connection();
} catch (\Exception $e) {
$this->error('Unable to connect to database.');
$this->error('Please fill valid database credentials into .env and rerun this command.');
return;
}
$this->comment('--------------------');
$this->comment('Attempting to install Attendize v' . $version);
$this->comment('--------------------');
if (!env('APP_KEY')) {
$this->info('Generating app key');
Artisan::call('key:generate');
} else {
$this->info('App key exists -- skipping');
}
$this->info('Migrating database.');
Artisan::call('migrate', ['--force' => true]);
$this->info('Database successfully migrated.');
if (!Timezone::count()) {
$this->info('Seeding DB data');
Artisan::call('db:seed', ['--force' => true]);
$this->info('Data successfully seeded');
} else {
$this->info('Data already seeded.');
}
/*
* If there is no account prompt the user to create one;
*/
if (Account::count() === 0) {
DB::beginTransaction();
try {
$this->comment('--------------------');
$this->comment('Please create an admin user.');
$this->comment('--------------------');
//Create the first user
$fname = $this->ask('Enter first name:');
$lname = $this->ask('Enter last name:');
$email = $this->ask('Enter your email:');
$password = $this->secret('Enter a password:');
$account_data['email'] = $email;
$account_data['first_name'] = $fname;
$account_data['last_name'] = $lname;
$account_data['currency_id'] = config('attendize.default_currency');
$account_data['timezone_id'] = config('attendize.default_timezone');
$account = Account::create($account_data);
$user_data['email'] = $email;
$user_data['first_name'] = $fname;
$user_data['last_name'] = $lname;
$user_data['password'] = Hash::make($password);
$user_data['account_id'] = $account->id;
$user_data['is_parent'] = 1;
$user_data['is_registered'] = 1;
$user = User::create($user_data);
DB::commit();
$this->info('Admin User Successfully Created');
} catch (Exception $e) {
DB::rollBack();
$this->error('Error Creating User');
$this->error($e);
}
}
file_put_contents(base_path('installed'), $version);
$this->comment("
_ _ _ _
/\ | | | | | (_)
/ \ | |_| |_ ___ _ __ __| |_ _______
/ /\ \| __| __/ _ \ '_ \ / _` | |_ / _ \
/ ____ \ |_| || __/ | | | (_| | |/ / __/
/_/ \_\__|\__\___|_| |_|\__,_|_/___\___|
");
$this->comment('Success! You can now run Attendize');
}
}
``` | /content/code_sandbox/app/Console/Commands/Install.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 885 |
```php
<?php
namespace App\Models;
class Country extends \Illuminate\Database\Eloquent\Model
{
public $timestamps = false;
}
``` | /content/code_sandbox/app/Models/Country.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 26 |
```php
<?php
namespace App\Models;
/**
* Class PaymentGateway
* @package App\Models
*/
class PaymentGateway extends MyBaseModel
{
public $timestamps = false;
/**
* @return array
*/
static public function getAllWithDefaultSet()
{
$payment_gateways = PaymentGateway::all()->toArray();
$payment_gateway = PaymentGateway::select('id')->where('default', 1)->get()->first();
if (empty($payment_gateway)) {
$default_payment_gateway_id = config('attendize.default_payment_gateway');
foreach ($payment_gateways as &$payment_gateway) {
if ($payment_gateway['id'] == $default_payment_gateway_id) {
$payment_gateway['default'] = 1;
}
}
}
return $payment_gateways;
}
/**
* @return \Illuminate\Config\Repository|mixed
*/
static public function getDefaultPaymentGatewayId()
{
$payment_gateway = PaymentGateway::select('id')->where('default', 1)->get()->first();
if (empty($payment_gateway)) {
$default_payment_gateway_id = config('attendize.default_payment_gateway');
return $default_payment_gateway_id;
}
return $payment_gateway['id'];
}
}
``` | /content/code_sandbox/app/Models/PaymentGateway.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 265 |
```php
<?php
namespace App\Models;
class QuestionOption extends MyBaseModel
{
/**
* Indicates if the model should be timestamped.
*
* @access public
* @var bool
*/
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @access protected
* @var array
*/
protected $fillable = ['name'];
/**
* The question associated with the question option.
*
* @access public
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function question()
{
return $this->belongsTo(\App\Models\Question::class);
}
}
``` | /content/code_sandbox/app/Models/QuestionOption.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 147 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
class Affiliate extends \Illuminate\Database\Eloquent\Model
{
/**
* The attributes that are mass assignable.
*
* @var array $fillable
*/
protected $fillable = [
'name',
'visits',
'tickets_sold',
'event_id',
'account_id',
'sales_volume'
];
/**
* The attributes that should be mutated to dates.
*
* @return array $dates
*/
public function getDates()
{
return ['created_at', 'updated_at'];
}
}
``` | /content/code_sandbox/app/Models/Affiliate.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 138 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of EventImage.
*
* @author Dave
*/
class EventImage extends MyBaseModel
{
//put your code here.
}
``` | /content/code_sandbox/app/Models/EventImage.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 54 |
```php
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
/**
* @property bool is_cancelled
* @property Order order
* @property string first_name
* @property string last_name
*/
class Attendee extends MyBaseModel
{
use SoftDeletes;
/**
* @var array $fillable
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'event_id',
'order_id',
'ticket_id',
'account_id',
'reference',
'has_arrived',
'arrival_time'
];
protected $casts = [
'is_refunded' => 'boolean',
'is_cancelled' => 'boolean',
];
/**
* Generate a private reference number for the attendee. Use for checking in the attendee.
*
*/
public static function boot()
{
parent::boot();
static::creating(function ($order) {
do {
//generate a random string using Laravel's Str::Random helper
$token = Str::Random(15);
} //check if the token already exists and if it does, try again
while (Attendee::where('private_reference_number', $token)->first());
$order->private_reference_number = $token;
});
}
/**
* @param array $attendeeIds
* @return Collection
*/
public static function findFromSelection(array $attendeeIds = [])
{
return (new static)->whereIn('id', $attendeeIds)->get();
}
/**
* The order associated with the attendee.
*
* @return BelongsTo
*/
public function order()
{
return $this->belongsTo(Order::class);
}
/**
* The ticket associated with the attendee.
*
* @return BelongsTo
*/
public function ticket()
{
return $this->belongsTo(Ticket::class);
}
/**
* The event associated with the attendee.
*
* @return BelongsTo
*/
public function event()
{
return $this->belongsTo(Event::class);
}
/**
* @return HasMany
*/
public function answers()
{
return $this->hasMany(QuestionAnswer::class);
}
/**
* Scope a query to return attendees that have not cancelled.
*
* @param $query
*
* @return mixed
*/
public function scopeWithoutCancelled($query)
{
return $query->where('attendees.is_cancelled', '=', 0);
}
/**
* Reference index is a number representing the position of
* an attendee on an order, for example if a given order has 3
* attendees, each attendee would be assigned an auto-incrementing
* integer to indicate if they were attendee 1, 2 or 3.
*
* The reference attribute is a string containing the order reference
* and the attendee's reference index.
*
* @return string
*/
public function getReferenceAttribute()
{
return $this->order->order_reference . '-' . $this->reference_index;
}
/**
* Get the full name of the attendee.
*
* @return string
*/
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
/**
* The attributes that should be mutated to dates.
*
* @return array $dates
*/
public function getDates()
{
return ['created_at', 'updated_at', 'arrival_time'];
}
}
``` | /content/code_sandbox/app/Models/Attendee.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 814 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of ReservedTickets.
*
* @author Dave
*/
class ReservedTickets extends \Illuminate\Database\Eloquent\Model
{
//put your code here
}
``` | /content/code_sandbox/app/Models/ReservedTickets.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 57 |
```php
<?php
namespace App\Models;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
/*
* Adapted from: path_to_url
*/
class MyBaseModel extends \Illuminate\Database\Eloquent\Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = true;
/**
* Indicates whether the model uses soft deletes.
*
* @var bool $softDelete
*/
protected $softDelete = true;
/**
* The validation rules of the model.
*
* @var array $rules
*/
protected $rules = [];
/**
* The validation error messages of the model.
*
* @var array $messages
*/
protected $messages = [];
/**
* The validation errors of model.
*
* @var $errors
*/
protected $errors;
/**
* Create a new model.
*
* @param int|bool $account_id
* @param int|bool $user_id
* @param bool $ignore_user_id
*
* @return \className
*/
public static function createNew($account_id = false, $user_id = false, $ignore_user_id = false)
{
$className = static::class;
$entity = new $className();
if (Auth::check()) {
if (!$ignore_user_id) {
$entity->user_id = Auth::id();
}
$entity->account_id = Auth::user()->account_id;
} elseif ($account_id || $user_id) {
if ($user_id && !$ignore_user_id) {
$entity->user_id = $user_id;
}
$entity->account_id = $account_id;
} else {
App::abort(500);
}
return $entity;
}
/**
* Validate the model instance.
*
* @param $data
*
* @return bool
*/
public function validate($data)
{
$rules = (method_exists($this, 'rules') ? $this->rules() : $this->rules);
$v = Validator::make($data, $rules, $this->messages, $this->attributes);
if ($v->fails()) {
$this->errors = $v->messages();
return false;
}
// validation pass
return true;
}
/**
* Gets the validation error messages.
*
* @param bool $returnArray
*
* @return mixed
*/
public function errors($returnArray = true)
{
return $returnArray ? $this->errors->toArray() : $this->errors;
}
/**
* Get a formatted date.
*
* @param $field
* @param bool|null|string $format
*
* @return bool|null|string
*/
public function getFormattedDate($field, $format = false)
{
if (!$format) {
$format = config('attendize.default_datetime_format');
}
return $this->$field === null ? null : $this->$field->format($format);
}
/**
* Ensures each query looks for account_id
*
* @param $query
* @param bool $accountId
* @return mixed
*/
public function scopeScope($query, $accountId = false)
{
/*
* GOD MODE - DON'T UNCOMMENT!
* returning $query before adding the account_id condition will let you
* browse all events etc. in the system.
* //return $query;
*/
if (!$accountId && Auth::check()) {
$accountId = Auth::user()->account_id;
}
if ($accountId !== false) {
$table = $this->getTable();
$query->where(function ($query) use ($accountId, $table) {
$query->whereRaw(\DB::raw('('.$table.'.account_id = '.$accountId.')'));
});
}
return $query;
}
}
``` | /content/code_sandbox/app/Models/MyBaseModel.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 894 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of DateTimeFormat.
*
* @author Dave
*/
class DateTimeFormat extends \Illuminate\Database\Eloquent\Model
{
/**
* Indicates whether the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = false;
/**
* The database table used by the model.
*
* @var string $table
*/
protected $table = 'datetime_formats';
/**
* Indicates whether the model should use soft deletes.
*
* @var bool $softDelete
*/
protected $softDelete = false;
}
``` | /content/code_sandbox/app/Models/DateTimeFormat.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 149 |
```php
<?php
namespace App\Models;
use App\Attendize\Utils;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;
class Account extends MyBaseModel
{
use SoftDeletes;
/**
* The validation rules
*
* @var array $rules
*/
protected $rules = [
'first_name' => ['required'],
'last_name' => ['required'],
'email' => ['required', 'email'],
];
/**
* The attributes that should be mutated to dates.
*
* @var array $dates
*/
public $dates = ['deleted_at'];
/**
* The validation error messages.
*
* @var array $messages
*/
protected $messages = [];
/**
* The attributes that are mass assignable.
*
* @var array $fillable
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'timezone_id',
'date_format_id',
'datetime_format_id',
'currency_id',
'name',
'last_ip',
'last_login_date',
'address1',
'address2',
'city',
'state',
'postal_code',
'country_id',
'email_footer',
'is_active',
'is_banned',
'is_beta',
'stripe_access_token',
'stripe_refresh_token',
'stripe_secret_key',
'stripe_publishable_key',
'stripe_data_raw'
];
/**
* The users associated with the account.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany(\App\Models\User::class);
}
/**
* The orders associated with the account.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function orders()
{
return $this->hasMany(\App\Models\Order::class);
}
/**
* The currency associated with the account.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function currency()
{
return $this->belongsTo(\App\Models\Currency::class);
}
/**
* Payment gateways associated with an account
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function account_payment_gateways()
{
return $this->hasMany(\App\Models\AccountPaymentGateway::class);
}
/**
* Alias for $this->account_payment_gateways()
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function gateways() {
return $this->account_payment_gateways();
}
/**
* Get an accounts active payment gateway
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function active_payment_gateway()
{
return $this->hasOne(\App\Models\AccountPaymentGateway::class, 'payment_gateway_id', 'payment_gateway_id')->where('account_id', $this->id);
}
/**
* Get an accounts gateways
*
* @param $gateway_id
* @return mixed
*/
public function getGateway($gateway_id)
{
return $this->gateways->where('payment_gateway_id', $gateway_id)->first();
}
/**
* Get a config value for a gateway
*
* @param $gateway_id
* @param $key
* @return mixed
*/
public function getGatewayConfigVal($gateway_id, $key)
{
$gateway = $this->getGateway($gateway_id);
if($gateway && is_array($gateway->config)) {
return isset($gateway->config[$key]) ? $gateway->config[$key] : false;
}
return false;
}
/**
* Get the stripe api key.
*
* @return \Illuminate\Support\Collection|mixed|static
*/
public function getStripeApiKeyAttribute()
{
if (Utils::isAttendize()) {
return $this->stripe_access_token;
}
return $this->stripe_secret_key;
}
}
``` | /content/code_sandbox/app/Models/Account.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 893 |
```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class EventAccessCodes extends MyBaseModel
{
use SoftDeletes;
/**
* @param integer $event_id
* @param string $accessCode
* @return void
*/
public static function logUsage($event_id, $accessCode)
{
(new static)::where('event_id', $event_id)
->where('code', $accessCode)
->increment('usage_count');
}
/**
* @param $code
* @param $event_id
* @return Collection
*/
public static function findFromCode($code, $event_id)
{
return (new static())
->where('code', $code)
->where('event_id', $event_id)
->get();
}
/**
* The validation rules.
*
* @return array $rules
*/
public function rules()
{
return [
'code' => 'required|string',
];
}
/**
* The Event associated with the event access code.
*
* @return BelongsTo
*/
public function event()
{
return $this->belongsTo(Event::class, 'event_id', 'id');
}
/**
* @return BelongsToMany
*/
function tickets()
{
return $this->belongsToMany(
Ticket::class,
'ticket_event_access_code',
'event_access_code_id',
'ticket_id'
)->withTimestamps();
}
}
``` | /content/code_sandbox/app/Models/EventAccessCodes.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 359 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of Timezone.
*
* @author Dave
*/
class Timezone extends \Illuminate\Database\Eloquent\Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = false;
/**
* Indicates if the model should use soft deletes.
*
* @var bool $softDelete
*/
protected $softDelete = false;
}
``` | /content/code_sandbox/app/Models/Timezone.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 116 |
```php
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Str;
use Superbalist\Money\Money;
use URL;
/**
* @property int start_date
*/
class Event extends MyBaseModel
{
use SoftDeletes;
protected $dates = ['start_date', 'end_date', 'on_sale_date'];
/**
* The validation error messages.
*
* @var array $messages
*/
protected $messages = [
'title.required' => 'You must at least give a title for your event.',
'organiser_name.required_without' => 'Please create an organiser or select an existing organiser.',
'event_image.mimes' => 'Please ensure you are uploading an image (JPG, PNG, JPEG)',
'event_image.max' => 'Please ensure the image is not larger then 3MB',
'location_venue_name.required_without' => 'Please enter a venue for your event',
'venue_name_full.required_without' => 'Please enter a venue for your event',
];
/**
* The validation rules.
*
* @return array $rules
*/
public function rules()
{
$format = config('attendize.default_datetime_format');
return [
'title' => 'required',
'description' => 'required',
'location_venue_name' => 'required_without:venue_name_full',
'venue_name_full' => 'required_without:location_venue_name',
'start_date' => 'required|date_format:"' . $format . '"',
'end_date' => 'required|date_format:"' . $format . '"',
'organiser_name' => 'required_without:organiser_id',
'event_image' => 'nullable|mimes:jpeg,jpg,png|max:3000',
];
}
/**
* The questions associated with the event.
*
* @return BelongsToMany
*/
public function questions()
{
return $this->belongsToMany(Question::class, 'event_question');
}
/**
* The questions associated with the event.
*
* @return BelongsToMany
*/
public function questions_with_trashed()
{
return $this->belongsToMany(Question::class, 'event_question')->withTrashed();
}
/**
* The images associated with the event.
*
* @return HasMany
*/
public function images()
{
return $this->hasMany(EventImage::class);
}
/**
* The messages associated with the event.
*
* @return mixed
*/
public function messages()
{
return $this->hasMany(Message::class)->orderBy('created_at', 'DESC');
}
/**
* The tickets associated with the event.
*
* @return HasMany
*/
public function tickets()
{
return $this->hasMany(Ticket::class);
}
/**
* The affiliates associated with the event.
*
* @return HasMany
*/
public function affiliates()
{
return $this->hasMany(Affiliate::class);
}
/**
* The orders associated with the event.
*
* @return HasMany
*/
public function orders()
{
return $this->hasMany(Order::class);
}
/**
* The account associated with the event.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function account()
{
return $this->belongsTo(Account::class);
}
/**
* The organizer associated with the event.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function organiser()
{
return $this->belongsTo(Organiser::class);
}
/**
* Get the embed url.
*
* @return mixed
*/
public function getEmbedUrlAttribute()
{
return str_replace(['http:', 'https:'], '', route('showEmbeddedEventPage', ['event_id' => $this->id]));
}
/**
* Get the fixed fee.
*
* @return mixed
*/
public function getFixedFeeAttribute()
{
return config('attendize.ticket_booking_fee_fixed') + $this->organiser_fee_fixed;
}
/**
* Get the percentage fee.
*
* @return mixed
*/
public function getPercentageFeeAttribute()
{
return config('attendize.ticket_booking_fee_percentage') + $this->organiser_fee_percentage;
}
/**
* Parse start_date to a Carbon instance
*
* @param string $date DateTime
*/
public function setStartDateAttribute($date)
{
$format = config('attendize.default_datetime_format');
if ($date instanceof Carbon) {
$this->attributes['start_date'] = $date->format($format);
} else {
$this->attributes['start_date'] = Carbon::createFromFormat($format, $date);
}
}
/**
* Format start date from user preferences
* @return String Formatted date
*/
public function startDateFormatted()
{
return $this->start_date->format(config('attendize.default_datetime_format'));
}
/**
* Parse end_date to a Carbon instance
*
* @param string $date DateTime
*/
public function setEndDateAttribute($date)
{
$format = config('attendize.default_datetime_format');
if ($date instanceof Carbon) {
$this->attributes['end_date'] = $date->format($format);
} else {
$this->attributes['end_date'] = Carbon::createFromFormat($format, $date);
}
}
/**
* Format end date from user preferences
* @return String Formatted date
*/
public function endDateFormatted()
{
return $this->end_date->format(config('attendize.default_datetime_format'));
}
/**
* Indicates whether the event is currently happening.
*
* @return bool
*/
public function getHappeningNowAttribute()
{
return Carbon::now()->between($this->start_date, $this->end_date);
}
/**
* Get the currency symbol.
*
* @return \Illuminate\Support\Collection
*/
public function getCurrencySymbolAttribute()
{
return $this->currency->symbol_left;
}
/**
* Get the currency code.
*
* @return \Illuminate\Support\Collection
*/
public function getCurrencyCodeAttribute()
{
return $this->currency->code;
}
/**
* Return an array of attendees and answers they gave to questions at checkout
*
* @return array
*/
public function getSurveyAnswersAttribute()
{
$rows[] = array_merge([
'Order Ref',
'Attendee Name',
'Attendee Email',
'Attendee Ticket'
], $this->questions->pluck('title')->toArray());
$attendees = $this->attendees()->has('answers')->get();
foreach ($attendees as $attendee) {
$answers = [];
foreach ($this->questions as $question) {
if (in_array($question->id, $attendee->answers->pluck('question_id')->toArray())) {
$answers[] = $attendee->answers->where('question_id', $question->id)->first()->answer_text;
} else {
$answers[] = null;
}
}
$rows[] = array_merge([
$attendee->order->order_reference,
$attendee->full_name,
$attendee->email,
$attendee->ticket->title
], $answers);
}
return $rows;
}
/**
* The attendees associated with the event.
*
* @return HasMany
*/
public function attendees()
{
return $this->hasMany(Attendee::class);
}
/**
* Get the embed html code.
*
* @return string
*/
public function getEmbedHtmlCodeAttribute()
{
return "<!--Attendize.com Ticketing Embed Code-->
<iframe style='overflow:hidden; min-height: 350px;' frameBorder='0' seamless='seamless' width='100%' height='100%' src='" . $this->embed_url . "' vspace='0' hspace='0' scrolling='auto' allowtransparency='true'></iframe>
<!--/Attendize.com Ticketing Embed Code-->";
}
/**
* Get a usable address for embedding Google Maps
*
*/
public function getMapAddressAttribute()
{
$string = $this->venue . ','
. $this->location_street_number . ','
. $this->location_address_line_1 . ','
. $this->location_address_line_2 . ','
. $this->location_state . ','
. $this->location_post_code . ','
. $this->location_country;
return urlencode($string);
}
/**
* Get the big image url.
*
* @return string
*/
public function getBgImageUrlAttribute()
{
return URL::to('/') . '/' . $this->bg_image_path;
}
/**
* Get the sales and fees volume.
*
* @return \Illuminate\Support\Collection|mixed|static
*/
public function getSalesAndFeesVoulmeAttribute()
{
return $this->sales_volume + $this->organiser_fees_volume;
}
/**
* The attributes that should be mutated to dates.
*
* @return array $dates
*/
public function getDates()
{
return ['created_at', 'updated_at', 'start_date', 'end_date'];
}
public function getIcsForEvent()
{
$siteUrl = URL::to('/');
$eventUrl = $this->getEventUrlAttribute();
$description = md_to_str($this->description);
$start_date = $this->start_date;
$end_date = $this->end_date;
$timestamp = new Carbon();
$icsTemplate = <<<ICSTemplate
BEGIN:VCALENDAR
VERSION:2.0
PRODID:{$siteUrl}
BEGIN:VEVENT
UID:{$eventUrl}
DTSTAMP:{$timestamp->format('Ymd\THis\Z')}
DTSTART:{$start_date->format('Ymd\THis\Z')}
DTEND:{$end_date->format('Ymd\THis\Z')}
SUMMARY:$this->title
LOCATION:{$this->venue_name}
DESCRIPTION:{$description}
END:VEVENT
END:VCALENDAR
ICSTemplate;
return $icsTemplate;
}
/**
* Get the url of the event.
*
* @return string
*/
public function getEventUrlAttribute()
{
return route("showEventPage", ["event_id" => $this->id, "event_slug" => Str::slug($this->title)]);
//return URL::to('/') . '/e/' . $this->id . '/' . Str::slug($this->title);
}
/**
* @param integer $accessCodeId
* @return bool
*/
public function hasAccessCode($accessCodeId)
{
return (is_null($this->access_codes()->where('id', $accessCodeId)->first()) === false);
}
/**
* The access codes associated with the event.
*
* @return HasMany
*/
public function access_codes()
{
return $this->hasMany(EventAccessCodes::class, 'event_id', 'id');
}
/**
* @return Money
*/
public function getEventRevenueAmount()
{
$currency = $this->getEventCurrency();
$eventRevenue = $this->stats()->get()->reduce(function ($eventRevenue, $statsEntry) use ($currency) {
$salesVolume = (new Money($statsEntry->sales_volume, $currency));
$organiserFeesVolume = (new Money($statsEntry->organiser_fees_volume, $currency));
return (new Money($eventRevenue, $currency))->add($salesVolume)->add($organiserFeesVolume);
});
return (new Money($eventRevenue, $currency));
}
/**
* @return \Superbalist\Money\Currency
*/
private function getEventCurrency()
{
// Get the event currency
$eventCurrency = $this->currency()->first();
// Setup the currency on the event for transformation
$currency = new \Superbalist\Money\Currency(
$eventCurrency->code,
empty($eventCurrency->symbol_left) ? $eventCurrency->symbol_right : $eventCurrency->symbol_left,
$eventCurrency->title,
!empty($eventCurrency->symbol_left)
);
return $currency;
}
/**
* The currency associated with the event.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function currency()
{
return $this->belongsTo(Currency::class);
}
/**
* The stats associated with the event.
*
* @return HasMany
*/
public function stats()
{
return $this->hasMany(EventStats::class);
}
/**
* Calculates the event organiser fee from both the fixed and percentage values based on the ticket
* price
*
* return Money
*/
public function getOrganiserFee(Money $ticketPrice)
{
$currency = $this->getEventCurrency();
$calculatedBookingFee = new Money('0', $currency);
// Fixed event organiser fees can be added without worry, defaults to zero
$eventOrganiserFeeFixed = new Money($this->organiser_fee_fixed, $currency);
$calculatedBookingFee = $calculatedBookingFee->add($eventOrganiserFeeFixed);
// We have to calculate the event organiser fee percentage from the ticket price
$eventOrganiserFeePercentage = new Money($this->organiser_fee_percentage, $currency);
$percentageFeeValue = $ticketPrice->multiply($eventOrganiserFeePercentage)->divide(100);
$calculatedBookingFee = $calculatedBookingFee->add($percentageFeeValue);
return $calculatedBookingFee;
}
}
``` | /content/code_sandbox/app/Models/Event.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 3,135 |
```php
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Http\UploadedFile;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Str;
use Image;
class Organiser extends MyBaseModel implements AuthenticatableContract
{
use Authenticatable;
/**
* The validation rules for the model.
*
* @var array $rules
*/
protected $rules = [
'name' => ['required'],
'email' => ['required', 'email'],
'organiser_logo' => ['nullable', 'mimes:jpeg,jpg,png', 'max:10000'],
];
protected $extra_rules = [
'tax_name' => ['nullable', 'max:15'],
'tax_value' => ['nullable', 'numeric'],
'tax_id' => ['nullable', 'max:100'],
];
/**
* The validation rules for the model.
*
* @var array $attributes
*/
protected $attributes = [
'tax_name' => 'Tax Name',
'tax_value' => 'Tax Rate',
'tax_id' => 'Tax ID',
];
/**
* The validation error messages for the model.
*
* @var array $messages
*/
protected $messages = [
'name.required' => 'You must at least give a name for the event organiser.',
'organiser_logo.max' => 'Please upload an image smaller than 10Mb',
'organiser_logo.size' => 'Please upload an image smaller than 10Mb',
'organiser_logo.mimes' => 'Please select a valid image type (jpeg, jpg, png)',
];
/**
* The account associated with the organiser
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function account()
{
return $this->belongsTo(\App\Models\Account::class);
}
/**
* The events associated with the organizer.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function events()
{
return $this->hasMany(\App\Models\Event::class);
}
/**
* The attendees associated with the organizer.
*
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
public function attendees()
{
return $this->hasManyThrough(\App\Models\Attendee::class, \App\Models\Event::class);
}
/**
* Get the orders related to an organiser
*
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
public function orders()
{
return $this->hasManyThrough(\App\Models\Order::class, \App\Models\Event::class);
}
/**
* Get the full logo path of the organizer.
*
* @return mixed|string
*/
public function getFullLogoPathAttribute()
{
if ($this->logo_path && (file_exists(public_path($this->logo_path)) || file_exists(config('attendize.cdn_url_user_assets') . '/' . $this->logo_path))) {
return config('attendize.cdn_url_user_assets') . '/' . $this->logo_path;
}
return config('attendize.fallback_organiser_logo_url');
}
/**
* Get the url of the organizer.
*
* @return string
*/
public function getOrganiserUrlAttribute()
{
return route('showOrganiserHome', [
'organiser_id' => $this->id,
'organiser_slug' => Str::slug($this->oraganiser_name),
]);
}
/**
* Get the sales volume of the organizer.
*
* @return mixed|number
*/
public function getOrganiserSalesVolumeAttribute()
{
return $this->events->sum('sales_volume');
}
public function getTicketsSold()
{
return $this->attendees()->where('is_cancelled', false)->count();
}
/**
* TODO:implement DailyStats method
*/
public function getDailyStats()
{
}
/**
* Set a new Logo for the Organiser
*
* @param \Illuminate\Http\UploadedFile $file
*/
public function setLogo(UploadedFile $file)
{
$filename = Str::slug($this->name).'-logo-'.$this->id.'.'.strtolower($file->getClientOriginalExtension());
// Image Directory
$imageDirectory = public_path() . '/' . config('attendize.organiser_images_path');
// Paths
$relativePath = config('attendize.organiser_images_path').'/'.$filename;
$absolutePath = public_path($relativePath);
$file->move($imageDirectory, $filename);
$img = Image::make($absolutePath);
$img->resize(250, 250, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($absolutePath);
if (file_exists($absolutePath)) {
$this->logo_path = $relativePath;
}
}
/**
* Adds extra validator rules to the organiser object depending on whether tax is required or not
*/
public function addExtraValidationRules() {
$this->rules = array_merge($this->rules, $this->extra_rules);
}
}
``` | /content/code_sandbox/app/Models/Organiser.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,159 |
```php
<?php
namespace App\Models;
class QuestionAnswer extends MyBaseModel
{
protected $fillable = [
'question_id',
'event_id',
'attendee_id',
'account_id',
'answer_text',
'questionable_id',
'questionable_type',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function event()
{
return $this->belongsToMany(\App\Models\Event::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function question()
{
return $this->belongsTo(\App\Models\Question::class)->withTrashed();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function attendee()
{
return $this->belongsTo(\App\Models\Attendee::class);
}
}
``` | /content/code_sandbox/app/Models/QuestionAnswer.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 192 |
```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Description of Questions.
*
* @author Dave
*/
class Question extends MyBaseModel
{
use SoftDeletes;
/**
* The events associated with the question.
*
* @access public
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function events()
{
return $this->belongsToMany(\App\Models\Event::class);
}
/**
* The type associated with the question.
*
* @access public
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function question_type()
{
return $this->belongsTo(\App\Models\QuestionType::class);
}
public function answers()
{
return $this->hasMany(\App\Models\QuestionAnswer::class);
}
/**
* The options associated with the question.
*
* @access public
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function options()
{
return $this->hasMany(\App\Models\QuestionOption::class);
}
public function tickets()
{
return $this->belongsToMany(\App\Models\Ticket::class);
}
/**
* Scope a query to only include active questions.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeIsEnabled($query)
{
return $query->where('is_enabled', 1);
}
}
``` | /content/code_sandbox/app/Models/Question.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 319 |
```php
<?php
namespace App\Models;
use Cookie;
use DB;
class EventStats extends \Illuminate\Database\Eloquent\Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = false;
public static $unguarded = true;
/**
* @todo This shouldn't be in a view.
* Update the amount of revenue a ticket has earned.
*
* @param int $ticket_id
* @param float $amount
* @param bool $deduct
*
* @return bool
*/
public function updateTicketRevenue($ticket_id, $amount, $deduct = false)
{
$ticket = Ticket::find($ticket_id);
if ($deduct) {
$amount = $amount * -1;
}
$ticket->sales_volume = $ticket->sales_volume + $amount;
return $ticket->save();
}
/**
* Update the amount of views a ticket has earned.
*
* @param $event_id
*
* @return bool
*/
public function updateViewCount($event_id)
{
$stats = $this->updateOrCreate([
'event_id' => $event_id,
'date' => DB::raw('CURRENT_DATE'),
]);
$cookie_name = 'visitTrack_'.$event_id.'_'.date('dmy');
if (!Cookie::get($cookie_name)) {
Cookie::queue($cookie_name, true, 60 * 24 * 14);
++$stats->unique_views;
}
++$stats->views;
return $stats->save();
}
/**
* @todo: Missing amount?
* Updates the sales volume earned by an event.
*
*/
public function updateSalesVolume($event_id)
{
$stats = $this->updateOrCreate([
'event_id' => $event_id,
'date' => DB::raw('CURRENT_DATE'),
]);
$stats->sales_volume = $stats->sales_volume + $amount;
return $stats->save();
}
/**
* Updates the number of tickets sold for the event.
*
* @param $event_id
* @param $count
*
* @return bool
*/
public function updateTicketsSoldCount($event_id, $count)
{
$stats = $this->updateOrCreate([
'event_id' => $event_id,
'date' => DB::raw('CURRENT_DATE'),
]);
$stats->increment('tickets_sold', $count);
return $stats->save();
}
}
``` | /content/code_sandbox/app/Models/EventStats.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 573 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of OrderItems.
*
* @author Dave
*/
class OrderItem extends MyBaseModel
{
/**
* Indicates if the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = false;
/**
* @var array $fillable
*/
protected $fillable = [
'title',
'quantity',
'order_id',
'unit_price',
];
}
``` | /content/code_sandbox/app/Models/OrderItem.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 117 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of Message.
*
* @author Dave
*/
class Message extends MyBaseModel
{
/**
* The attributes that are mass assignable.
*
* @var array $fillable
*/
protected $fillable = [
'message',
'subject',
'recipients',
];
/**
* The event associated with the message.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function event()
{
return $this->belongsTo(\App\Models\Event::class);
}
/**
* Get the recipient label of the model.
*
* @return string
*/
public function getRecipientsLabelAttribute()
{
if ($this->recipients == 0) {
return 'All Attendees';
}
$ticket = Ticket::scope()->find($this->recipients);
return 'Ticket: ' . $ticket->title;
}
/**
* The attributes that should be mutated to dates.
*
* @return array $dates
*/
public function getDates()
{
return ['created_at', 'updated_at', 'sent_at'];
}
}
``` | /content/code_sandbox/app/Models/Message.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 272 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of Activity.
*
* @author Dave
*/
class Activity extends \Illuminate\Database\Eloquent\Model
{
//put your code here.
}
``` | /content/code_sandbox/app/Models/Activity.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 55 |
```php
<?php
namespace App\Models;
use App\Attendize\PaymentUtils;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\SoftDeletes;
use Superbalist\Money\Money;
class Ticket extends MyBaseModel
{
use SoftDeletes;
protected $dates = ['start_sale_date', 'end_sale_date'];
protected $quantity_reserved_cache = null;
/**
* The rules to validate the model.
*
* @return array $rules
*/
public function rules()
{
$format = config('attendize.default_datetime_format');
return [
'title' => 'required',
'price' => 'required|numeric|min:0',
'description' => 'nullable',
'start_sale_date' => 'nullable|date_format:"'.$format.'"',
'end_sale_date' => 'nullable|date_format:"'.$format.'"|after:start_sale_date',
'quantity_available' => 'nullable|integer|min:'.($this->quantity_sold + $this->quantity_reserved)
];
}
/**
* The validation error messages.
*
* @var array $messages
*/
public $messages = [
'price.numeric' => 'The price must be a valid number (e.g 12.50)',
'title.required' => 'You must at least give a title for your ticket. (e.g Early Bird)',
'quantity_available.integer' => 'Please ensure the quantity available is a number.',
];
protected $perPage = 10;
/**
* The event associated with the ticket.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function event()
{
return $this->belongsTo(\App\Models\Event::class);
}
/**
* The order associated with the ticket.
* @return BelongsToMany
*/
public function orders()
{
return $this->belongsToMany(
Order::class,
'ticket_order',
'ticket_id',
'order_id'
);
}
/**
* The questions associated with the ticket.
*
* @return BelongsToMany
*/
public function questions()
{
return $this->belongsToMany(\App\Models\Question::class);
}
/**
* @return BelongsToMany
*/
function event_access_codes()
{
return $this->belongsToMany(
EventAccessCodes::class,
'ticket_event_access_code',
'ticket_id',
'event_access_code_id'
)->withTimestamps();
}
/**
* TODO:implement the reserved method.
*/
public function reserved()
{
}
/**
* Parse start_sale_date to a Carbon instance
*
* @param string $date DateTime
*/
public function setStartSaleDateAttribute($date)
{
if (!$date) {
$this->attributes['start_sale_date'] = Carbon::now();
} else {
$this->attributes['start_sale_date'] = Carbon::createFromFormat(
config('attendize.default_datetime_format'),
$date
);
}
}
/**
* Parse end_sale_date to a Carbon instance
*
* @param string|null $date DateTime
*/
public function setEndSaleDateAttribute($date)
{
if (!$date) {
$this->attributes['end_sale_date'] = null;
} else {
$this->attributes['end_sale_date'] = Carbon::createFromFormat(
config('attendize.default_datetime_format'),
$date
);
}
}
/**
* Scope a query to only include tickets that are sold out.
*
* @param $query
*/
public function scopeSoldOut($query)
{
$query->where('remaining_tickets', '=', 0);
}
/**
* Get the number of tickets remaining.
*
* @return \Illuminate\Support\Collection|int|mixed|static
*/
public function getQuantityRemainingAttribute()
{
if (is_null($this->quantity_available)) {
return 9999; //Better way to do this?
}
return $this->quantity_available - ($this->quantity_sold + $this->quantity_reserved);
}
/**
* Get the number of tickets reserved.
*
* @return mixed
*/
public function getQuantityReservedAttribute()
{
if (is_null($this->quantity_reserved_cache)) {
$reserved_total = DB::table('reserved_tickets')
->where('ticket_id', $this->id)
->where('expires', '>', Carbon::now())
->sum('quantity_reserved');
$this->quantity_reserved_cache = $reserved_total;
return $reserved_total;
}
return $this->quantity_reserved_cache;
}
/**
* Get the total price of the ticket.
*
* @return float|int
*/
public function getTotalPriceAttribute()
{
return $this->getTotalBookingFeeAttribute() + $this->price;
}
/**
* Get the total booking fee of the ticket.
*
* @return float|int
*/
public function getTotalBookingFeeAttribute()
{
return $this->getBookingFeeAttribute() + $this->getOrganiserBookingFeeAttribute();
}
/**
* Get the booking fee of the ticket.
*
* @return float|int
*/
public function getBookingFeeAttribute()
{
return PaymentUtils::isFree($this->price) ? 0 : round(
($this->price * (config('attendize.ticket_booking_fee_percentage') / 100)) + (config('attendize.ticket_booking_fee_fixed')),
2
);
}
/**
* Get the organizer's booking fee.
*
* @return float|int
*/
public function getOrganiserBookingFeeAttribute()
{
return PaymentUtils::isFree($this->price) ? 0 : round(
($this->price * ($this->event->organiser_fee_percentage / 100)) + ($this->event->organiser_fee_fixed),
2
);
}
/**
* Get the maximum and minimum range of the ticket.
*
* @return array
*/
public function getTicketMaxMinRangAttribute()
{
$range = [];
for ($i = $this->min_per_person; $i <= $this->max_per_person; $i++) {
$range[] = [$i => $i];
}
return $range;
}
/**
* Indicates if the ticket is free.
*
* @return bool
*/
public function getIsFreeAttribute()
{
return PaymentUtils::isFree($this->price);
}
/**
* Return the maximum figure to go to on dropdowns.
*
* @return int
*/
public function getSaleStatusAttribute()
{
if ($this->start_sale_date !== null && $this->start_sale_date->isFuture()) {
return config('attendize.ticket_status_before_sale_date');
}
if ($this->end_sale_date !== null && $this->end_sale_date->isPast()) {
return config('attendize.ticket_status_after_sale_date');
}
if ((int)$this->quantity_available > 0 && (int)$this->quantity_remaining <= 0) {
return config('attendize.ticket_status_sold_out');
}
if ($this->event->start_date->lte(Carbon::now())) {
return config('attendize.ticket_status_off_sale');
}
return config('attendize.ticket_status_on_sale');
}
/**
* Ticket revenue is calculated as:
*
* Sales Volume + Organiser Booking Fees - Partial Refunds
* @return Money
*/
public function getTicketRevenueAmount()
{
$currency = $this->getEventCurrency();
$salesVolume = (new Money($this->sales_volume, $currency));
$organiserFeesVolume = (new Money($this->organiser_fees_volume, $currency));
return $salesVolume->add($organiserFeesVolume);
}
/**
* @return \Superbalist\Money\Currency
*/
private function getEventCurrency()
{
// Get the event currency
$eventCurrency = $this->event()->first()->currency()->first();
// Setup the currency on the event for transformation
$currency = new \Superbalist\Money\Currency(
$eventCurrency->code,
empty($eventCurrency->symbol_left) ? $eventCurrency->symbol_right : $eventCurrency->symbol_left,
$eventCurrency->title,
!empty($eventCurrency->symbol_left)
);
return $currency;
}
}
``` | /content/code_sandbox/app/Models/Ticket.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,891 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of DiscountCode.
*
* @author Dave
*/
class DiscountCode extends \Illuminate\Database\Eloquent\Model
{
//put your code here
}
``` | /content/code_sandbox/app/Models/DiscountCode.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 57 |
```php
<?php
namespace App\Models;
class QuestionType extends \Illuminate\Database\Eloquent\Model
{
//put your code here
}
``` | /content/code_sandbox/app/Models/QuestionType.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 27 |
```php
<?php
namespace App\Models;
use App\Notifications\UserResetPassword;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
class User extends Authenticatable
{
use SoftDeletes, Notifiable;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that should be mutated to dates.
*
* @var array $dates
*/
public $dates = ['deleted_at'];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'account_id',
'first_name',
'last_name',
'phone',
'email',
'password',
'confirmation_code',
'is_registered',
'is_confirmed',
'is_parent',
'remember_token'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The account associated with the user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function account()
{
return $this->belongsTo(\App\Models\Account::class);
}
/**
* The activity associated with the user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function activity()
{
return $this->hasMany(\App\Models\Activity::class);
}
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
/**
* Get the remember token for the user.
*
* @return \Illuminate\Support\Collection|mixed|static
*/
public function getRememberToken()
{
return $this->remember_token;
}
/**
* Set the remember token for the user.
*
* @param string $value
*/
public function setRememberToken($value)
{
$this->remember_token = $value;
}
/**
* Get the name of the remember token for the user.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
/**
* Get the full name of the user.
*
* @return string
*/
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
/**
* Boot all of the bootable traits on the model.
*/
public static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->confirmation_code = Str::random();
$user->api_token = Str::random(60);
});
}
/**
* Send the password reset notification.
*
* @param string $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new UserResetPassword($token));
}
}
``` | /content/code_sandbox/app/Models/User.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 826 |
```php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class AccountPaymentGateway extends MyBaseModel
{
use softDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'payment_gateway_id',
'account_id',
'config'
];
/**
* Account associated with gateway
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function account() {
return $this->belongsTo(\App\Models\Account::class);
}
/**
* Parent payment gateway
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function payment_gateway()
{
return $this->belongsTo(\App\Models\PaymentGateway::class, 'payment_gateway_id', 'id');
}
/**
* @param $value
*
* @return mixed
*/
public function getConfigAttribute($value) {
return json_decode($value, true);
}
public function setConfigAttribute($value) {
$this->attributes['config'] = json_encode($value);
}
}
``` | /content/code_sandbox/app/Models/AccountPaymentGateway.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 248 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of OrderStatus.
*
* @author Dave
*/
class OrderStatus extends \Illuminate\Database\Eloquent\Model
{
public $timestamps = false;
}
``` | /content/code_sandbox/app/Models/OrderStatus.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 57 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of Currency.
*
* @author Dave
*/
class Currency extends \Illuminate\Database\Eloquent\Model
{
/**
* Indicates whether the model should be timestamped.
*
* @var bool $timestamps
*/
public $timestamps = false;
/**
* The database table used by the model.
*
* @var string $table
*/
protected $table = 'currencies';
/**
* Indicates whether the model should use soft deletes.
*
* @var bool $softDelete
*/
protected $softDelete = false;
/**
* The event associated with the currency.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function event()
{
return $this->belongsTo(\App\Models\Event::class);
}
}
``` | /content/code_sandbox/app/Models/Currency.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 198 |
```php
<?php
namespace App\Models;
/*
Attendize.com - Event Management & Ticketing
*/
/**
* Description of TicketStatuses.
*
* @author Dave
*/
class TicketStatus extends \Illuminate\Database\Eloquent\Model
{
public $timestamps = false;
}
``` | /content/code_sandbox/app/Models/TicketStatus.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 58 |
```php
<?php
namespace App\Transformers;
class EventTransformer extends Transformer
{
public function transform($event)
{
return [
'id' => $event['id'],
];
}
}
``` | /content/code_sandbox/app/Transformers/EventTransformer.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 44 |
```php
<?php namespace App\Models;
use File;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use PDF;
use Illuminate\Support\Str;
use Superbalist\Money\Money;
class Order extends MyBaseModel
{
use SoftDeletes;
/**
* The validation rules of the model.
*
* @var array $rules
*/
public $rules = [
'order_first_name' => ['required'],
'order_last_name' => ['required'],
'order_email' => ['required', 'email'],
];
/**
* @var array $fillable
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'order_status_id',
'amount',
'account_id',
'event_id',
'taxamt',
];
/**
* The validation error messages.
*
* @var array $messages
*/
public $messages = [
'order_first_name.required' => 'Please enter a valid first name',
'order_last_name.required' => 'Please enter a valid last name',
'order_email.email' => 'Please enter a valid email',
];
protected $casts = [
'is_business' => 'boolean',
'is_refunded' => 'boolean',
'is_partially_refunded' => 'boolean',
];
/**
* The items associated with the order.
*
* @return HasMany
*/
public function orderItems()
{
return $this->hasMany(OrderItem::class);
}
/**
* The attendees associated with the order.
*
* @return HasMany
*/
public function attendees()
{
return $this->hasMany(Attendee::class);
}
/**
* The account associated with the order.
*
* @return BelongsTo
*/
public function account()
{
return $this->belongsTo(Account::class);
}
/**
* The event associated with the order.
*
* @return BelongsTo
*/
public function event()
{
return $this->belongsTo(Event::class);
}
/**
* The tickets associated with the order.
* @return BelongsToMany
*/
public function tickets()
{
return $this->belongsToMany(
Ticket::class,
'ticket_order',
'order_id',
'ticket_id'
);
}
/**
* @return BelongsTo
*/
public function payment_gateway()
{
return $this->belongsTo(PaymentGateway::class);
}
/**
* The status associated with the order.
*
* @return BelongsTo
*/
public function orderStatus()
{
return $this->belongsTo(OrderStatus::class);
}
/**
* Get the organizer fee of the order.
*
* @return \Illuminate\Support\Collection|mixed|static
*/
public function getOrganiserAmountAttribute()
{
return $this->amount + $this->organiser_booking_fee + $this->taxamt;
}
/**
* Get the total amount of the order.
*
* @return \Illuminate\Support\Collection|mixed|static
*/
public function getTotalAmountAttribute()
{
return $this->amount + $this->organiser_booking_fee + $this->booking_fee;
}
/**
* Get the full name of the order.
*
* @return string
*/
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
/**
* Generate and save the PDF tickets.
*
* @todo Move this from the order model
*
* @return bool
*/
public function generatePdfTickets()
{
$data = [
'order' => $this,
'event' => $this->event,
'tickets' => $this->event->tickets,
'attendees' => $this->attendees,
'css' => file_get_contents(public_path('assets/stylesheet/ticket.css')),
'image' => base64_encode(file_get_contents(public_path($this->event->organiser->full_logo_path))),
];
$pdf_file_path = public_path(config('attendize.event_pdf_tickets_path')) . '/' . $this->order_reference;
$pdf_file = $pdf_file_path . '.pdf';
if (file_exists($pdf_file)) {
return true;
}
if (!is_dir($pdf_file_path)) {
File::makeDirectory(dirname($pdf_file_path), 0777, true, true);
}
PDF::setOutputMode('F'); // force to file
PDF::html('Public.ViewEvent.Partials.PDFTicket', $data, $pdf_file_path);
$this->ticket_pdf_path = config('attendize.event_pdf_tickets_path') . '/' . $this->order_reference . '.pdf';
$this->save();
return file_exists($pdf_file);
}
/**
* Boot all of the bootable traits on the model.
*/
public static function boot()
{
parent::boot();
static::creating(function ($order) {
do {
//generate a random string using Laravel's Str::Random helper
$token = Str::Random(5) . date('jn');
} //check if the token already exists and if it does, try again
while (Order::where('order_reference', $token)->first());
$order->order_reference = $token;
});
}
/**
* @return Money
*/
public function getOrderAmount()
{
// We need to show if an order has been refunded
if ($this->is_refunded) {
return $this->getRefundedAmountExcludingTax();
}
$orderValue = new Money($this->amount, $this->getEventCurrency());
$bookingFee = new Money($this->organiser_booking_fee, $this->getEventCurrency());
return $orderValue->add($bookingFee);
}
/**
* @return Money
*/
public function getOrderTaxAmount()
{
$currency = $this->getEventCurrency();
$taxAmount = (new Money($this->taxamt, $currency));
return $taxAmount;
}
/**
* @return Money
*/
public function getMaxAmountRefundable()
{
$currency = $this->getEventCurrency();
$organiserAmount = new Money($this->organiser_amount, $currency);
$refundedAmount = new Money($this->amount_refunded, $currency);
return $organiserAmount->subtract($refundedAmount);
}
/**
* @return Money
*/
public function getRefundedAmountExcludingTax()
{
// Setup the currency on the event for transformation
$currency = $this->getEventCurrency();
$taxAmount = (new Money($this->taxamt, $currency));
$amountRefunded = (new Money($this->amount_refunded, $currency));
return $amountRefunded->subtract($taxAmount);
}
/**
* @return Money
*/
public function getRefundedAmountIncludingTax()
{
return (new Money($this->amount_refunded, $this->getEventCurrency()));
}
/**
* @return Money
*/
public function getPartiallyRefundedAmount()
{
return (new Money($this->amount_refunded, $this->getEventCurrency()));
}
/**
* @return \Superbalist\Money\Currency
*/
public function getEventCurrency()
{
// Get the event currency
$eventCurrency = $this->event()->first()->currency()->first();
// Transform the event currency for use in the Money library
return new \Superbalist\Money\Currency(
$eventCurrency->code,
empty($eventCurrency->symbol_left) ? $eventCurrency->symbol_right : $eventCurrency->symbol_left,
$eventCurrency->title,
!empty($eventCurrency->symbol_left)
);
}
/**
* @return boolean
*/
public function canRefund()
{
// Guard against orders that does not contain a payment gateway, ex: Free tickets
if (is_null($this->payment_gateway)) {
return false;
}
return $this->payment_gateway->can_refund;
}
/**
* @return Collection
*/
public function getAllNonCancelledAttendees()
{
return $this->attendees()->where('is_cancelled', false)->get();
}
}
``` | /content/code_sandbox/app/Models/Order.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,893 |
```php
<?php
namespace App\Transformers;
abstract class Transformer
{
/**
* @param $item
* @return array
*/
public abstract function transform($item);
/**
* @param array $items
* @return array
*/
public function transformCollection(array $items)
{
return array_map([$this, 'transform'], $items);
}
}
``` | /content/code_sandbox/app/Transformers/Transformer.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 85 |
```php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class BladeServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Blade::directive('money', function ($expression) {
return "<?php echo number_format($expression, 2); ?>";
});
}
}
``` | /content/code_sandbox/app/Providers/BladeServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 114 |
```php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
``` | /content/code_sandbox/app/Providers/AuthServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 119 |
```php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// Only load LaravelIdeHelper if we're in development mode
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
}
}
``` | /content/code_sandbox/app/Providers/AppServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 135 |
```php
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
}
``` | /content/code_sandbox/app/Exceptions/Handler.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 288 |
```php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ConfigServiceProvider extends ServiceProvider
{
/**
* Overwrite any vendor / package configuration.
*
* This service provider is intended to provide a convenient location for you
* to overwrite any "vendor" or package configuration that you may want to
* modify before the application handles the incoming request / command.
*
* @return void
*/
public function register()
{
config([
//
]);
}
}
``` | /content/code_sandbox/app/Providers/ConfigServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 108 |
```php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}
``` | /content/code_sandbox/app/Providers/RouteServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 326 |
```php
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}
``` | /content/code_sandbox/app/Providers/EventServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 135 |
```php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
``` | /content/code_sandbox/app/Providers/BroadcastServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 73 |
```php
<?php
namespace App\Providers;
use Illuminate\Bus\Dispatcher;
use Illuminate\Support\ServiceProvider;
class BusServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @param \Illuminate\Bus\Dispatcher $dispatcher
*
* @return void
*/
public function boot(Dispatcher $dispatcher)
{
$dispatcher->mapUsing(function ($command) {
return Dispatcher::simpleMapping(
$command, 'App\Commands', 'App\Handlers\Commands'
);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
``` | /content/code_sandbox/app/Providers/BusServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 145 |
```php
<?php
namespace App\Providers;
use Form;
use Html;
use Illuminate\Support\ServiceProvider;
class HtmlMacroServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
$this->rawLabel();
$this->labelWithHelp();
$this->customCheckBox();
$this->styledFile();
$this->sortableLink();
}
private function rawLabel()
{
Form::macro('rawLabel', function ($name, $value = null, $options = []) {
$label = Form::label($name, '%s', $options);
return sprintf($label, $value);
});
}
private function labelWithHelp()
{
Form::macro('labelWithHelp', function ($name, $value, $options, $help_text) {
$label = Form::label($name, '%s', $options);
return sprintf($label, $value)
. '<a style="margin-left: 4px;font-size: 11px;" href="javascript:showHelp(' . "'" . $help_text . "'" . ');" >'
. '<i class="ico ico-question "></i>'
. '</a>';
});
}
private function customCheckBox()
{
Form::macro('customCheckbox', function ($name, $value, $checked = false, $label = false, $options = []) {
// $checkbox = Form::checkbox($name, $value = null, $checked, $options);
// $label = Form::rawLabel();
//
// $out = '<div class="checkbox custom-checkbox">
// <input type="checkbox" name="send_copy" id="send_copy" value="1">
// <label for="send_copy"> Send a copy to <b>{{$attendee->event->organiser->email}}</b></label>
// </div>';
//
// return $out;
});
}
private function styledFile()
{
Form::macro('styledFile', function ($name, $multiple = false) {
$out = '<div class="styledFile" id="input-' . $name . '">
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file ">
' . trans("basic.browse") . '… <input name="' . $name . '" type="file" ' . ($multiple ? 'multiple' : '') . '>
</span>
</span>
<input type="text" class="form-control" readonly>
<span style="display: none;" class="input-group-btn btn-upload-file">
<span class="btn btn-success ">
' . trans("basic.upload") . '
</span>
</span>
</div>
</div>';
return $out;
});
}
private function sortableLink()
{
Html::macro('sortable_link',
function ($title, $active_sort, $sort_by, $sort_order, $url_params = [], $class = '', $extra = '') {
$sort_order = $sort_order == 'asc' ? 'desc' : 'asc';
$url_params = http_build_query([
'sort_by' => $sort_by,
'sort_order' => $sort_order,
] + $url_params);
$html = "<a href='?$url_params' class='col-sort $class' $extra>";
$html .= ($active_sort == $sort_by) ? "<b>$title</b>" : $title;
$html .= ($sort_order == 'desc') ? '<i class="ico-arrow-down22"></i>' : '<i class="ico-arrow-up22"></i>';
$html .= '</a>';
return $html;
});
}
}
``` | /content/code_sandbox/app/Providers/HtmlMacroServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 855 |
```php
<?php
namespace App\Providers;
use App\Attendize\PaymentUtils;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class HelpersServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
require app_path('Helpers/helpers.php');
require app_path('Helpers/strings.php');
$this->paymentUtils();
}
/**
* Add blade custom if for PaymentUtils
*
* @return void
*/
public function paymentUtils()
{
Blade::if(
'isFree',
static function ($amount) {
return PaymentUtils::isFree($amount);
}
);
Blade::if(
'requiresPayment',
static function ($amount) {
return PaymentUtils::requiresPayment($amount);
}
);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
}
}
``` | /content/code_sandbox/app/Providers/HelpersServiceProvider.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 216 |
```php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\GeneralChecks::class,
\App\Http\Middleware\TrimStrings::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
// Attendize Middleware
\App\Http\Middleware\SetViewVariables::class
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
/**** ATTENDIZE MIDDLEWARE ****/
'first.run' => \App\Http\Middleware\FirstRunMiddleware::class,
'installed' => \App\Http\Middleware\CheckInstalled::class,
/**** OTHER MIDDLEWARE ****/
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
// REDIRECTION MIDDLEWARE
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
``` | /content/code_sandbox/app/Http/Kernel.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 792 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Organiser;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Image;
class OrganiserController extends MyBaseController
{
/**
* Show the select organiser page
*
* @return \Illuminate\Contracts\View\View
*/
public function showSelectOrganiser()
{
return view('ManageOrganiser.SelectOrganiser');
}
/**
* Show the create organiser page
*
* @return \Illuminate\Contracts\View\View
*/
public function showCreateOrganiser()
{
return view('ManageOrganiser.CreateOrganiser');
}
/**
* Create the organiser
*
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
* @throws \Symfony\Component\HttpFoundation\File\Exception\FileException
*/
public function postCreateOrganiser(Request $request)
{
$organiser = Organiser::createNew(false, false, true);
$chargeTax = $request->get('charge_tax');
if ($chargeTax == 1) {
$organiser->addExtraValidationRules();
}
if (!$organiser->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $organiser->errors(),
]);
}
$organiser->name = $request->get('name');
$organiser->about = prepare_markdown($request->get('about'));
$organiser->email = $request->get('email');
$organiser->facebook = $request->get('facebook');
$organiser->twitter = $request->get('twitter');
$organiser->confirmation_key = Str::random(15);
$organiser->tax_name = $request->get('tax_name');
$organiser->tax_value = round($request->get('tax_value'),2);
$organiser->tax_id = $request->get('tax_id');
$organiser->charge_tax = ($chargeTax == 1) ? 1 : 0;
if ($request->hasFile('organiser_logo')) {
$organiser->setLogo($request->file('organiser_logo'));
}
$organiser->save();
session()->flash('message', trans("Controllers.successfully_created_organiser"));
return response()->json([
'status' => 'success',
'message' => trans("Controllers.refreshing"),
'redirectUrl' => route('showOrganiserEvents', [
'organiser_id' => $organiser->id,
'first_run' => 1
]),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/OrganiserController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 574 |
```php
<?php
namespace App\Http\Controllers;
use App\Attendize\Utils;
use App\Models\Affiliate;
use App\Models\Event;
use App\Models\EventAccessCodes;
use App\Models\EventStats;
use Auth;
use Cookie;
use Illuminate\Http\Request;
use Mail;
use Redirect;
use Validator;
use Services\Captcha\Factory;
use Illuminate\Support\Facades\Lang;
class EventViewController extends Controller
{
protected $captchaService;
public function __construct()
{
$captchaConfig = config('attendize.captcha');
if ($captchaConfig["captcha_is_on"]) {
$this->captchaService = Factory::create($captchaConfig);
}
}
/**
* Show the homepage for an event
*
* @param Request $request
* @param $event_id
* @param string $slug
* @param bool $preview
* @return mixed
*/
public function showEventHome(Request $request, $event_id, $slug = '', $preview = false)
{
$event = Event::findOrFail($event_id);
if (!Utils::userOwns($event) && !$event->is_live) {
return view('Public.ViewEvent.EventNotLivePage');
}
$data = [
'event' => $event,
'tickets' => $event->tickets()->orderBy('sort_order', 'asc')->get(),
'is_embedded' => 0,
];
/*
* Don't record stats if we're previewing the event page from the backend or if we own the event.
*/
if (!$preview && !Auth::check()) {
$event_stats = new EventStats();
$event_stats->updateViewCount($event_id);
}
/*
* See if there is an affiliate referral in the URL
*/
if ($affiliate_ref = $request->get('ref')) {
$affiliate_ref = preg_replace("/\W|_/", '', $affiliate_ref);
if ($affiliate_ref) {
$affiliate = Affiliate::firstOrNew([
'name' => $request->get('ref'),
'event_id' => $event_id,
'account_id' => $event->account_id,
]);
++$affiliate->visits;
$affiliate->save();
Cookie::queue('affiliate_' . $event_id, $affiliate_ref, 60 * 24 * 60);
}
}
return view('Public.ViewEvent.EventPage', $data);
}
/**
* Show preview of event homepage / used for backend previewing
*
* @param $event_id
* @return mixed
*/
public function showEventHomePreview($event_id)
{
return showEventHome($event_id, true);
}
/**
* Sends a message to the organiser
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function postContactOrganiser(Request $request, $event_id)
{
$rules = [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
if (is_object($this->captchaService)) {
if (!$this->captchaService->isHuman($request)) {
return Redirect::back()
->with(['message' => trans("Controllers.incorrect_captcha"), 'failed' => true])
->withInput();
}
}
$event = Event::findOrFail($event_id);
$data = [
'sender_name' => $request->get('name'),
'sender_email' => $request->get('email'),
'message_content' => clean($request->get('message')),
'event' => $event,
];
Mail::send(Lang::locale().'.Emails.messageReceived', $data, function ($message) use ($event, $data) {
$message->to($event->organiser->email, $event->organiser->name)
->from(config('attendize.outgoing_email_noreply'), $data['sender_name'])
->replyTo($data['sender_email'], $data['sender_name'])
->subject(trans("Email.message_regarding_event", ["event"=>$event->title]));
});
return response()->json([
'status' => 'success',
'message' => trans("Controllers.message_successfully_sent"),
]);
}
public function showCalendarIcs(Request $request, $event_id)
{
$event = Event::findOrFail($event_id);
$icsContent = $event->getIcsForEvent();
return response()->make($icsContent, 200, [
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="event.ics'
]);
}
/**
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postShowHiddenTickets(Request $request, $event_id)
{
$event = Event::findOrFail($event_id);
$accessCode = strtoupper($request->get('access_code'));
if (!$accessCode) {
return response()->json([
'status' => 'error',
'message' => trans('AccessCodes.valid_code_required'),
]);
}
$unlockedHiddenTickets = $event->tickets()
->where('is_hidden', true)
->orderBy('sort_order', 'asc')
->get()
->filter(function($ticket) use ($accessCode) {
// Only return the hidden tickets that match the access code
return ($ticket->event_access_codes()->where('code', $accessCode)->get()->count() > 0);
});
if ($unlockedHiddenTickets->count() === 0) {
return response()->json([
'status' => 'error',
'message' => trans('AccessCodes.no_tickets_matched'),
]);
}
// Bump usage count
EventAccessCodes::logUsage($event_id, $accessCode);
return view('Public.ViewEvent.Partials.EventHiddenTicketsSelection', [
'event' => $event,
'tickets' => $unlockedHiddenTickets,
'is_embedded' => 0,
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventViewController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,402 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Organiser;
use File;
use Image;
use Illuminate\Http\Request;
use Validator;
class OrganiserCustomizeController extends MyBaseController
{
/**
* Show organiser setting page
*
* @param $organiser_id
* @return mixed
*/
public function showCustomize($organiser_id)
{
$data = [
'organiser' => Organiser::scope()->findOrFail($organiser_id),
];
return view('ManageOrganiser.Customize', $data);
}
/**
* Edits organiser settings / design etc.
*
* @param Request $request
* @param $organiser_id
* @return mixed
*/
public function postEditOrganiser(Request $request, $organiser_id)
{
$organiser = Organiser::scope()->find($organiser_id);
$chargeTax = $request->get('charge_tax');
if ($chargeTax == 1) {
$organiser->addExtraValidationRules();
}
if (!$organiser->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $organiser->errors(),
]);
}
$organiser->name = $request->get('name');
$organiser->about = prepare_markdown($request->get('about'));
$organiser->google_analytics_code = $request->get('google_analytics_code');
$organiser->google_tag_manager_code = $request->get('google_tag_manager_code');
$organiser->email = $request->get('email');
$organiser->enable_organiser_page = $request->get('enable_organiser_page');
$organiser->facebook = $request->get('facebook');
$organiser->twitter = $request->get('twitter');
$organiser->tax_name = $request->get('tax_name');
$organiser->tax_value = round($request->get('tax_value'), 2);
$organiser->tax_id = $request->get('tax_id');
$organiser->charge_tax = ($request->get('charge_tax') == 1) ? 1 : 0;
if ($request->get('remove_current_image') == '1') {
$organiser->logo_path = '';
}
if ($request->hasFile('organiser_logo')) {
$organiser->setLogo($request->file('organiser_logo'));
}
$organiser->save();
session()->flash('message', trans("Controllers.successfully_updated_organiser"));
return response()->json([
'status' => 'success',
'redirectUrl' => '',
]);
}
/**
* Edits organiser profile page colors / design
*
* @param Request $request
* @param $organiser_id
* @return mixed
*/
public function postEditOrganiserPageDesign(Request $request, $organiser_id)
{
$organiser = Organiser::scope()->findOrFail($organiser_id);
$rules = [
'page_bg_color' => ['required'],
'page_header_bg_color' => ['required'],
'page_text_color' => ['required'],
];
$messages = [
'page_header_bg_color.required' => trans("Controllers.error.page_header_bg_color.required"),
'page_bg_color.required' => trans("Controllers.error.page_bg_color.required"),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$organiser->page_bg_color = $request->get('page_bg_color');
$organiser->page_header_bg_color = $request->get('page_header_bg_color');
$organiser->page_text_color = $request->get('page_text_color');
$organiser->save();
return response()->json([
'status' => 'success',
'message' => trans("Controllers.organiser_design_successfully_updated"),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/OrganiserCustomizeController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 913 |
```php
<?php
namespace App\Http\Controllers;
use DateTime;
use DatePeriod;
use DateInterval;
use Carbon\Carbon;
use App\Models\Event;
use App\Models\EventStats;
class EventDashboardController extends MyBaseController
{
/**
* Show the event dashboard
*
* @param bool|false $event_id
* @return \Illuminate\View\View
*/
public function showDashboard($event_id = false)
{
$event = Event::scope()->findOrFail($event_id);
$num_days = 20;
/*
* This is a fairly hackish way to get the data for the dashboard charts. I'm sure someone
* with better SQL skill could do it in one simple query.
*
* Filling in the missing days here seems to be fast(ish) (with 20 days history), but the work
* should be done in the DB
*/
$chartData = EventStats::where('event_id', '=', $event->id)
->where('date', '>', Carbon::now()->subDays($num_days)->format('Y-m-d'))
->get()
->toArray();
$startDate = new DateTime("-$num_days days");
$dateItter = new DatePeriod(
$startDate, new DateInterval('P1D'), $num_days
);
/*
* Iterate through each possible date, if no stats exist for this date set default values
* Otherwise, if a date does exist use these values
*/
$result = [];
$tickets_data = [];
foreach ($dateItter as $date) {
$views = 0;
$sales_volume = 0;
$unique_views = 0;
$tickets_sold = 0;
$organiser_fees_volume = 0;
foreach ($chartData as $item) {
if ($item['date'] == $date->format('Y-m-d')) {
$views = $item['views'];
$sales_volume = $item['sales_volume'];
$organiser_fees_volume = $item['organiser_fees_volume'];
$unique_views = $item['unique_views'];
$tickets_sold = $item['tickets_sold'];
break;
}
}
$result[] = [
'date' => $date->format('Y-m-d'),
'views' => $views,
'unique_views' => $unique_views,
'sales_volume' => $sales_volume + $organiser_fees_volume,
'tickets_sold' => $tickets_sold,
];
}
foreach ($event->tickets as $ticket) {
$tickets_data[] = [
'value' => $ticket->quantity_sold,
'label' => $ticket->title,
];
}
$data = [
'event' => $event,
'chartData' => json_encode($result),
'ticketData' => json_encode($tickets_data),
];
return view('ManageEvent.Dashboard', $data);
}
/**
* Redirect to event dashboard
* @param Integer|false $event_id
* @return \Illuminate\Http\RedirectResponse
*/
public function redirectToDashboard($event_id = false) {
return redirect()->action(
'EventDashboardController@showDashboard', ['event_id' => $event_id]
);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventDashboardController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 716 |
```php
<?php
namespace App\Http\Controllers;
use App\Rules\Passcheck;
use Auth;
use Hash;
use Illuminate\Http\Request;
use Validator;
class UserController extends Controller
{
/**
* Show the edit user modal
*
* @return \Illuminate\Contracts\View\View
*/
public function showEditUser()
{
$data = [
'user' => Auth::user(),
];
return view('ManageUser.Modals.EditUser', $data);
}
/**
* Updates the current user
*
* @param Request $request
* @return mixed
*/
public function postEditUser(Request $request)
{
$rules = [
'email' => [
'required',
'email',
'unique:users,email,' . Auth::user()->id . ',id,account_id,' . Auth::user()->account_id
],
'password' => [new Passcheck],
'new_password' => ['min:8', 'confirmed', 'required_with:password'],
'first_name' => ['required'],
'last_name' => ['required'],
];
$messages = [
'email.email' => trans("Controllers.error.email.email"),
'email.required' => trans("Controllers.error.email.required"),
'password.passcheck' => trans("Controllers.error.password.passcheck"),
'email.unique' => trans("Controllers.error.email.unique"),
'first_name.required' => trans("Controllers.error.first_name.required"),
'last_name.required' => trans("Controllers.error.last_name.required"),
];
$validation = Validator::make($request->all(), $rules, $messages);
if ($validation->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validation->messages()->toArray(),
]);
}
$user = Auth::user();
if ($request->get('password')) {
$user->password = Hash::make($request->get('new_password'));
}
$user->first_name = $request->get('first_name');
$user->last_name = $request->get('last_name');
$user->email = $request->get('email');
$user->save();
return response()->json([
'status' => 'success',
'message' => trans("Controllers.successfully_saved_details"),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/UserController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 516 |
```php
<?php namespace App\Http\Controllers;
use App\Cancellation\OrderCancellation;
use App\Exports\AttendeesExport;
use App\Imports\AttendeesImport;
use App\Jobs\GenerateTicketJob;
use App\Jobs\SendAttendeeInviteJob;
use App\Jobs\SendOrderAttendeeTicketJob;
use App\Jobs\SendMessageToAttendeesJob;
use App\Jobs\SendMessageToAttendeeJob;
use App\Models\Attendee;
use App\Models\Event;
use App\Models\EventStats;
use App\Models\Message;
use App\Models\Order;
use App\Models\OrderItem;
use App\Services\Order as OrderService;
use App\Models\Ticket;
use Auth;
use Config;
use DB;
use Excel;
use Exception;
use Illuminate\Http\Request;
use Log;
use Mail;
use PDF;
use Validator;
use Illuminate\Support\Facades\Lang;
class EventAttendeesController extends MyBaseController
{
/**
* Show the attendees list
*
* @param Request $request
* @param $event_id
* @return View
*/
public function showAttendees(Request $request, $event_id)
{
$allowed_sorts = ['first_name', 'email', 'ticket_id', 'order_reference'];
$searchQuery = $request->get('q');
$sort_order = $request->get('sort_order') == 'asc' ? 'asc' : 'desc';
$sort_by = (in_array($request->get('sort_by'), $allowed_sorts) ? $request->get('sort_by') : 'created_at');
$event = Event::scope()->find($event_id);
if ($searchQuery) {
$attendees = $event->attendees()
->withoutCancelled()
->join('orders', 'orders.id', '=', 'attendees.order_id')
->where(function ($query) use ($searchQuery) {
$query->where('orders.order_reference', 'like', $searchQuery . '%')
->orWhere('attendees.first_name', 'like', $searchQuery . '%')
->orWhere('attendees.email', 'like', $searchQuery . '%')
->orWhere('attendees.last_name', 'like', $searchQuery . '%');
})
->orderBy(($sort_by == 'order_reference' ? 'orders.' : 'attendees.') . $sort_by, $sort_order)
->select('attendees.*', 'orders.order_reference')
->paginate();
} else {
$attendees = $event->attendees()
->join('orders', 'orders.id', '=', 'attendees.order_id')
->withoutCancelled()
->orderBy(($sort_by == 'order_reference' ? 'orders.' : 'attendees.') . $sort_by, $sort_order)
->select('attendees.*', 'orders.order_reference')
->paginate();
}
$data = [
'attendees' => $attendees,
'event' => $event,
'sort_by' => $sort_by,
'sort_order' => $sort_order,
'q' => $searchQuery ? $searchQuery : '',
];
return view('ManageEvent.Attendees', $data);
}
/**
* Show the 'Invite Attendee' modal
*
* @param Request $request
* @param $event_id
* @return string|View
*/
public function showInviteAttendee(Request $request, $event_id)
{
$event = Event::scope()->find($event_id);
/*
* If there are no tickets then we can't create an attendee
* @todo This is a bit hackish
*/
if ($event->tickets->count() === 0) {
return '<script>showMessage("'.trans("Controllers.addInviteError").'");</script>';
}
return view('ManageEvent.Modals.InviteAttendee', [
'event' => $event,
'tickets' => $event->tickets()->pluck('title', 'id'),
]);
}
/**
* Invite an attendee
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function postInviteAttendee(Request $request, $event_id)
{
$rules = [
'first_name' => 'required',
'ticket_id' => 'required|exists:tickets,id,account_id,' . \Auth::user()->account_id,
'email' => 'email|required',
];
$messages = [
'ticket_id.exists' => trans("Controllers.ticket_not_exists_error"),
'ticket_id.required' => trans("Controllers.ticket_field_required_error"),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$ticket_id = $request->get('ticket_id');
$event = Event::findOrFail($event_id);
$ticket_price = 0;
$attendee_first_name = $request->get('first_name');
$attendee_last_name = $request->get('last_name');
$attendee_email = $request->get('email');
$email_attendee = $request->get('email_ticket');
DB::beginTransaction();
try {
/*
* Create the order
*/
$order = new Order();
$order->first_name = $attendee_first_name;
$order->last_name = $attendee_last_name;
$order->email = $attendee_email;
$order->order_status_id = config('attendize.order.complete');
$order->amount = $ticket_price;
$order->account_id = Auth::user()->account_id;
$order->event_id = $event_id;
// Calculating grand total including tax
$orderService = new OrderService($ticket_price, 0, $event);
$orderService->calculateFinalCosts();
$order->taxamt = $orderService->getTaxAmount();
if ($orderService->getGrandTotal() == 0) {
$order->is_payment_received = 1;
}
$order->save();
/*
* Update qty sold
*/
$ticket = Ticket::scope()->find($ticket_id);
$ticket->increment('quantity_sold');
$ticket->increment('sales_volume', $ticket_price);
/*
* Insert order item
*/
$orderItem = new OrderItem();
$orderItem->title = $ticket->title;
$orderItem->quantity = 1;
$orderItem->order_id = $order->id;
$orderItem->unit_price = $ticket_price;
$orderItem->save();
/*
* Update the event stats
*/
$event_stats = new EventStats();
$event_stats->updateTicketsSoldCount($event_id, 1);
$event_stats->updateTicketRevenue($ticket_id, $ticket_price);
/*
* Create the attendee
*/
$attendee = new Attendee();
$attendee->first_name = $attendee_first_name;
$attendee->last_name = $attendee_last_name;
$attendee->email = $attendee_email;
$attendee->event_id = $event_id;
$attendee->order_id = $order->id;
$attendee->ticket_id = $ticket_id;
$attendee->account_id = Auth::user()->account_id;
$attendee->reference_index = 1;
$attendee->save();
if ($email_attendee == '1') {
SendAttendeeInviteJob::dispatch($attendee);
}
session()->flash('message', trans("Controllers.attendee_successfully_invited"));
DB::commit();
return response()->json([
'status' => 'success',
'redirectUrl' => route('showEventAttendees', [
'event_id' => $event_id,
]),
]);
} catch (Exception $e) {
Log::error($e);
DB::rollBack();
return response()->json([
'status' => 'error',
'error' => trans("Controllers.attendee_exception")
]);
}
}
/**
* Show the 'Import Attendee' modal
*
* @param Request $request
* @param $event_id
* @return string|View
*/
public function showImportAttendee(Request $request, $event_id)
{
$event = Event::scope()->find($event_id);
/*
* If there are no tickets then we can't create an attendee
* @todo This is a bit hackish
*/
if ($event->tickets->count() === 0) {
return '<script>showMessage("'.trans("Controllers.addInviteError").'");</script>';
}
return view('ManageEvent.Modals.ImportAttendee', [
'event' => $event,
'tickets' => $event->tickets()->pluck('title', 'id'),
]);
}
/**
* Import attendees
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function postImportAttendee(Request $request, $event_id)
{
$rules = [
'ticket_id' => 'required|exists:tickets,id,account_id,' . \Auth::user()->account_id,
'attendees_list' => 'required|mimes:csv,txt|max:5000|',
];
$messages = [
'ticket_id.exists' => trans("Controllers.ticket_not_exists_error"),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$event = Event::findOrFail($event_id);
$ticket = Ticket::scope()->find($request->get('ticket_id'));
$emailAttendees = $request->get('email_ticket');
if ($request->file('attendees_list')) {
(new AttendeesImport($event, $ticket, (bool)$emailAttendees))->import(request()->file('attendees_list'));
}
session()->flash('message', 'Attendees Successfully Invited');
return response()->json([
'status' => 'success',
'redirectUrl' => route('showEventAttendees', [
'event_id' => $event_id,
]),
]);
}
/**
* Show the printable attendee list
*
* @param $event_id
* @return View
*/
public function showPrintAttendees($event_id)
{
$data['event'] = Event::scope()->find($event_id);
$data['attendees'] = $data['event']->attendees()->withoutCancelled()->orderBy('first_name')->get();
return view('ManageEvent.PrintAttendees', $data);
}
/**
* Show the 'Message Attendee' modal
*
* @param Request $request
* @param $attendee_id
* @return View
*/
public function showMessageAttendee(Request $request, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$data = [
'attendee' => $attendee,
'event' => $attendee->event,
];
return view('ManageEvent.Modals.MessageAttendee', $data);
}
/**
* Send a message to an attendee
*
* @param Request $request
* @param $attendee_id
* @return mixed
*/
public function postMessageAttendee(Request $request, $attendee_id)
{
$rules = [
'subject' => 'required',
'message' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$attendee = Attendee::scope()->findOrFail($attendee_id);
$event = Event::scope()->findOrFail($attendee->event_id);
$subject = $request->get('subject');
$content = $request->get('message');
$send_copy = $request->get('send_copy');
/*
* Queue the emails
*/
SendMessageToAttendeeJob::dispatch($subject, $content, $event, $attendee, $send_copy);
return response()->json([
'status' => 'success',
'message' => trans("Controllers.message_successfully_sent"),
]);
}
/**
* Shows the 'Message Attendees' modal
*
* @param $event_id
* @return View
*/
public function showMessageAttendees(Request $request, $event_id)
{
$data = [
'event' => Event::scope()->find($event_id),
'tickets' => Event::scope()->find($event_id)->tickets()->pluck('title', 'id')->toArray(),
];
return view('ManageEvent.Modals.MessageAttendees', $data);
}
/**
* Send a message to attendees
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function postMessageAttendees(Request $request, $event_id)
{
$rules = [
'subject' => 'required',
'message' => 'required',
'recipients' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$message = Message::createNew();
$message->message = $request->get('message');
$message->subject = $request->get('subject');
$message->recipients = ($request->get('recipients') == 'all') ? 'all' : $request->get('recipients');
$message->event_id = $event_id;
$message->save();
/*
* Queue the emails
*/
SendMessageToAttendeesJob::dispatch($message);
return response()->json([
'status' => 'success',
'message' => 'Message Successfully Sent',
]);
}
/**
* @param $event_id
* @param $attendee_id
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function showExportTicket($event_id, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$attendee_reference = $attendee->getReferenceAttribute();
Log::debug("Exporting ticket PDF", [
'attendee_id' => $attendee_id,
'order_reference' => $attendee->order->order_reference,
'attendee_reference' => $attendee_reference,
'event_id' => $event_id
]);
$pdf_file = public_path(config('attendize.event_pdf_tickets_path')) . '/' . $attendee_reference . '.pdf';
$this->dispatchNow(new GenerateTicketJob($attendee));
return response()->download($pdf_file);
}
/**
* Downloads an export of attendees
*
* @param $event_id
* @param string $export_as (xlsx, xls, csv, html)
*/
public function showExportAttendees($event_id, $export_as = 'xls')
{
$event = Event::scope()->findOrFail($event_id);
$date = date('d-m-Y-g.i.a');
return (new AttendeesExport($event->id))->download("attendees-as-of-{$date}.{$export_as}");
}
/**
* Show the 'Edit Attendee' modal
*
* @param Request $request
* @param $event_id
* @param $attendee_id
* @return View
*/
public function showEditAttendee(Request $request, $event_id, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$data = [
'attendee' => $attendee,
'event' => $attendee->event,
'tickets' => $attendee->event->tickets->pluck('title', 'id'),
];
return view('ManageEvent.Modals.EditAttendee', $data);
}
/**
* Updates an attendee
*
* @param Request $request
* @param $event_id
* @param $attendee_id
* @return mixed
*/
public function postEditAttendee(Request $request, $event_id, $attendee_id)
{
$rules = [
'first_name' => 'required',
'ticket_id' => 'required|exists:tickets,id,account_id,' . Auth::user()->account_id,
'email' => 'required|email',
];
$messages = [
'ticket_id.exists' => trans("Controllers.ticket_not_exists_error"),
'ticket_id.required' => trans("Controllers.ticket_field_required_error"),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$attendee = Attendee::scope()->findOrFail($attendee_id);
$attendee->update($request->all());
session()->flash('message',trans("Controllers.successfully_updated_attendee"));
return response()->json([
'status' => 'success',
'id' => $attendee->id,
'redirectUrl' => '',
]);
}
/**
* Shows the 'Cancel Attendee' modal
*
* @param Request $request
* @param $event_id
* @param $attendee_id
* @return View
*/
public function showCancelAttendee(Request $request, $event_id, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$data = [
'attendee' => $attendee,
'event' => $attendee->event,
'tickets' => $attendee->event->tickets->pluck('title', 'id'),
];
return view('ManageEvent.Modals.CancelAttendee', $data);
}
/**
* Cancels an attendee
*
* @param Request $request
* @param $event_id
* @param $attendee_id
* @return mixed
*/
public function postCancelAttendee(Request $request, $event_id, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
if ($attendee->is_cancelled) {
return response()->json([
'status' => 'success',
'message' => trans("Controllers.attendee_already_cancelled"),
]);
}
// Create email data
$data = [
'attendee' => $attendee,
'email_logo' => $attendee->event->organiser->full_logo_path,
];
try {
// Cancels attendee for an order and attempts to refund
$orderCancellation = OrderCancellation::make($attendee->order, collect([$attendee]));
$orderCancellation->cancel();
$data['refund_amount'] = $orderCancellation->getRefundAmount();
} catch (Exception | OrderRefundException $e) {
Log::error($e);
return response()->json([
'status' => 'error',
'message' => $e->getMessage(),
]);
}
if ($request->get('notify_attendee') == '1') {
try {
Mail::send(Lang::locale().'.Emails.notifyCancelledAttendee', $data, function ($message) use ($attendee) {
$message->to($attendee->email, $attendee->full_name)
->from(config('attendize.outgoing_email_noreply'), $attendee->event->organiser->name)
->replyTo($attendee->event->organiser->email, $attendee->event->organiser->name)
->subject(trans("Email.your_ticket_cancelled"));
});
} catch (\Exception $e) {
Log::error($e);
// We do not want to kill the flow if the email fails
}
}
try {
// Let the user know that they have received a refund.
Mail::send(Lang::locale().'.Emails.notifyRefundedAttendee', $data, function ($message) use ($attendee) {
$message->to($attendee->email, $attendee->full_name)
->from(config('attendize.outgoing_email_noreply'), $attendee->event->organiser->name)
->replyTo($attendee->event->organiser->email, $attendee->event->organiser->name)
->subject(trans("Email.refund_from_name", ["name"=>$attendee->event->organiser->name]));
});
} catch (\Exception $e) {
Log::error($e);
// We do not want to kill the flow if the email fails
}
session()->flash('message', trans("Controllers.successfully_cancelled_attendee"));
return response()->json([
'status' => 'success',
'id' => $attendee->id,
'redirectUrl' => '',
]);
}
/**
* Show the 'Message Attendee' modal
*
* @param Request $request
* @param $attendee_id
* @return View
*/
public function showResendTicketToAttendee(Request $request, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$data = [
'attendee' => $attendee,
'event' => $attendee->event,
];
return view('ManageEvent.Modals.ResendTicketToAttendee', $data);
}
/**
* Send a message to an attendee
*
* @param Request $request
* @param $attendee_id
* @return mixed
*/
public function postResendTicketToAttendee(Request $request, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$this->dispatch(new SendOrderAttendeeTicketJob($attendee));
return response()->json([
'status' => 'success',
'message' => trans("Controllers.ticket_successfully_resent"),
]);
}
/**
* Show an attendee ticket
*
* @param Request $request
* @param $attendee_id
* @return bool
*/
public function showAttendeeTicket(Request $request, $attendee_id)
{
$attendee = Attendee::scope()->findOrFail($attendee_id);
$data = [
'order' => $attendee->order,
'event' => $attendee->event,
'tickets' => $attendee->ticket,
'attendees' => [$attendee],
'css' => file_get_contents(public_path('assets/stylesheet/ticket.css')),
'image' => base64_encode(file_get_contents(public_path($attendee->event->organiser->full_logo_path))),
];
if ($request->get('download') == '1') {
return PDF::html('Public.ViewEvent.Partials.PDFTicket', $data, 'Tickets');
}
return view('Public.ViewEvent.Partials.PDFTicket', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventAttendeesController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 5,232 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use Illuminate\Http\Request;
/*
Attendize.com - Event Management & Ticketing
*/
class EventWidgetsController extends MyBaseController
{
/**
* Show the event widgets page
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function showEventWidgets(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
$data = [
'event' => $event,
];
return view('ManageEvent.Widgets', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventWidgetsController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 137 |
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Redirect;
use View;
use Services\Captcha\Factory;
class UserLoginController extends Controller
{
protected $captchaService;
public function __construct()
{
$captchaConfig = config('attendize.captcha');
if ($captchaConfig["captcha_is_on"]) {
$this->captchaService = Factory::create($captchaConfig);
}
$this->middleware('guest');
}
/**
* Shows login form.
*
* @param Request $request
*
* @return mixed
*/
public function showLogin(Request $request)
{
/*
* If there's an ajax request to the login page assume the person has been
* logged out and redirect them to the login page
*/
if ($request->ajax()) {
return response()->json([
'status' => 'success',
'redirectUrl' => route('login'),
]);
}
return View::make('Public.LoginAndRegister.Login');
}
/**
* Handles the login request.
*
* @param Request $request
*
* @return mixed
*/
public function postLogin(Request $request)
{
$email = $request->get('email');
$password = $request->get('password');
if (empty($email) || empty($password)) {
return Redirect::back()
->with(['message' => trans('Controllers.fill_email_and_password'), 'failed' => true])
->withInput();
}
if (is_object($this->captchaService)) {
if (!$this->captchaService->isHuman($request)) {
return Redirect::back()
->with(['message' => trans("Controllers.incorrect_captcha"), 'failed' => true])
->withInput();
}
}
if (Auth::attempt(['email' => $email, 'password' => $password], true) === false) {
return Redirect::back()
->with(['message' => trans('Controllers.login_password_incorrect'), 'failed' => true])
->withInput();
}
return redirect()->intended(route('showSelectOrganiser'));
}
}
``` | /content/code_sandbox/app/Http/Controllers/UserLoginController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 478 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Organiser;
use Carbon\Carbon;
class OrganiserDashboardController extends MyBaseController
{
/**
* Show the organiser dashboard
*
* @param $organiser_id
* @return mixed
*/
public function showDashboard($organiser_id)
{
$organiser = Organiser::scope()->findOrFail($organiser_id);
$upcoming_events = $organiser->events()->where('end_date', '>=', Carbon::now())->get();
$calendar_events = [];
/* Prepare JSON array for events for use in the dashboard calendar */
foreach ($organiser->events as $event) {
$calendar_events[] = [
'title' => $event->title,
'start' => $event->start_date->toIso8601String(),
'end' => $event->end_date->toIso8601String(),
'url' => route('showEventDashboard', [
'event_id' => $event->id
]),
'color' => '#4E558F'
];
}
$data = [
'organiser' => $organiser,
'upcoming_events' => $upcoming_events,
'calendar_events' => json_encode($calendar_events),
];
return view('ManageOrganiser.Dashboard', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/OrganiserDashboardController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 296 |
```php
<?php
namespace App\Http\Controllers;
use Log;
use Auth;
use Image;
use Validator;
use App\Models\Event;
use App\Models\Organiser;
use App\Models\EventImage;
use Illuminate\Http\Request;
use Spatie\GoogleCalendar\Event as GCEvent;
class EventController extends MyBaseController
{
/**
* Show the 'Create Event' Modal
*
* @param Request $request
* @return \Illuminate\View\View
*/
public function showCreateEvent(Request $request)
{
$data = [
'modal_id' => $request->get('modal_id'),
'organisers' => Organiser::scope()->pluck('name', 'id'),
'organiser_id' => $request->get('organiser_id') ? $request->get('organiser_id') : false,
];
return view('ManageOrganiser.Modals.CreateEvent', $data);
}
/**
* Create an event
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postCreateEvent(Request $request)
{
$event = Event::createNew();
if (!$event->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $event->errors(),
]);
}
$event->title = $request->get('title');
$event->description = prepare_markdown($request->get('description'));
$event->start_date = $request->get('start_date');
/*
* Venue location info (Usually auto-filled from google maps)
*/
$is_auto_address = (trim($request->get('place_id')) !== '');
if ($is_auto_address) { /* Google auto filled */
$event->venue_name = $request->get('name');
$event->venue_name_full = $request->get('venue_name_full');
$event->location_lat = $request->get('lat');
$event->location_long = $request->get('lng');
$event->location_address = $request->get('formatted_address');
$event->location_country = $request->get('country');
$event->location_country_code = $request->get('country_short');
$event->location_state = $request->get('administrative_area_level_1');
$event->location_address_line_1 = $request->get('route');
$event->location_address_line_2 = $request->get('locality');
$event->location_post_code = $request->get('postal_code');
$event->location_street_number = $request->get('street_number');
$event->location_google_place_id = $request->get('place_id');
$event->location_is_manual = 0;
} else { /* Manually entered */
$event->venue_name = $request->get('location_venue_name');
$event->location_address_line_1 = $request->get('location_address_line_1');
$event->location_address_line_2 = $request->get('location_address_line_2');
$event->location_state = $request->get('location_state');
$event->location_post_code = $request->get('location_post_code');
$event->location_is_manual = 1;
}
$event->end_date = $request->get('end_date');
$event->currency_id = Auth::user()->account->currency_id;
//$event->timezone_id = Auth::user()->account->timezone_id;
/*
* Set a default background for the event
*/
$event->bg_type = 'image';
$event->bg_image_path = config('attendize.event_default_bg_image');
if ($request->get('organiser_name')) {
$organiser = Organiser::createNew(false, false, true);
$rules = [
'organiser_name' => ['required'],
'organiser_email' => ['required', 'email'],
];
$messages = [
'organiser_name.required' => trans("Controllers.no_organiser_name_error"),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$organiser->name = $request->get('organiser_name');
$organiser->about = prepare_markdown($request->get('organiser_about'));
$organiser->email = $request->get('organiser_email');
$organiser->facebook = $request->get('organiser_facebook');
$organiser->twitter = $request->get('organiser_twitter');
$organiser->save();
$event->organiser_id = $organiser->id;
} elseif ($request->get('organiser_id')) {
$event->organiser_id = $request->get('organiser_id');
} else { /* Somethings gone horribly wrong */
return response()->json([
'status' => 'error',
'messages' => trans("Controllers.organiser_other_error"),
]);
}
/*
* Set the event defaults.
* @todo these could do mass assigned
*/
$defaults = $event->organiser->event_defaults;
if ($defaults) {
$event->organiser_fee_fixed = $defaults->organiser_fee_fixed;
$event->organiser_fee_percentage = $defaults->organiser_fee_percentage;
$event->pre_order_display_message = $defaults->pre_order_display_message;
$event->post_order_display_message = $defaults->post_order_display_message;
$event->offline_payment_instructions = prepare_markdown($defaults->offline_payment_instructions);
$event->enable_offline_payments = $defaults->enable_offline_payments;
$event->social_show_facebook = $defaults->social_show_facebook;
$event->social_show_linkedin = $defaults->social_show_linkedin;
$event->social_show_twitter = $defaults->social_show_twitter;
$event->social_show_email = $defaults->social_show_email;
$event->social_show_whatsapp = $defaults->social_show_whatsapp;
$event->is_1d_barcode_enabled = $defaults->is_1d_barcode_enabled;
$event->ticket_border_color = $defaults->ticket_border_color;
$event->ticket_bg_color = $defaults->ticket_bg_color;
$event->ticket_text_color = $defaults->ticket_text_color;
$event->ticket_sub_text_color = $defaults->ticket_sub_text_color;
}
try {
$event->save();
} catch (\Exception $e) {
Log::error($e);
return response()->json([
'status' => 'error',
'messages' => trans("Controllers.event_create_exception"),
]);
}
if ($request->hasFile('event_image')) {
$path = public_path() . '/' . config('attendize.event_images_path');
$filename = 'event_image-' . md5(time() . $event->id) . '.' . strtolower($request->file('event_image')->getClientOriginalExtension());
$file_full_path = $path . '/' . $filename;
$request->file('event_image')->move($path, $filename);
$img = Image::make($file_full_path);
$img->resize(800, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file_full_path);
/* Upload to s3 */
\Storage::put(config('attendize.event_images_path') . '/' . $filename, file_get_contents($file_full_path));
$eventImage = EventImage::createNew();
$eventImage->image_path = config('attendize.event_images_path') . '/' . $filename;
$eventImage->event_id = $event->id;
$eventImage->save();
}
return response()->json([
'status' => 'success',
'id' => $event->id,
'redirectUrl' => route('showEventTickets', [
'event_id' => $event->id,
'first_run' => 'yup',
]),
]);
}
/**
* Edit an event
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditEvent(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
if (!$event->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $event->errors(),
]);
}
$event->is_live = $request->get('is_live');
$event->currency_id = $request->get('currency_id');
$event->title = $request->get('title');
$event->description = prepare_markdown($request->get('description'));
$event->start_date = $request->get('start_date');
$event->google_tag_manager_code = $request->get('google_tag_manager_code');
/*
* If the google place ID is the same as before then don't update the venue
*/
if (($request->get('place_id') !== $event->location_google_place_id) || $event->location_google_place_id == '') {
$is_auto_address = (trim($request->get('place_id')) !== '');
if ($is_auto_address) { /* Google auto filled */
$event->venue_name = $request->get('name');
$event->venue_name_full = $request->get('venue_name_full');
$event->location_lat = $request->get('lat');
$event->location_long = $request->get('lng');
$event->location_address = $request->get('formatted_address');
$event->location_country = $request->get('country');
$event->location_country_code = $request->get('country_short');
$event->location_state = $request->get('administrative_area_level_1');
$event->location_address_line_1 = $request->get('route');
$event->location_address_line_2 = $request->get('locality');
$event->location_post_code = $request->get('postal_code');
$event->location_street_number = $request->get('street_number');
$event->location_google_place_id = $request->get('place_id');
$event->location_is_manual = 0;
} else { /* Manually entered */
$event->venue_name = $request->get('location_venue_name');
$event->location_address_line_1 = $request->get('location_address_line_1');
$event->location_address_line_2 = $request->get('location_address_line_2');
$event->location_state = $request->get('location_state');
$event->location_post_code = $request->get('location_post_code');
$event->location_is_manual = 1;
$event->location_google_place_id = '';
$event->venue_name_full = '';
$event->location_lat = '';
$event->location_long = '';
$event->location_address = '';
$event->location_country = '';
$event->location_country_code = '';
$event->location_street_number = '';
}
}
$event->end_date = $request->get('end_date');
$event->event_image_position = $request->get('event_image_position');
if ($request->get('remove_current_image') == '1') {
EventImage::where('event_id', '=', $event->id)->delete();
}
$event->save();
if ($request->hasFile('event_image')) {
$path = public_path() . '/' . config('attendize.event_images_path');
$filename = 'event_image-' . md5(time() . $event->id) . '.' . strtolower($request->file('event_image')->getClientOriginalExtension());
$file_full_path = $path . '/' . $filename;
$request->file('event_image')->move($path, $filename);
$img = Image::make($file_full_path);
$img->resize(800, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file_full_path);
\Storage::put(config('attendize.event_images_path') . '/' . $filename, file_get_contents($file_full_path));
EventImage::where('event_id', '=', $event->id)->delete();
$eventImage = EventImage::createNew();
$eventImage->image_path = config('attendize.event_images_path') . '/' . $filename;
$eventImage->event_id = $event->id;
$eventImage->save();
}
return response()->json([
'status' => 'success',
'id' => $event->id,
'message' => trans("Controllers.event_successfully_updated"),
'redirectUrl' => '',
]);
}
/**
* Upload event image
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postUploadEventImage(Request $request)
{
if ($request->hasFile('event_image')) {
$the_file = \File::get($request->file('event_image')->getRealPath());
$file_name = 'event_details_image-' . md5(microtime()) . '.' . strtolower($request->file('event_image')->getClientOriginalExtension());
$relative_path_to_file = config('attendize.event_images_path') . '/' . $file_name;
$full_path_to_file = public_path() . '/' . $relative_path_to_file;
$img = Image::make($the_file);
$img->resize(1000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($full_path_to_file);
if (\Storage::put($file_name, $the_file)) {
return response()->json([
'link' => '/' . $relative_path_to_file,
]);
}
return response()->json([
'error' => trans("Controllers.image_upload_error"),
]);
}
}
/**
* Puplish event and redirect
* @param Integer|false $event_id
* @return \Illuminate\Http\RedirectResponse
*/
public function postMakeEventLive($event_id = false) {
$event = Event::scope()->findOrFail($event_id);
$event->is_live = 1;
$event->save();
\Session::flash('message', trans('Event.go_live'));
return redirect()->action(
'EventDashboardController@showDashboard', ['event_id' => $event_id]
);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 3,227 |
```php
<?php
namespace App\Http\Controllers;
class EventPromoteController extends MyBaseController
{
/**
* @param $event_id
* @return mixed
*/
public function showPromote($event_id)
{
$data = [
'event' => Event::scope()->find($event_id),
];
return view('ManageEvent.Promote', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventPromoteController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 86 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Organiser;
use Illuminate\Http\Request;
class OrganiserEventsController extends MyBaseController
{
/**
* Show the organiser events page
*
* @param Request $request
* @param $organiser_id
* @return mixed
*/
public function showEvents(Request $request, $organiser_id)
{
$organiser = Organiser::scope()->findOrfail($organiser_id);
$allowed_sorts = ['created_at', 'start_date', 'end_date', 'title'];
$searchQuery = $request->get('q');
$sort_by = (in_array($request->get('sort_by'), $allowed_sorts) ? $request->get('sort_by') : 'start_date');
$events = $searchQuery
? Event::scope()->with(['organiser', 'currency'])->where('title', 'like', '%' . $searchQuery . '%')->orderBy($sort_by,
'desc')->where('organiser_id', '=', $organiser_id)->paginate(12)
: Event::scope()->with(['organiser', 'currency'])->where('organiser_id', '=', $organiser_id)->orderBy($sort_by, 'desc')->paginate(12);
$data = [
'events' => $events,
'organiser' => $organiser,
'search' => [
'q' => $searchQuery ? $searchQuery : '',
'sort_by' => $request->get('sort_by') ? $request->get('sort_by') : '',
'showPast' => $request->get('past'),
],
];
return view('ManageOrganiser.Events', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/OrganiserEventsController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 380 |
```php
<?php namespace App\Http\Controllers;
use App\Cancellation\OrderCancellation;
use App\Cancellation\OrderRefundException;
use App\Exports\OrdersExport;
use App\Jobs\SendOrderConfirmationJob;
use App\Models\Attendee;
use App\Models\Event;
use App\Models\Order;
use App\Services\Order as OrderService;
use DB;
use Excel;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Log;
use Mail;
use Session;
use Validator;
use Illuminate\Support\Facades\Lang;
class EventOrdersController extends MyBaseController
{
/**
* Show event orders page
*
* @param Request $request
* @param string $event_id
* @return mixed
*/
public function showOrders(Request $request, $event_id = '')
{
$allowed_sorts = ['first_name', 'email', 'order_reference', 'order_status_id', 'created_at'];
$searchQuery = $request->get('q');
$sort_by = (in_array($request->get('sort_by'), $allowed_sorts) ? $request->get('sort_by') : 'created_at');
$sort_order = $request->get('sort_order') == 'asc' ? 'asc' : 'desc';
$event = Event::scope()->find($event_id);
if ($searchQuery) {
/*
* Strip the hash from the start of the search term in case people search for
* order references like '#EDGC67'
*/
if ($searchQuery[0] === '#') {
$searchQuery = str_replace('#', '', $searchQuery);
}
$orders = $event->orders()
->where(function ($query) use ($searchQuery) {
$query->where('order_reference', 'like', $searchQuery . '%')
->orWhere('first_name', 'like', $searchQuery . '%')
->orWhere('email', 'like', $searchQuery . '%')
->orWhere('last_name', 'like', $searchQuery . '%');
})
->orderBy($sort_by, $sort_order)
->paginate();
} else {
$orders = $event->orders()->orderBy($sort_by, $sort_order)->paginate();
}
$data = [
'orders' => $orders,
'event' => $event,
'sort_by' => $sort_by,
'sort_order' => $sort_order,
'q' => $searchQuery ? $searchQuery : '',
];
return view('ManageEvent.Orders', $data);
}
/**
* Shows 'Manage Order' modal
*
* @param Request $request
* @param $order_id
* @return mixed
*/
public function manageOrder(Request $request, $order_id)
{
$order = Order::scope()->find($order_id);
$orderService = new OrderService($order->amount, $order->booking_fee, $order->event);
$orderService->calculateFinalCosts();
$data = [
'order' => $order,
'orderService' => $orderService
];
return view('ManageEvent.Modals.ManageOrder', $data);
}
/**
* Shows 'Edit Order' modal
*
* @param Request $request
* @param $order_id
* @return mixed
*/
public function showEditOrder(Request $request, $order_id)
{
$order = Order::scope()->find($order_id);
$data = [
'order' => $order,
'event' => $order->event(),
'attendees' => $order->attendees()->withoutCancelled()->get(),
'modal_id' => $request->get('modal_id'),
];
return view('ManageEvent.Modals.EditOrder', $data);
}
/**
* Shows 'Cancel Order' modal
*
* @param Request $request
* @param $order_id
* @return mixed
*/
public function showCancelOrder(Request $request, $order_id)
{
$order = Order::scope()->find($order_id);
$data = [
'order' => $order,
'event' => $order->event(),
'attendees' => $order->attendees()->withoutCancelled()->get(),
'modal_id' => $request->get('modal_id'),
];
return view('ManageEvent.Modals.CancelOrder', $data);
}
/**
* Resend an entire order
*
* @param $order_id
*
* @return \Illuminate\Http\JsonResponse
*/
public function resendOrder($order_id)
{
$order = Order::scope()->find($order_id);
$orderService = new OrderService($order->amount, $order->booking_fee, $order->event);
$this->dispatch(new SendOrderConfirmationJob($order, $orderService));
return response()->json([
'status' => 'success',
'redirectUrl' => '',
]);
}
/**
* Cancels an order
*
* @param Request $request
* @param $order_id
* @return mixed
*/
public function postEditOrder(Request $request, $order_id)
{
$rules = [
'first_name' => ['required'],
'last_name' => ['required'],
'email' => ['required', 'email'],
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$order = Order::scope()->findOrFail($order_id);
$order->first_name = $request->get('first_name');
$order->last_name = $request->get('last_name');
$order->email = $request->get('email');
$order->update();
Session::flash('message', trans("Controllers.the_order_has_been_updated"));
return response()->json([
'status' => 'success',
'redirectUrl' => '',
]);
}
/**
* Cancels attendees in an order
* @param Request $request
* @param $order_id
* @return \Illuminate\Http\JsonResponse
* @throws \Exception
*/
public function postCancelOrder(Request $request, $order_id)
{
$validator = Validator::make(
$request->all(),
['attendees' => 'required'],
['attendees.required' => trans('Controllers.attendees_required')]
);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
/** @var Order $order */
$order = Order::scope()->findOrFail($order_id);
/** @var Collection $attendees */
$attendees = Attendee::findFromSelection($request->get('attendees'));
try {
// Cancels attendees for an order and attempts to refund
OrderCancellation::make($order, $attendees)->cancel();
} catch (OrderRefundException $e) {
Log::error($e);
return response()->json([
'status' => 'error',
'message' => $e->getMessage(),
]);
}
// Done
Session::flash('message', trans("Controllers.successfully_refunded_and_cancelled"));
return response()->json([
'status' => 'success',
'redirectUrl' => '',
]);
}
/**
* Exports order to popular file types
*
* @param $event_id
* @param string $export_as Accepted: xls, xlsx, csv, pdf, html
*/
public function showExportOrders($event_id, $export_as = 'xls')
{
$event = Event::scope()->findOrFail($event_id);
$date = date('d-m-Y-g.i.a');
return (new OrdersExport($event->id))->download("orders-as-of-{$date}.{$export_as}");
}
/**
* shows 'Message Order Creator' modal
*
* @param Request $request
* @param $order_id
* @return mixed
*/
public function showMessageOrder(Request $request, $event_id, $order_id)
{
$order = Order::scope()->findOrFail($order_id);
$data = [
'order' => $order,
'event' => $order->event,
];
return view('ManageEvent.Modals.MessageOrder', $data);
}
/**
* Sends message to order creator
*
* @param Request $request
* @param $order_id
* @return mixed
*/
public function postMessageOrder(Request $request, $event_id, $order_id)
{
$rules = [
'subject' => 'required|max:250',
'message' => 'required|max:5000',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$order = Order::scope()->findOrFail($order_id);
$data = [
'order' => $order,
'message_content' => $request->get('message'),
'subject' => $request->get('subject'),
'event' => $order->event
];
Mail::send(Lang::locale().'.Emails.messageReceived', $data, function ($message) use ($order, $data) {
$message->to($order->email, $order->full_name)
->from(config('attendize.outgoing_email_noreply'), $order->event->organiser->name)
->replyTo($order->event->organiser->email, $order->event->organiser->name)
->subject($data['subject']);
});
/* Send a copy to the Organiser with a different subject */
if ($request->get('send_copy') == '1') {
Mail::send(Lang::locale().'.Emails.messageReceived', $data, function ($message) use ($order, $data) {
$message->to($order->event->organiser->email)
->from(config('attendize.outgoing_email_noreply'), $order->event->organiser->name)
->replyTo($order->event->organiser->email, $order->event->organiser->name)
->subject($data['subject'] . trans("Email.organiser_copy"));
});
}
return response()->json([
'status' => 'success',
'message' => trans("Controllers.message_successfully_sent"),
]);
}
/**
* Mark an order as payment received
*
* @param Request $request
* @param $order_id
* @return \Illuminate\Http\JsonResponse
*/
public function postMarkPaymentReceived(Request $request, $order_id)
{
$order = Order::scope()->findOrFail($order_id);
$order->is_payment_received = 1;
$order->order_status_id = 1;
$order->save();
session()->flash('message', trans("Controllers.order_payment_status_successfully_updated"));
return response()->json([
'status' => 'success',
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventOrdersController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,502 |
```php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreEventQuestionRequest;
use App\Models\Attendee;
use App\Models\Event;
use App\Models\Question;
use App\Models\QuestionAnswer;
use App\Models\QuestionType;
use Excel;
use Illuminate\Http\Request;
use JavaScript;
/*
Attendize.com - Event Management & Ticketing
*/
class EventSurveyController extends MyBaseController
{
/**
* Show the event survey page
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function showEventSurveys(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
JavaScript::put([
'postUpdateQuestionsOrderRoute' => route('postUpdateQuestionsOrder', ['event_id' => $event_id]),
]);
$data = [
'event' => $event,
'questions' => $event->questions->sortBy('sort_order'),
'sort_order' => 'asc',
'sort_by' => 'title',
'q' => '',
];
return view('ManageEvent.Surveys', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function showCreateEventQuestion(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
return view('ManageEvent.Modals.CreateQuestion', [
'event' => $event,
'question_types' => QuestionType::all(),
]);
}
/**
* Store a newly created resource in storage.
*
* @access public
* @param StoreEventQuestionRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function postCreateEventQuestion(StoreEventQuestionRequest $request, $event_id)
{
// Get the event or display a 'not found' warning.
$event = Event::findOrFail($event_id);
// Create question.
$question = Question::createNew(false, false, true);
$question->title = $request->get('title');
$question->is_required = (bool) $request->get('is_required', false);
$question->question_type_id = $request->get('question_type_id');
$question->save();
// Get options.
$options = $request->get('option');
// Add options.
if ($options && is_array($options)) {
foreach ($options as $option_name) {
if (trim($option_name) !== '') {
$question->options()->create([
'name' => $option_name,
]);
}
}
}
// Get tickets.
$ticket_ids = $request->get('tickets');
$question->tickets()->attach($ticket_ids);
$event->questions()->attach($question->id);
session()->flash('message', trans("Controllers.successfully_created_question"));
return response()->json([
'status' => 'success',
'message' => trans("Controllers.refreshing"),
'redirectUrl' => '',
]);
}
/**
* Show the Edit Question Modal
*
* @param Request $request
* @param $event_id
* @param $question_id
* @return mixed
*/
public function showEditEventQuestion(Request $request, $event_id, $question_id)
{
$question = Question::scope()->findOrFail($question_id);
$event = Event::scope()->findOrFail($event_id);
$data = [
'question' => $question,
'event' => $event,
'question_types' => QuestionType::all(),
];
return view('ManageEvent.Modals.EditQuestion', $data);
}
/**
* Edit a question
*
* @param Request $request
* @param $event_id
* @param $question_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditEventQuestion(Request $request, $event_id, $question_id)
{
// Get the event or display a 'not found' warning.
$event = Event::scope()->findOrFail($event_id);
// Create question.
$question = Question::scope()->findOrFail($question_id);
$question->title = $request->get('title');
$question->is_required = (bool) $request->get('is_required', false);
$question->question_type_id = $request->get('question_type_id');
$question->save();
$question_type = QuestionType::find($question->question_type_id);
if ($question_type->has_options) {
// Get options.
$options = $request->get('option');
$question->options()->delete();
// Add options.
if ($options && is_array($options)) {
foreach ($options as $option_name) {
if (trim($option_name) !== '') {
$question->options()->create([
'name' => $option_name,
]);
}
}
}
}
// Get tickets.
$ticket_ids = (array)$request->get('tickets');
$question->tickets()->sync($ticket_ids);
session()->flash('message', trans("Controllers.successfully_edited_question"));
return response()->json([
'status' => 'success',
'message' => trans("Controllers.refreshing"),
'redirectUrl' => '',
]);
}
/**
* Delete a question
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postDeleteEventQuestion(Request $request, $event_id)
{
$question_id = $request->get('question_id');
$question = Question::scope()->find($question_id);
$question->answers()->delete();
if ($question->delete()) {
session()->flash('message', trans("Controllers.successfully_deleted_question"));
return response()->json([
'status' => 'success',
'message' => trans("Controllers.refreshing"),
'redirectUrl' => '',
]);
}
return response()->json([
'status' => 'error',
'id' => $question->id,
'message' => trans("Controllers.this_question_cant_be_deleted"),
]);
}
/**
* Show all attendees answers to questions
*
* @param Request $request
* @param $event_id
* @param $question_id
* @return mixed
*/
public function showEventQuestionAnswers(Request $request, $event_id, $question_id)
{
$answers = QuestionAnswer::scope()->where('question_id', $question_id)->get();
$question = Question::scope()->withTrashed()->find($question_id);
$attendees = Attendee::scope()
->has('answers')
->where('event_id', $event_id)
->get();
$data = [
'answers' => $answers,
'question' => $question,
];
return view('ManageEvent.Modals.ViewAnswers', $data);
}
/**
* Export answers to xls, csv etc.
*
* @param Request $request
* @param $event_id
* @param string $export_as
*/
public function showExportAnswers(Request $request, $event_id, $export_as = 'xlsx')
{
Excel::create('answers-as-of-' . date('d-m-Y-g.i.a'), function ($excel) use ($event_id) {
$excel->setTitle(trans("Controllers.survey_answers"));
// Chain the setters
$excel->setCreator(config('attendize.app_name'))
->setCompany(config('attendize.app_name'));
$excel->sheet('survey_answers_sheet_', function ($sheet) use ($event_id) {
$event = Event::scope()->findOrFail($event_id);
$sheet->fromArray($event->survey_answers, null, 'A1', false, false);
// Set gray background on first row
$sheet->row(1, function ($row) {
$row->setBackground('#f5f5f5');
});
});
})->export($export_as);
}
/**
* Toggle the enabled status of question
*
* @param Request $request
* @param $event_id
* @param $question_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEnableQuestion(Request $request, $event_id, $question_id)
{
$question = Question::scope()->find($question_id);
$question->is_enabled = ($question->is_enabled == 1) ? 0 : 1;
if ($question->save()) {
return response()->json([
'status' => 'success',
'message' => trans("Controllers.successfully_updated_question"),
'id' => $question->id,
]);
}
return response()->json([
'status' => 'error',
'id' => $question->id,
'message' => trans("basic.whoops"),
]);
}
/**
* Updates the sort order of event questions
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postUpdateQuestionsOrder(Request $request)
{
$question_ids = $request->get('question_ids');
$sort = 1;
foreach ($question_ids as $question_id) {
$question = Question::scope()->find($question_id);
$question->sort_order = $sort;
$question->save();
$sort++;
}
return response()->json([
'status' => 'success',
'message' => trans("Controllers.successfully_updated_question_order"),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventSurveyController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,146 |
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class IndexController extends Controller
{
/**
* redirect index page
* @param Request $request http request
* @return \Illuminate\Http\RedirectResponse
*/
public function showIndex(Request $request)
{
return redirect()->route('showSelectOrganiser');
}
}
``` | /content/code_sandbox/app/Http/Controllers/IndexController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 77 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use File;
use Illuminate\Http\Request;
use App\Models\Currency;
use Image;
use Validator;
class EventCustomizeController extends MyBaseController
{
/**
* Returns data which is required in each view, optionally combined with additional data.
*
* @param int $event_id
* @param array $additional_data
*
* @return array
*/
public function getEventViewData($event_id, $additional_data = [])
{
$event = Event::scope()->findOrFail($event_id);
$image_path = $event->organiser->full_logo_path;
if ($event->images->first() != null) {
$image_path = $event->images()->first()->image_path;
}
return array_merge([
'event' => $event,
'questions' => $event->questions()->get(),
'image_path' => $image_path,
], $additional_data);
}
/**
* Show the event customize page
*
* @param string $event_id
* @param string $tab
* @return \Illuminate\View\View
*/
public function showCustomize($event_id = '', $tab = '')
{
$data = $this->getEventViewData($event_id, [
'currencies' => Currency::pluck('title', 'id'),
'available_bg_images' => $this->getAvailableBackgroundImages(),
'available_bg_images_thumbs' => $this->getAvailableBackgroundImagesThumbs(),
'tab' => $tab,
]);
return view('ManageEvent.Customize', $data);
}
/**
* get an array of available event background images
*
* @return array
*/
public function getAvailableBackgroundImages()
{
$images = [];
$files = File::files(public_path() . '/' . config('attendize.event_bg_images'));
foreach ($files as $image) {
$images[] = str_replace(public_path(), '', $image);
}
return $images;
}
/**
* Get an array of event bg image thumbnails
*
* @return array
*/
public function getAvailableBackgroundImagesThumbs()
{
$images = [];
$files = File::files(public_path() . '/' . config('attendize.event_bg_images') . '/thumbs');
foreach ($files as $image) {
$images[] = str_replace(public_path(), '', $image);
}
return $images;
}
/**
* Edit social settings of an event
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditEventSocial(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
$rules = [
'social_share_text' => ['max:3000'],
'social_show_facebook' => ['boolean'],
'social_show_twitter' => ['boolean'],
'social_show_linkedin' => ['boolean'],
'social_show_email' => ['boolean'],
];
$messages = [
'social_share_text.max' => 'Please keep the text under 3000 characters.',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$event->social_share_text = $request->get('social_share_text', false);
$event->social_show_facebook = $request->get('social_show_facebook', false);
$event->social_show_linkedin = $request->get('social_show_linkedin', false);
$event->social_show_twitter = $request->get('social_show_twitter', false);
$event->social_show_email = $request->get('social_show_email', false);
$event->social_show_whatsapp = $request->get('social_show_whatsapp', false);
$event->save();
return response()->json([
'status' => 'success',
'message' => trans("Controllers.social_settings_successfully_updated"),
]);
}
/**
* Update ticket details
*
* @param Request $request
* @param $event_id
* @return mixed
*/
public function postEditEventTicketDesign(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
$rules = [
'ticket_border_color' => ['required'],
'ticket_bg_color' => ['required'],
'ticket_text_color' => ['required'],
'ticket_sub_text_color' => ['required'],
'is_1d_barcode_enabled' => ['required'],
];
$messages = [
'ticket_bg_color.required' => trans("Controllers.please_enter_a_background_color"),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$event->ticket_border_color = $request->get('ticket_border_color');
$event->ticket_bg_color = $request->get('ticket_bg_color');
$event->ticket_text_color = $request->get('ticket_text_color');
$event->ticket_sub_text_color = $request->get('ticket_sub_text_color');
$event->is_1d_barcode_enabled = $request->get('is_1d_barcode_enabled');
$event->save();
return response()->json([
'status' => 'success',
'message' => 'Ticket Settings Updated',
]);
}
/**
* Edit fees of an event
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditEventFees(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
$rules = [
'organiser_fee_percentage' => ['numeric', 'between:0,100'],
'organiser_fee_fixed' => ['numeric', 'between:0,100'],
];
$messages = [
'organiser_fee_percentage.numeric' => trans("validation.between.numeric", ["attribute"=>trans("Fees.service_fee_percentage"), "min"=>0, "max"=>100]),
'organiser_fee_fixed.numeric' => trans("validation.date_format", ["attribute"=>trans("Fees.service_fee_fixed_price"), "format"=>"0.00"]),
'organiser_fee_fixed.between' => trans("validation.between.numeric", ["attribute"=>trans("Fees.service_fee_fixed_price"), "min"=>0, "max"=>100]),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$event->organiser_fee_percentage = $request->get('organiser_fee_percentage');
$event->organiser_fee_fixed = $request->get('organiser_fee_fixed');
$event->save();
return response()->json([
'status' => 'success',
'message' => trans("Controllers.order_page_successfully_updated"),
]);
}
/**
* Edit the event order page settings
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditEventOrderPage(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
// Just plain text so no validation needed (hopefully)
$rules = [];
$messages = [];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$event->pre_order_display_message = trim($request->get('pre_order_display_message'));
$event->post_order_display_message = trim($request->get('post_order_display_message'));
$event->offline_payment_instructions = prepare_markdown(trim($request->get('offline_payment_instructions')));
$event->enable_offline_payments = (int)$request->get('enable_offline_payments');
$event->save();
return response()->json([
'status' => 'success',
'message' => trans("Controllers.order_page_successfully_updated"),
]);
}
/**
* Edit event page design/colors etc.
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditEventDesign(Request $request, $event_id)
{
$event = Event::scope()->findOrFail($event_id);
$rules = [
'bg_image_path' => ['mimes:jpeg,jpg,png', 'max:4000'],
];
$messages = [
'bg_image_path.mimes' => trans("validation.mimes", ["attribute"=>trans("Event.event_image"), "values"=>"JPEG, JPG, PNG"]),
'bg_image_path.max' => trans("validation.max.file", ["attribute"=>trans("Event.event_image"), "max"=>2500]),
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
if ($request->get('bg_image_path_custom') && $request->get('bg_type') == 'image') {
$event->bg_image_path = $request->get('bg_image_path_custom');
$event->bg_type = 'image';
}
if ($request->get('bg_color') && $request->get('bg_type') == 'color') {
$event->bg_color = $request->get('bg_color');
$event->bg_type = 'color';
}
/*
* Not in use for now.
*/
if ($request->hasFile('bg_image_path') && $request->get('bg_type') == 'custom_image') {
$path = public_path() . '/' . config('attendize.event_images_path');
$filename = 'event_bg-' . md5($event->id) . '.' . strtolower($request->file('bg_image_path')->getClientOriginalExtension());
$file_full_path = $path . '/' . $filename;
$request->file('bg_image_path')->move($path, $filename);
$img = Image::make($file_full_path);
$img->resize(1400, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file_full_path, 75);
$event->bg_image_path = config('attendize.event_images_path') . '/' . $filename;
$event->bg_type = 'custom_image';
\Storage::put(config('attendize.event_images_path') . '/' . $filename, file_get_contents($file_full_path));
}
$event->save();
return response()->json([
'status' => 'success',
'message' => trans("Controllers.event_page_successfully_updated"),
'runThis' => 'document.getElementById(\'previewIframe\').contentWindow.location.reload(true);',
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventCustomizeController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,552 |
```php
<?php
namespace App\Http\Controllers;
use Auth;
class MyBaseController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
}
``` | /content/code_sandbox/app/Http/Controllers/MyBaseController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 58 |
```php
<?php
namespace App\Http\Controllers;
use Redirect;
use App\Attendize\Utils;
use App\Models\Account;
use App\Models\User;
use App\Models\PaymentGateway;
use App\Models\AccountPaymentGateway;
use Hash;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Mail;
use Services\Captcha\Factory;
use Illuminate\Support\Facades\Lang;
class UserSignupController extends Controller
{
protected $auth;
protected $captchaService;
public function __construct(Guard $auth)
{
if (Account::count() > 0 && !Utils::isAttendize()) {
return redirect()->route('login')->send();
}
$this->auth = $auth;
$captchaConfig = config('attendize.captcha');
if ($captchaConfig["captcha_is_on"]) {
$this->captchaService = Factory::create($captchaConfig);
}
$this->middleware('guest');
}
public function showSignup()
{
$is_attendize = Utils::isAttendize();
return view('Public.LoginAndRegister.Signup', compact('is_attendize'));
}
/**
* Creates an account.
*
* @param Request $request
*
* @return Redirect
*/
public function postSignup(Request $request)
{
$is_attendize = Utils::isAttendizeCloud();
$this->validate($request, [
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
'first_name' => 'required',
'last_name' => 'required',
'terms_agreed' => $is_attendize ? 'required' : ''
]);
if (is_object($this->captchaService)) {
if (!$this->captchaService->isHuman($request)) {
return Redirect::back()
->with(['message' => trans("Controllers.incorrect_captcha"), 'failed' => true])
->withInput();
}
}
$account_data = $request->only(['email', 'first_name', 'last_name']);
$account_data['currency_id'] = config('attendize.default_currency');
$account_data['timezone_id'] = config('attendize.default_timezone');
$account = Account::create($account_data);
$user = new User();
$user_data = $request->only(['email', 'first_name', 'last_name']);
$user_data['password'] = Hash::make($request->get('password'));
$user_data['account_id'] = $account->id;
$user_data['is_parent'] = 1;
$user_data['is_registered'] = 1;
$user = User::create($user_data);
$payment_gateway_data = [
'payment_gateway_id' => PaymentGateway::getDefaultPaymentGatewayId(),
'account_id' => $account->id,
'config' => '{"apiKey":"","publishableKey":""}',
];
$paymentGateway = AccountPaymentGateway::create($payment_gateway_data);
if ($is_attendize) {
// TODO: Do this async?
Mail::send(Lang::locale().'.Emails.ConfirmEmail',
['first_name' => $user->first_name, 'confirmation_code' => $user->confirmation_code],
function ($message) use ($request) {
$message->to($request->get('email'), $request->get('first_name'))
->subject(trans("Email.attendize_register"));
});
}
session()->flash('message', 'Success! You can now login.');
return redirect('login');
}
/**
* Confirm a user email
*
* @param $confirmation_code
* @return mixed
*/
public function confirmEmail($confirmation_code)
{
$user = User::whereConfirmationCode($confirmation_code)->first();
if (!$user) {
return view('Public.Errors.Generic', [
'message' => trans("Controllers.confirmation_malformed"),
]);
}
$user->is_confirmed = 1;
$user->confirmation_code = null;
$user->save();
session()->flash('message', trans("Controllers.confirmation_successful"));
return redirect()->route('login');
}
}
``` | /content/code_sandbox/app/Http/Controllers/UserSignupController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 911 |
```php
<?php
namespace App\Http\Controllers;
use App\Attendize\PaymentUtils;
use App\Jobs\SendOrderNotificationJob;
use App\Jobs\SendOrderConfirmationJob;
use App\Jobs\SendOrderAttendeeTicketJob;
use App\Models\Account;
use App\Models\AccountPaymentGateway;
use App\Models\Affiliate;
use App\Models\Attendee;
use App\Models\Event;
use App\Models\EventStats;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\PaymentGateway;
use App\Models\QuestionAnswer;
use App\Models\ReservedTickets;
use App\Models\Ticket;
use App\Services\Order as OrderService;
use Services\PaymentGateway\Factory as PaymentGatewayFactory;
use Carbon\Carbon;
use Config;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Log;
use Mail;
use Omnipay;
use PDF;
use PhpSpec\Exception\Exception;
use Validator;
class EventCheckoutController extends Controller
{
/**
* Is the checkout in an embedded Iframe?
*
* @var bool
*/
protected $is_embedded;
/**
* EventCheckoutController constructor.
* @param Request $request
*/
public function __construct(Request $request)
{
/*
* See if the checkout is being called from an embedded iframe.
*/
$this->is_embedded = $request->get('is_embedded') == '1';
}
/**
* Validate a ticket request. If successful reserve the tickets and redirect to checkout
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
public function postValidateTickets(Request $request, $event_id)
{
/*
* Order expires after X min
*/
$order_expires_time = Carbon::now()->addMinutes(config('attendize.checkout_timeout_after'));
$event = Event::findOrFail($event_id);
if (!$request->has('tickets')) {
return response()->json([
'status' => 'error',
'message' => 'No tickets selected',
]);
}
$ticket_ids = $request->get('tickets');
/*
* Remove any tickets the user has reserved
*/
ReservedTickets::where('session_id', '=', session()->getId())->delete();
/*
* Go though the selected tickets and check if they're available
* , tot up the price and reserve them to prevent over selling.
*/
$validation_rules = [];
$validation_messages = [];
$tickets = [];
$order_total = 0;
$total_ticket_quantity = 0;
$booking_fee = 0;
$organiser_booking_fee = 0;
$quantity_available_validation_rules = [];
foreach ($ticket_ids as $ticket_id) {
$current_ticket_quantity = (int)$request->get('ticket_' . $ticket_id);
if ($current_ticket_quantity < 1) {
continue;
}
$total_ticket_quantity = $total_ticket_quantity + $current_ticket_quantity;
$ticket = Ticket::find($ticket_id);
$max_per_person = min($ticket->quantity_remaining, $ticket->max_per_person);
$quantity_available_validation_rules['ticket_' . $ticket_id] = [
'numeric',
'min:' . $ticket->min_per_person,
'max:' . $max_per_person
];
$quantity_available_validation_messages = [
'ticket_' . $ticket_id . '.max' => 'The maximum number of tickets you can register is ' . $max_per_person,
'ticket_' . $ticket_id . '.min' => 'You must select at least ' . $ticket->min_per_person . ' tickets.',
];
$validator = Validator::make(['ticket_' . $ticket_id => (int)$request->get('ticket_' . $ticket_id)],
$quantity_available_validation_rules, $quantity_available_validation_messages);
if ($validator->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validator->messages()->toArray(),
]);
}
$order_total = $order_total + ($current_ticket_quantity * $ticket->price);
$booking_fee = $booking_fee + ($current_ticket_quantity * $ticket->booking_fee);
$organiser_booking_fee = $organiser_booking_fee + ($current_ticket_quantity * $ticket->organiser_booking_fee);
$tickets[] = [
'ticket' => $ticket,
'qty' => $current_ticket_quantity,
'price' => ($current_ticket_quantity * $ticket->price),
'booking_fee' => ($current_ticket_quantity * $ticket->booking_fee),
'organiser_booking_fee' => ($current_ticket_quantity * $ticket->organiser_booking_fee),
'full_price' => $ticket->price + $ticket->total_booking_fee,
];
/*
* Reserve the tickets for X amount of minutes
*/
$reservedTickets = new ReservedTickets();
$reservedTickets->ticket_id = $ticket_id;
$reservedTickets->event_id = $event_id;
$reservedTickets->quantity_reserved = $current_ticket_quantity;
$reservedTickets->expires = $order_expires_time;
$reservedTickets->session_id = session()->getId();
$reservedTickets->save();
for ($i = 0; $i < $current_ticket_quantity; $i++) {
/*
* Create our validation rules here
*/
$validation_rules['ticket_holder_first_name.' . $i . '.' . $ticket_id] = ['required'];
$validation_rules['ticket_holder_last_name.' . $i . '.' . $ticket_id] = ['required'];
$validation_rules['ticket_holder_email.' . $i . '.' . $ticket_id] = ['required', 'email'];
$validation_messages['ticket_holder_first_name.' . $i . '.' . $ticket_id . '.required'] = 'Ticket holder ' . ($i + 1) . '\'s first name is required';
$validation_messages['ticket_holder_last_name.' . $i . '.' . $ticket_id . '.required'] = 'Ticket holder ' . ($i + 1) . '\'s last name is required';
$validation_messages['ticket_holder_email.' . $i . '.' . $ticket_id . '.required'] = 'Ticket holder ' . ($i + 1) . '\'s email is required';
$validation_messages['ticket_holder_email.' . $i . '.' . $ticket_id . '.email'] = 'Ticket holder ' . ($i + 1) . '\'s email appears to be invalid';
/*
* Validation rules for custom questions
*/
foreach ($ticket->questions as $question) {
if ($question->is_required && $question->is_enabled) {
$validation_rules['ticket_holder_questions.' . $ticket_id . '.' . $i . '.' . $question->id] = ['required'];
$validation_messages['ticket_holder_questions.' . $ticket_id . '.' . $i . '.' . $question->id . '.required'] = "This question is required";
}
}
}
}
if (empty($tickets)) {
return response()->json([
'status' => 'error',
'message' => 'No tickets selected.',
]);
}
$activeAccountPaymentGateway = $event->account->getGateway($event->account->payment_gateway_id);
//if no payment gateway configured and no offline pay, don't go to the next step and show user error
if (empty($activeAccountPaymentGateway) && !$event->enable_offline_payments) {
return response()->json([
'status' => 'error',
'message' => 'No payment gateway configured',
]);
}
$paymentGateway = $activeAccountPaymentGateway ? $activeAccountPaymentGateway->payment_gateway : false;
/*
* The 'ticket_order_{event_id}' session stores everything we need to complete the transaction.
*/
session()->put('ticket_order_' . $event->id, [
'validation_rules' => $validation_rules,
'validation_messages' => $validation_messages,
'event_id' => $event->id,
'tickets' => $tickets,
'total_ticket_quantity' => $total_ticket_quantity,
'order_started' => time(),
'expires' => $order_expires_time,
'reserved_tickets_id' => $reservedTickets->id,
'order_total' => $order_total,
'booking_fee' => $booking_fee,
'organiser_booking_fee' => $organiser_booking_fee,
'total_booking_fee' => $booking_fee + $organiser_booking_fee,
'order_requires_payment' => PaymentUtils::requiresPayment($order_total),
'account_id' => $event->account->id,
'affiliate_referral' => Cookie::get('affiliate_' . $event_id),
'account_payment_gateway' => $activeAccountPaymentGateway,
'payment_gateway' => $paymentGateway
]);
/*
* If we're this far assume everything is OK and redirect them
* to the the checkout page.
*/
if ($request->ajax()) {
return response()->json([
'status' => 'success',
'isEmbedded' => $this->is_embedded,
'redirectUrl' => route('showEventCheckout', [
'event_id' => $event_id,
]) . '#order_form',
]);
}
/*
* Maybe display something prettier than this?
*/
exit('Please enable Javascript in your browser.');
}
/**
* Show the checkout page
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/
public function showEventCheckout(Request $request, $event_id)
{
$order_session = session()->get('ticket_order_' . $event_id);
if (!$order_session || $order_session['expires'] < Carbon::now()) {
$route_name = $this->is_embedded ? 'showEmbeddedEventPage' : 'showEventPage';
return redirect()->route($route_name, ['event_id' => $event_id]);
}
$secondsToExpire = Carbon::now()->diffInSeconds($order_session['expires']);
$event = Event::findorFail($order_session['event_id']);
$orderService = new OrderService($order_session['order_total'], $order_session['total_booking_fee'], $event);
$orderService->calculateFinalCosts();
$data = $order_session + [
'event' => $event,
'secondsToExpire' => $secondsToExpire,
'is_embedded' => $this->is_embedded,
'orderService' => $orderService
];
if ($this->is_embedded) {
return view('Public.ViewEvent.Embedded.EventPageCheckout', $data);
}
return view('Public.ViewEvent.EventPageCheckout', $data);
}
public function postValidateOrder(Request $request, $event_id)
{
//If there's no session kill the request and redirect back to the event homepage.
if (!session()->get('ticket_order_' . $event_id)) {
return response()->json([
'status' => 'error',
'message' => 'Your session has expired.',
'redirectUrl' => route('showEventPage', [
'event_id' => $event_id,
])
]);
}
$request_data = session()->get('ticket_order_' . $event_id . ".request_data");
$request_data = (!empty($request_data[0])) ? array_merge($request_data[0], $request->all())
: $request->all();
session()->remove('ticket_order_' . $event_id . '.request_data');
session()->push('ticket_order_' . $event_id . '.request_data', $request_data);
$event = Event::findOrFail($event_id);
$order = new Order();
$ticket_order = session()->get('ticket_order_' . $event_id);
$validation_rules = $ticket_order['validation_rules'];
$validation_messages = $ticket_order['validation_messages'];
$order->rules = $order->rules + $validation_rules;
$order->messages = $order->messages + $validation_messages;
if ($request->has('is_business') && $request->get('is_business')) {
// Dynamic validation on the new business fields, only gets validated if business selected
$businessRules = [
'business_name' => 'required',
'business_tax_number' => 'required',
'business_address_line1' => 'required',
'business_address_city' => 'required',
'business_address_code' => 'required',
];
$businessMessages = [
'business_name.required' => 'Please enter a valid business name',
'business_tax_number.required' => 'Please enter a valid business tax number',
'business_address_line1.required' => 'Please enter a valid street address',
'business_address_city.required' => 'Please enter a valid city',
'business_address_code.required' => 'Please enter a valid code',
];
$order->rules = $order->rules + $businessRules;
$order->messages = $order->messages + $businessMessages;
}
if (!$order->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $order->errors(),
]);
}
return response()->json([
'status' => 'success',
'redirectUrl' => route('showEventPayment', [
'event_id' => $event_id,
'is_embedded' => $this->is_embedded
])
]);
}
public function showEventPayment(Request $request, $event_id)
{
$order_session = session()->get('ticket_order_' . $event_id);
$event = Event::findOrFail($event_id);
$payment_gateway = $order_session['payment_gateway'];
$order_total = $order_session['order_total'];
$account_payment_gateway = $order_session['account_payment_gateway'];
$orderService = new OrderService($order_session['order_total'], $order_session['total_booking_fee'], $event);
$orderService->calculateFinalCosts();
$payment_failed = $request->get('is_payment_failed') ? 1 : 0;
$secondsToExpire = Carbon::now()->diffInSeconds($order_session['expires']);
$viewData = ['event' => $event,
'tickets' => $order_session['tickets'],
'order_total' => $order_total,
'orderService' => $orderService,
'order_requires_payment' => PaymentUtils::requiresPayment($order_total),
'account_payment_gateway' => $account_payment_gateway,
'payment_gateway' => $payment_gateway,
'secondsToExpire' => $secondsToExpire,
'payment_failed' => $payment_failed
];
return view('Public.ViewEvent.EventPagePayment', $viewData);
}
/**
* Create the order and start the payment for the order via Omnipay
*
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
* @throws \Exception
*/
public function postCreateOrder(Request $request, $event_id)
{
$request_data = $ticket_order = session()->get('ticket_order_' . $event_id . ".request_data",[0 => []]);
$request_data = array_merge($request_data[0], $request->except(['cardnumber', 'cvc']));
session()->remove('ticket_order_' . $event_id . '.request_data');
session()->push('ticket_order_' . $event_id . '.request_data', $request_data);
$ticket_order = session()->get('ticket_order_' . $event_id);
$event = Event::findOrFail($event_id);
$order_requires_payment = $ticket_order['order_requires_payment'];
if ($order_requires_payment && $request->get('pay_offline') && $event->enable_offline_payments) {
return $this->completeOrder($event_id);
}
if (!$order_requires_payment) {
return $this->completeOrder($event_id);
}
try {
$order_service = new OrderService($ticket_order['order_total'], $ticket_order['total_booking_fee'], $event);
$order_service->calculateFinalCosts();
$payment_gateway_config = $ticket_order['account_payment_gateway']->config + [
'testMode' => config('attendize.enable_test_payments')];
$payment_gateway_factory = new PaymentGatewayFactory();
$gateway = $payment_gateway_factory->create($ticket_order['payment_gateway']->name, $payment_gateway_config);
//certain payment gateways require an extra parameter here and there so this method takes care of that
//and sets certain options for the gateway that can be used when the transaction is started
$gateway->extractRequestParameters($request);
//generic data that is needed for most orders
$order_total = $order_service->getGrandTotal();
$order_email = $ticket_order['request_data'][0]['order_email'];
$response = $gateway->startTransaction($order_total, $order_email, $event);
if ($response->isSuccessful()) {
session()->push('ticket_order_' . $event_id . '.transaction_id',
$response->getTransactionReference());
$additionalData = ($gateway->storeAdditionalData()) ? $gateway->getAdditionalData($response) : array();
session()->push('ticket_order_' . $event_id . '.transaction_data',
$gateway->getTransactionData() + $additionalData);
$gateway->completeTransaction($additionalData);
return $this->completeOrder($event_id);
} elseif ($response->isRedirect()) {
$additionalData = ($gateway->storeAdditionalData()) ? $gateway->getAdditionalData($response) : array();
session()->push('ticket_order_' . $event_id . '.transaction_data',
$gateway->getTransactionData() + $additionalData);
Log::info("Redirect url: " . $response->getRedirectUrl());
$return = [
'status' => 'success',
'redirectUrl' => $response->getRedirectUrl(),
'message' => 'Redirecting to ' . $ticket_order['payment_gateway']->provider_name
];
// GET method requests should not have redirectData on the JSON return string
if($response->getRedirectMethod() == 'POST') {
$return['redirectData'] = $response->getRedirectData();
}
return response()->json($return);
} else {
// display error to customer
return response()->json([
'status' => 'error',
'message' => $response->getMessage(),
]);
}
} catch (\Exeption $e) {
Log::error($e);
$error = 'Sorry, there was an error processing your payment. Please try again.';
}
if ($error) {
return response()->json([
'status' => 'error',
'message' => $error,
]);
}
}
/**
* Handles the return when a payment is off site
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
* @throws \Exception
*/
public function showEventCheckoutPaymentReturn(Request $request, $event_id)
{
$ticket_order = session()->get('ticket_order_' . $event_id);
$payment_gateway_config = $ticket_order['account_payment_gateway']->config + [
'testMode' => config('attendize.enable_test_payments')];
$payment_gateway_factory = new PaymentGatewayFactory();
$gateway = $payment_gateway_factory->create($ticket_order['payment_gateway']->name, $payment_gateway_config);
$gateway->extractRequestParameters($request);
$response = $gateway->completeTransaction($ticket_order['transaction_data'][0]);
if ($response->isSuccessful()) {
session()->push('ticket_order_' . $event_id . '.transaction_id', $response->getTransactionReference());
return $this->completeOrder($event_id, false);
} else {
session()->flash('message', $response->getMessage());
return response()->redirectToRoute('showEventPayment', [
'event_id' => $event_id,
'is_payment_failed' => 1,
]);
}
}
/**
* Complete an order
*
* @param $event_id
* @param bool|true $return_json
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
public function completeOrder($event_id, $return_json = true)
{
DB::beginTransaction();
try {
$order = new Order();
$ticket_order = session()->get('ticket_order_' . $event_id);
$request_data = $ticket_order['request_data'][0];
$event = Event::findOrFail($ticket_order['event_id']);
$attendee_increment = 1;
$ticket_questions = isset($request_data['ticket_holder_questions']) ? $request_data['ticket_holder_questions'] : [];
/*
* Create the order
*/
if (isset($ticket_order['transaction_id'])) {
$order->transaction_id = $ticket_order['transaction_id'][0];
}
if (isset($ticket_order['transaction_data'][0]['payment_intent'])) {
$order->payment_intent = $ticket_order['transaction_data'][0]['payment_intent'];
}
if ($ticket_order['order_requires_payment'] && !isset($request_data['pay_offline'])) {
$order->payment_gateway_id = $ticket_order['payment_gateway']->id;
}
$order->first_name = sanitise($request_data['order_first_name']);
$order->last_name = sanitise($request_data['order_last_name']);
$order->email = sanitise($request_data['order_email']);
$order->order_status_id = isset($request_data['pay_offline']) ? config('attendize.order.awaiting_payment') : config('attendize.order.complete');
$order->amount = $ticket_order['order_total'];
$order->booking_fee = $ticket_order['booking_fee'];
$order->organiser_booking_fee = $ticket_order['organiser_booking_fee'];
$order->discount = 0.00;
$order->account_id = $event->account->id;
$order->event_id = $ticket_order['event_id'];
$order->is_payment_received = isset($request_data['pay_offline']) ? 0 : 1;
// Business details is selected, we need to save the business details
if (isset($request_data['is_business']) && (bool)$request_data['is_business']) {
$order->is_business = $request_data['is_business'];
$order->business_name = sanitise($request_data['business_name']);
$order->business_tax_number = sanitise($request_data['business_tax_number']);
$order->business_address_line_one = sanitise($request_data['business_address_line1']);
$order->business_address_line_two = sanitise($request_data['business_address_line2']);
$order->business_address_state_province = sanitise($request_data['business_address_state']);
$order->business_address_city = sanitise($request_data['business_address_city']);
$order->business_address_code = sanitise($request_data['business_address_code']);
}
// Calculating grand total including tax
$orderService = new OrderService($ticket_order['order_total'], $ticket_order['total_booking_fee'], $event);
$orderService->calculateFinalCosts();
$order->taxamt = $orderService->getTaxAmount();
$order->save();
/**
* We need to attach the ticket ID to an order. There is a case where multiple tickets
* can be bought in the same order.
*/
collect($ticket_order['tickets'])->map(function($ticketDetail) use ($order) {
$order->tickets()->attach($ticketDetail['ticket']['id']);
});
/*
* Update affiliates stats stats
*/
if ($ticket_order['affiliate_referral']) {
$affiliate = Affiliate::where('name', '=', $ticket_order['affiliate_referral'])
->where('event_id', '=', $event_id)->first();
$affiliate->increment('sales_volume', $order->amount + $order->organiser_booking_fee);
$affiliate->increment('tickets_sold', $ticket_order['total_ticket_quantity']);
}
/*
* Update the event stats
*/
$event_stats = EventStats::updateOrCreate([
'event_id' => $event_id,
'date' => DB::raw('CURRENT_DATE'),
]);
$event_stats->increment('tickets_sold', $ticket_order['total_ticket_quantity']);
if ($ticket_order['order_requires_payment']) {
$event_stats->increment('sales_volume', $order->amount);
$event_stats->increment('organiser_fees_volume', $order->organiser_booking_fee);
}
/*
* Add the attendees
*/
foreach ($ticket_order['tickets'] as $attendee_details) {
/*
* Update ticket's quantity sold
*/
$ticket = Ticket::findOrFail($attendee_details['ticket']['id']);
/*
* Update some ticket info
*/
$ticket->increment('quantity_sold', $attendee_details['qty']);
$ticket->increment('sales_volume', ($attendee_details['ticket']['price'] * $attendee_details['qty']));
$ticket->increment('organiser_fees_volume',
($attendee_details['ticket']['organiser_booking_fee'] * $attendee_details['qty']));
/*
* Insert order items (for use in generating invoices)
*/
$orderItem = new OrderItem();
$orderItem->title = $attendee_details['ticket']['title'];
$orderItem->quantity = $attendee_details['qty'];
$orderItem->order_id = $order->id;
$orderItem->unit_price = $attendee_details['ticket']['price'];
$orderItem->unit_booking_fee = $attendee_details['ticket']['booking_fee'] + $attendee_details['ticket']['organiser_booking_fee'];
$orderItem->save();
/*
* Create the attendees
*/
for ($i = 0; $i < $attendee_details['qty']; $i++) {
$attendee = new Attendee();
$attendee->first_name = sanitise($request_data["ticket_holder_first_name"][$i][$attendee_details['ticket']['id']]);
$attendee->last_name = sanitise($request_data["ticket_holder_last_name"][$i][$attendee_details['ticket']['id']]);
$attendee->email = sanitise($request_data["ticket_holder_email"][$i][$attendee_details['ticket']['id']]);
$attendee->event_id = $event_id;
$attendee->order_id = $order->id;
$attendee->ticket_id = $attendee_details['ticket']['id'];
$attendee->account_id = $event->account->id;
$attendee->reference_index = $attendee_increment;
$attendee->save();
/*
* Save the attendee's questions
*/
foreach ($attendee_details['ticket']->questions as $question) {
$ticket_answer = isset($ticket_questions[$attendee_details['ticket']->id][$i][$question->id])
? $ticket_questions[$attendee_details['ticket']->id][$i][$question->id]
: null;
if (is_null($ticket_answer)) {
continue;
}
/*
* If there are multiple answers to a question then join them with a comma
* and treat them as a single answer.
*/
$ticket_answer = is_array($ticket_answer) ? implode(', ', $ticket_answer) : $ticket_answer;
if (!empty($ticket_answer)) {
QuestionAnswer::create([
'answer_text' => $ticket_answer,
'attendee_id' => $attendee->id,
'event_id' => $event->id,
'account_id' => $event->account->id,
'question_id' => $question->id
]);
}
}
/* Keep track of total number of attendees */
$attendee_increment++;
}
}
} catch (Exception $e) {
Log::error($e);
DB::rollBack();
return response()->json([
'status' => 'error',
'message' => 'Whoops! There was a problem processing your order. Please try again.'
]);
}
//save the order to the database
DB::commit();
//forget the order in the session
session()->forget('ticket_order_' . $event->id);
/*
* Remove any tickets the user has reserved after they have been ordered for the user
*/
ReservedTickets::where('session_id', '=', session()->getId())->delete();
// Queue up some tasks - Emails to be sent, PDFs etc.
// Send order notification to organizer
Log::debug('Queueing Order Notification Job');
SendOrderNotificationJob::dispatch($order, $orderService);
// Send order confirmation to ticket buyer
Log::debug('Queueing Order Tickets Job');
SendOrderConfirmationJob::dispatch($order, $orderService);
// Send tickets to attendees
Log::debug('Queueing Attendee Ticket Jobs');
foreach ($order->attendees as $attendee) {
SendOrderAttendeeTicketJob::dispatch($attendee);
Log::debug('Queueing Attendee Ticket Job Done');
}
if ($return_json) {
return response()->json([
'status' => 'success',
'redirectUrl' => route('showOrderDetails', [
'is_embedded' => $this->is_embedded,
'order_reference' => $order->order_reference,
]),
]);
}
return response()->redirectToRoute('showOrderDetails', [
'is_embedded' => $this->is_embedded,
'order_reference' => $order->order_reference,
]);
}
/**
* Show the order details page
*
* @param Request $request
* @param $order_reference
* @return \Illuminate\View\View
*/
public function showOrderDetails(Request $request, $order_reference)
{
$order = Order::where('order_reference', '=', $order_reference)->first();
if (!$order) {
abort(404);
}
$orderService = new OrderService($order->amount, $order->organiser_booking_fee, $order->event);
$orderService->calculateFinalCosts();
$data = [
'order' => $order,
'orderService' => $orderService,
'event' => $order->event,
'tickets' => $order->event->tickets,
'is_embedded' => $this->is_embedded,
];
if ($this->is_embedded) {
return view('Public.ViewEvent.Embedded.EventPageViewOrder', $data);
}
return view('Public.ViewEvent.EventPageViewOrder', $data);
}
/**
* Shows the tickets for an order - either HTML or PDF
*
* @param Request $request
* @param $order_reference
* @return \Illuminate\View\View
*/
public function showOrderTickets(Request $request, $order_reference)
{
$order = Order::where('order_reference', '=', $order_reference)->first();
if (!$order) {
abort(404);
}
$images = [];
$imgs = $order->event->images;
foreach ($imgs as $img) {
$images[] = base64_encode(file_get_contents(public_path($img->image_path)));
}
$data = [
'order' => $order,
'event' => $order->event,
'tickets' => $order->event->tickets,
'attendees' => $order->attendees,
'css' => file_get_contents(public_path('assets/stylesheet/ticket.css')),
'image' => base64_encode(file_get_contents(public_path($order->event->organiser->full_logo_path))),
'images' => $images,
];
if ($request->get('download') == '1') {
return PDF::html('Public.ViewEvent.Partials.PDFTicket', $data, 'Tickets');
}
return view('Public.ViewEvent.Partials.PDFTicket', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventCheckoutController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 7,090 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Ticket;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Log;
/*
Attendize.com - Event Management & Ticketing
*/
class EventTicketsController extends MyBaseController
{
/**
* @param Request $request
* @param $event_id
* @return mixed
*/
public function showTickets(Request $request, $event_id)
{
$allowed_sorts = [
'created_at' => trans("Controllers.sort.created_at"),
'title' => trans("Controllers.sort.title"),
'quantity_sold' => trans("Controllers.sort.quantity_sold"),
'sales_volume' => trans("Controllers.sort.sales_volume"),
'sort_order' => trans("Controllers.sort.sort_order"),
];
// Getting get parameters.
$q = $request->get('q', '');
$sort_by = $request->get('sort_by');
if (isset($allowed_sorts[$sort_by]) === false) {
$sort_by = 'sort_order';
}
// Find event or return 404 error.
$event = Event::scope()->find($event_id);
if ($event === null) {
abort(404);
}
// Get tickets for event.
$tickets = empty($q) === false
? $event->tickets()->where('title', 'like', '%' . $q . '%')->orderBy($sort_by, 'asc')->paginate()
: $event->tickets()->orderBy($sort_by, 'asc')->paginate();
// Return view.
return view('ManageEvent.Tickets', compact('event', 'tickets', 'sort_by', 'q', 'allowed_sorts'));
}
/**
* Show the edit ticket modal
*
* @param $event_id
* @param $ticket_id
* @return mixed
*/
public function showEditTicket($event_id, $ticket_id)
{
$data = [
'event' => Event::scope()->find($event_id),
'ticket' => Ticket::scope()->find($ticket_id),
];
return view('ManageEvent.Modals.EditTicket', $data);
}
/**
* Show the create ticket modal
*
* @param $event_id
* @return \Illuminate\Contracts\View\View
*/
public function showCreateTicket($event_id)
{
return view('ManageEvent.Modals.CreateTicket', [
'event' => Event::scope()->find($event_id),
]);
}
/**
* Creates a ticket
*
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postCreateTicket(Request $request, $event_id)
{
$ticket = Ticket::createNew();
if (!$ticket->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $ticket->errors(),
]);
}
$ticket->event_id = $event_id;
$ticket->title = $request->get('title');
$ticket->quantity_available = !$request->get('quantity_available') ? null : $request->get('quantity_available');
$ticket->start_sale_date = $request->get('start_sale_date');
$ticket->end_sale_date = $request->get('end_sale_date');
$ticket->price = $request->get('price');
$ticket->min_per_person = $request->get('min_per_person');
$ticket->max_per_person = $request->get('max_per_person');
$ticket->description = prepare_markdown($request->get('description'));
$ticket->is_hidden = $request->get('is_hidden') ? 1 : 0;
$ticket->save();
// Attach the access codes to the ticket if it's hidden and the code ids have come from the front
if ($ticket->is_hidden) {
$ticketAccessCodes = $request->get('ticket_access_codes', []);
if (empty($ticketAccessCodes) === false) {
// Sync the access codes on the ticket
$ticket->event_access_codes()->attach($ticketAccessCodes);
}
}
session()->flash('message', 'Successfully Created Ticket');
return response()->json([
'status' => 'success',
'id' => $ticket->id,
'message' => trans("Controllers.refreshing"),
'redirectUrl' => route('showEventTickets', [
'event_id' => $event_id,
]),
]);
}
/**
* Pause ticket / take it off sale
*
* @param Request $request
* @return mixed
*/
public function postPauseTicket(Request $request)
{
$ticket_id = $request->get('ticket_id');
$ticket = Ticket::scope()->find($ticket_id);
$ticket->is_paused = ($ticket->is_paused == 1) ? 0 : 1;
if ($ticket->save()) {
return response()->json([
'status' => 'success',
'message' => trans("Controllers.ticket_successfully_updated"),
'id' => $ticket->id,
]);
}
Log::error('Ticket Failed to pause/resume', [
'ticket' => $ticket,
]);
return response()->json([
'status' => 'error',
'id' => $ticket->id,
'message' => trans("Controllers.whoops"),
]);
}
/**
* Deleted a ticket
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postDeleteTicket(Request $request)
{
$ticket_id = $request->get('ticket_id');
$ticket = Ticket::scope()->find($ticket_id);
/*
* Don't allow deletion of tickets which have been sold already.
*/
if ($ticket->quantity_sold > 0) {
return response()->json([
'status' => 'error',
'message' => trans("Controllers.cant_delete_ticket_when_sold"),
'id' => $ticket->id,
]);
}
if ($ticket->delete()) {
return response()->json([
'status' => 'success',
'message' => trans("Controllers.ticket_successfully_deleted"),
'id' => $ticket->id,
]);
}
Log::error('Ticket Failed to delete', [
'ticket' => $ticket,
]);
return response()->json([
'status' => 'error',
'id' => $ticket->id,
'message' => trans("Controllers.whoops"),
]);
}
/**
* Edit a ticket
*
* @param Request $request
* @param $event_id
* @param $ticket_id
* @return \Illuminate\Http\JsonResponse
*/
public function postEditTicket(Request $request, $event_id, $ticket_id)
{
$ticket = Ticket::scope()->findOrFail($ticket_id);
/*
* Add validation message
*/
$validation_messages['quantity_available.min'] = trans("Controllers.quantity_min_error");
$ticket->messages = $validation_messages + $ticket->messages;
if (!$ticket->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $ticket->errors(),
]);
}
// Check if the ticket visibility changed on update
$ticketPreviouslyHidden = (bool)$ticket->is_hidden;
$ticket->title = $request->get('title');
$ticket->quantity_available = !$request->get('quantity_available') ? null : $request->get('quantity_available');
$ticket->price = $request->get('price');
$ticket->start_sale_date = $request->get('start_sale_date');
$ticket->end_sale_date = $request->get('end_sale_date');
$ticket->description = prepare_markdown($request->get('description'));
$ticket->min_per_person = $request->get('min_per_person');
$ticket->max_per_person = $request->get('max_per_person');
$ticket->is_hidden = $request->get('is_hidden') ? 1 : 0;
$ticket->save();
// Attach the access codes to the ticket if it's hidden and the code ids have come from the front
if ($ticket->is_hidden) {
$ticketAccessCodes = $request->get('ticket_access_codes', []);
if (empty($ticketAccessCodes) === false) {
// Sync the access codes on the ticket
$ticket->event_access_codes()->detach();
$ticket->event_access_codes()->attach($ticketAccessCodes);
}
} else if ($ticketPreviouslyHidden) {
// Delete access codes on ticket if the visibility changed to visible
$ticket->event_access_codes()->detach();
}
return response()->json([
'status' => 'success',
'id' => $ticket->id,
'message' => trans("Controllers.refreshing"),
'redirectUrl' => route('showEventTickets', [
'event_id' => $event_id,
]),
]);
}
/**
* Updates the sort order of tickets
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postUpdateTicketsOrder(Request $request)
{
$ticket_ids = $request->get('ticket_ids');
$sort = 1;
foreach ($ticket_ids as $ticket_id) {
$ticket = Ticket::scope()->find($ticket_id);
$ticket->sort_order = $sort;
$ticket->save();
$sort++;
}
return response()->json([
'status' => 'success',
'message' => trans("Controllers.ticket_order_successfully_updated"),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventTicketsController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 2,149 |
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Session;
class UserLogoutController extends Controller
{
protected $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Log a user out and redirect them
*
* @return mixed
*/
public function doLogout()
{
$this->auth->logout();
Session::flush();
return redirect()->to('/?logged_out=yup');
}
}
``` | /content/code_sandbox/app/Http/Controllers/UserLogoutController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 116 |
```php
<?php
namespace App\Http\Controllers;
use App\Attendize\Utils;
use App\Models\Organiser;
use Auth;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
class OrganiserViewController extends Controller
{
/**
* Show the public organiser page
*
* @param $organiser_id
* @param string $slug
* @param bool $preview
* @return View
*/
public function showOrganiserHome(Request $request, $organiser_id, $slug = '', $preview = false)
{
/** @var Organiser $organiser */
$organiser = Organiser::findOrFail($organiser_id);
if (!$organiser->enable_organiser_page && !Utils::userOwns($organiser)) {
abort(404);
}
/*
* If we are previewing styles from the backend we set them here.
*/
if ($request->get('preview_styles') && Auth::check()) {
$query_string = rawurldecode($request->get('preview_styles'));
parse_str($query_string, $preview_styles);
$organiser->page_bg_color = $preview_styles['page_bg_color'];
$organiser->page_header_bg_color = $preview_styles['page_header_bg_color'];
$organiser->page_text_color = $preview_styles['page_text_color'];
}
$upcoming_events = $organiser->events()->where([
['end_date', '>=', now()],
['is_live', 1]
])->get();
$past_events = $organiser->events()->where([
['end_date', '<', now()],
['is_live', 1]
])->limit(10)->get();
$data = [
'organiser' => $organiser,
'tickets' => $organiser->events()->orderBy('created_at', 'desc')->get(),
'is_embedded' => 0,
'upcoming_events' => $upcoming_events,
'past_events' => $past_events,
];
return view('Public.ViewOrganiser.OrganiserPage', $data);
}
/**
* Show the backend preview of the organiser page
*
* @param $event_id
* @return mixed
*/
public function showEventHomePreview($event_id)
{
return (new EventViewController)->showEventHome($event_id, true);
}
}
``` | /content/code_sandbox/app/Http/Controllers/OrganiserViewController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 525 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Attendee;
use App\Models\Event;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use JavaScript;
class EventCheckInController extends MyBaseController
{
/**
* Show the check-in page
*
* @param $event_id
* @return \Illuminate\View\View
*/
public function showCheckIn($event_id)
{
$event = Event::scope()->findOrFail($event_id);
$data = [
'event' => $event,
'attendees' => $event->attendees
];
JavaScript::put([
'qrcodeCheckInRoute' => route('postQRCodeCheckInAttendee', ['event_id' => $event->id]),
'checkInRoute' => route('postCheckInAttendee', ['event_id' => $event->id]),
'checkInSearchRoute' => route('postCheckInSearch', ['event_id' => $event->id]),
]);
return view('ManageEvent.CheckIn', $data);
}
public function showQRCodeModal(Request $request, $event_id)
{
return view('ManageEvent.Modals.QrcodeCheckIn');
}
/**
* Search attendees
*
* @param Request $request
* @param $event_id
* @return \Illuminate\Http\JsonResponse
*/
public function postCheckInSearch(Request $request, $event_id)
{
$searchQuery = $request->get('q');
$attendees = Attendee::scope()->withoutCancelled()
->join('tickets', 'tickets.id', '=', 'attendees.ticket_id')
->join('orders', 'orders.id', '=', 'attendees.order_id')
->where(function ($query) use ($event_id) {
$query->where('attendees.event_id', '=', $event_id);
})->where(function ($query) use ($searchQuery) {
$query->orWhere('attendees.first_name', 'like', $searchQuery . '%')
->orWhere(
DB::raw("CONCAT_WS(' ', attendees.first_name, attendees.last_name)"),
'like',
$searchQuery . '%'
)
//->orWhere('attendees.email', 'like', $searchQuery . '%')
->orWhere('orders.order_reference', 'like', $searchQuery . '%')
->orWhere('attendees.private_reference_number', 'like', $searchQuery . '%')
->orWhere('attendees.last_name', 'like', $searchQuery . '%');
})
->select([
'attendees.id',
'attendees.first_name',
'attendees.last_name',
'attendees.email',
'attendees.arrival_time',
'attendees.reference_index',
'attendees.has_arrived',
'tickets.title as ticket',
'orders.order_reference',
'orders.is_payment_received'
])
->orderBy('attendees.first_name', 'ASC')
->get();
return response()->json($attendees);
}
/**
* Check in/out an attendee
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postCheckInAttendee(Request $request)
{
$attendee_id = $request->get('attendee_id');
$checking = $request->get('checking');
$attendee = Attendee::scope()->find($attendee_id);
/*
* Ugh
*/
if ((($checking == 'in') && ($attendee->has_arrived == 1)) || (($checking == 'out') && ($attendee->has_arrived == 0))) {
return response()->json([
'status' => 'error',
'message' => 'Attendee Already Checked ' . (($checking == 'in') ? 'In (at ' . $attendee->arrival_time->format('H:i A, F j') . ')' : 'Out') . '!',
'checked' => $checking,
'id' => $attendee->id,
]);
}
$attendee->has_arrived = ($checking == 'in') ? 1 : 0;
$attendee->arrival_time = Carbon::now();
$attendee->save();
return response()->json([
'status' => 'success',
'checked' => $checking,
'message' => (($checking == 'in') ? trans("Controllers.attendee_successfully_checked_in") : trans("Controllers.attendee_successfully_checked_out")),
'id' => $attendee->id,
]);
}
/**
* Check in an attendee
*
* @param $event_id
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function postCheckInAttendeeQr($event_id, Request $request)
{
$event = Event::scope()->findOrFail($event_id);
$qrcodeToken = $request->get('attendee_reference');
$attendee = Attendee::scope()->withoutCancelled()
->join('tickets', 'tickets.id', '=', 'attendees.ticket_id')
->where(function ($query) use ($event, $qrcodeToken) {
$query->where('attendees.event_id', $event->id)
->where('attendees.private_reference_number', $qrcodeToken);
})->select([
'attendees.id',
'attendees.order_id',
'attendees.first_name',
'attendees.last_name',
'attendees.email',
'attendees.reference_index',
'attendees.arrival_time',
'attendees.has_arrived',
'tickets.title as ticket',
])->first();
if (is_null($attendee)) {
return response()->json([
'status' => 'error',
'message' => trans("Controllers.invalid_ticket_error")
]);
}
$relatedAttendesCount = Attendee::where('id', '!=', $attendee->id)
->where([
'order_id' => $attendee->order_id,
'has_arrived' => false
])->count();
if ($attendee->has_arrived) {
return response()->json([
'status' => 'error',
'message' => trans("Controllers.attendee_already_checked_in", ["time"=> $attendee->arrival_time->format(config("attendize.default_datetime_format"))])
]);
}
Attendee::find($attendee->id)->update(['has_arrived' => true, 'arrival_time' => Carbon::now()]);
return response()->json([
'status' => 'success',
'name' => $attendee->first_name." ".$attendee->last_name,
'reference' => $attendee->reference,
'ticket' => $attendee->ticket
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventCheckInController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,485 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Account;
use App\Models\AccountPaymentGateway;
use App\Models\Currency;
use App\Models\PaymentGateway;
use App\Models\Timezone;
use App\Models\User;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Mail\Message;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Services\PaymentGateway\Dummy;
use Services\PaymentGateway\Stripe;
use Services\PaymentGateway\StripeSCA;
use Utils;
use Illuminate\Support\Facades\Lang;
class ManageAccountController extends MyBaseController
{
/**
* Show the account modal
*
* @param Request $request
* @return mixed
*/
public function showEditAccount(Request $request)
{
$data = [
'account' => Account::find(Auth::user()->account_id),
'timezones' => Timezone::pluck('location', 'id'),
'currencies' => Currency::pluck('title', 'id'),
'payment_gateways' => PaymentGateway::getAllWithDefaultSet(),
'default_payment_gateway_id' => PaymentGateway::getDefaultPaymentGatewayId(),
'account_payment_gateways' => AccountPaymentGateway::scope()->get(),
'version_info' => $this->getVersionInfo(),
];
return view('ManageAccount.Modals.EditAccount', $data);
}
public function getVersionInfo()
{
$installedVersion = null;
$latestVersion = null;
try {
$http_client = new Client();
$response = $http_client->get('path_to_url
$latestVersion = Utils::parse_version((string)$response->getBody());
$installedVersion = trim(file_get_contents(base_path('VERSION')));
} catch (\Exception $exception) {
\Log::warn("Error retrieving the latest Attendize version. ManageAccountController.getVersionInf() try/catch");
\Log::warn($exception);
return false;
}
if ($installedVersion && $latestVersion) {
return [
'latest' => $latestVersion,
'installed' => $installedVersion,
'is_outdated' => (version_compare($installedVersion, $latestVersion) === -1) ? true : false,
];
}
return false;
}
/**
* Edit an account
*
* @param Request $request
* @return JsonResponse
*/
public function postEditAccount(Request $request)
{
$account = Account::find(Auth::user()->account_id);
if (!$account->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $account->errors(),
]);
}
$account->first_name = $request->input('first_name');
$account->last_name = $request->input('last_name');
$account->email = $request->input('email');
$account->timezone_id = $request->input('timezone_id');
$account->currency_id = $request->input('currency_id');
$account->save();
return response()->json([
'status' => 'success',
'id' => $account->id,
'message' => trans('Controllers.account_successfully_updated'),
]);
}
/**
* Save account payment information
*
* @param Request $request
* @return mixed
*/
public function postEditAccountPayment(Request $request)
{
$account = Account::find(Auth::user()->account_id);
$gateway_id = $request->get('payment_gateway');
$payment_gateway = PaymentGateway::where('id', '=', $gateway_id)->first();
$config = [];
switch ($payment_gateway->name) {
case Stripe::GATEWAY_NAME :
$config = $request->get('stripe');
break;
case StripeSCA::GATEWAY_NAME :
$config = $request->get('stripe_sca');
break;
case Dummy::GATEWAY_NAME :
break;
}
PaymentGateway::query()->update(['default' => 0]);
$payment_gateway->default = 1;
$payment_gateway->save();
$account_payment_gateway = AccountPaymentGateway::firstOrNew(
[
'payment_gateway_id' => $gateway_id,
'account_id' => $account->id,
]);
$account_payment_gateway->config = $config;
$account_payment_gateway->account_id = $account->id;
$account_payment_gateway->payment_gateway_id = $gateway_id;
$account_payment_gateway->save();
$account->payment_gateway_id = $gateway_id;
$account->save();
return response()->json([
'status' => 'success',
'id' => $account_payment_gateway->id,
'message' => trans('Controllers.payment_information_successfully_updated'),
]);
}
/**
* Invite a user to the application
*
* @return JsonResponse
*/
public function postInviteUser(Request $request)
{
$rules = [
'email' => ['required', 'email', 'unique:users,email,NULL,id,account_id,' . Auth::user()->account_id],
];
$messages = [
'email.email' => trans('Controllers.error.email.email'),
'email.required' => trans('Controllers.error.email.required'),
'email.unique' => trans('Controllers.error.email.unique'),
];
$validation = Validator::make($request->all(), $rules, $messages);
if ($validation->fails()) {
return response()->json([
'status' => 'error',
'messages' => $validation->messages()->toArray(),
]);
}
$temp_password = Str::random(8);
$user = new User();
$user->email = $request->input('email');
$user->password = Hash::make($temp_password);
$user->account_id = Auth::user()->account_id;
$user->save();
$data = [
'user' => $user,
'temp_password' => $temp_password,
'inviter' => Auth::user(),
];
Mail::send(Lang::locale().'.Emails.inviteUser', $data, static function (Message $message) use ($data) {
$message->to($data['user']->email)
->subject(trans('Email.invite_user', [
'name' => $data['inviter']->first_name . ' ' . $data['inviter']->last_name,
'app' => config('attendize.app_name')
]));
});
return response()->json([
'status' => 'success',
'message' => trans('Controllers.success_name_has_received_instruction', ['name' => $user->email]),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/ManageAccountController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,502 |
```php
<?php
namespace App\Http\Controllers;
/* Depreciated */
class EventQuestionsController extends MyBaseController
{
}
``` | /content/code_sandbox/app/Http/Controllers/EventQuestionsController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 24 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Event;
class EventViewEmbeddedController extends Controller
{
/**
* Show an embedded version of the event page
*
* @param $event_id
* @return mixed
*/
public function showEmbeddedEvent($event_id)
{
$event = Event::findOrFail($event_id);
$data = [
'event' => $event,
'tickets' => $event->tickets()->where('is_hidden', 0)->orderBy('sort_order', 'asc')->get(),
'is_embedded' => '1',
];
return view('Public.ViewEvent.Embedded.EventPage', $data);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventViewEmbeddedController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 150 |
```php
<?php
namespace App\Http\Controllers;
class ImageController extends Controller
{
/**
* Generate a thumbnail for a given image
*
* @param $image_src
* @param bool $width
* @param bool $height
* @param int $quality
*/
public function generateThumbnail($image_src, $width = false, $height = false, $quality = 90)
{
$img = Image::make('public/foo.jpg');
$img->resize(320, 240);
$img->insert('public/watermark.png');
$img->save('public/bar.jpg');
}
}
``` | /content/code_sandbox/app/Http/Controllers/ImageController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 139 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\EventAccessCodes;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
/*
Attendize.com - Event Management & Ticketing
*/
class EventAccessCodesController extends MyBaseController
{
/**
* @param $event_id
* @return mixed
*/
public function show($event_id)
{
$event = Event::scope()->findOrFail($event_id);
return view('ManageEvent.AccessCodes', [
'event' => $event,
]);
}
/**
* @param $event_id
* @return Factory|View
*/
public function showCreate($event_id)
{
return view('ManageEvent.Modals.CreateAccessCode', [
'event' => Event::scope()->find($event_id),
]);
}
/**
* Creates a ticket
*
* @param Request $request
* @param $event_id
* @return JsonResponse
*/
public function postCreate(Request $request, $event_id)
{
$eventAccessCode = new EventAccessCodes();
if (!$eventAccessCode->validate($request->all())) {
return response()->json([
'status' => 'error',
'messages' => $eventAccessCode->errors(),
]);
}
// Checks for no duplicates
$newAccessCode = strtoupper($request->get('code'));
if (EventAccessCodes::findFromCode($newAccessCode, $event_id)->count() > 0) {
return response()->json([
'status' => 'error',
'messages' => [
'code' => [ trans('AccessCodes.unique_error') ],
],
]);
}
// Saves the new access code if validation and dupe check passed
$eventAccessCode->event_id = $event_id;
$eventAccessCode->code = $newAccessCode;
$eventAccessCode->save();
session()->flash('message', trans('AccessCodes.success_message'));
return response()->json([
'status' => 'success',
'id' => $eventAccessCode->id,
'message' => trans("Controllers.refreshing"),
'redirectUrl' => route('showEventAccessCodes', [ 'event_id' => $event_id ]),
]);
}
/**
* @param integer $event_id
* @param integer $access_code_id
* @return JsonResponse
* @throws \Exception
*/
public function postDelete($event_id, $access_code_id)
{
/** @var Event $event */
$event = Event::scope()->findOrFail($event_id);
if ($event->hasAccessCode($access_code_id)) {
/** @var EventAccessCodes $accessCode */
$accessCode = EventAccessCodes::find($access_code_id);
if ($accessCode->usage_count > 0) {
return response()->json([
'status' => 'error',
'message' => trans('AccessCodes.cannot_delete_used_code'),
]);
}
$accessCode->delete();
}
session()->flash('message', trans('AccessCodes.delete_message'));
return response()->json([
'status' => 'success',
'message' => trans("Controllers.refreshing"),
'redirectUrl' => route('showEventAccessCodes', [ 'event_id' => $event_id ]),
]);
}
}
``` | /content/code_sandbox/app/Http/Controllers/EventAccessCodesController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 745 |
```php
<?php
namespace App\Http\Controllers;
use App\Models\Timezone;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;
use Utils;
class InstallerController extends Controller
{
/**
* @var array Stores the installation data
*/
protected $installation_data = [];
/**
* @var array Stores the installer data
*/
private $data;
protected function constructInstallerData(): void
{
$this->addDefaultConfig();
$this->addWritablePaths();
$this->addPHPExtensions();
$this->addPHPOptionalExtensions();
}
/**
* Show the application installer
*
* @return mixed
*/
public function showInstaller()
{
/**
* If we're already installed display user friendly message and direct them to the appropriate next steps.
*
* @todo Check if DB is installed etc.
* @todo Add some automated checks to see exactly what the state of the install is. Potentially would be nice to
* allow the user to restart the install process
*/
$this->constructInstallerData();
if (self::isInstalled()) {
return view('Installer.AlreadyInstalled', $this->data);
}
return view('Installer.Installer', $this->data);
}
/**
* Attempts to install the system
*
* @param Request $request
* @return JsonResponse|RedirectResponse
*/
public function postInstaller(Request $request)
{
// Do not run the installation if it is already installed
if (self::isInstalled()) {
// Return 409 Conflict HTTP Code and a friendly message
abort(409, trans('Installer.setup_completed_already_message'));
}
// Increase PHP time limit
set_time_limit(300);
// Check if we just have to test the database for JSON before doing anything else
if ($request->get('test') === 'db') {
return $this->checkDatabaseJSON($request);
}
// Construct the data for installer
$this->constructInstallerData();
// If the database settings are invalid, return to the installer page.
if (!$this->validateConnectionDetails($request)) {
return view('Installer.Installer', $this->data);
}
// Get and store data for installation
$this->getInstallationData($request);
// If a user doesn't use the default database details, enters incorrect values in the form, and then proceeds
// the installation fails miserably. Rather check if the database connection details are valid and fail
// gracefully
if (!$this->testDatabase($this->installation_data['database'])) {
return view('Installer.Installer', $this->data)->withErrors(
new MessageBag(['Database connection failed. Please check the details you have entered and try again.']));
}
// Writes the new env file
$this->writeEnvFile();
// Force laravel to regenerate a new key (see key:generate sources)
Config::set('app.key', $this->installation_data['app_key']);
Artisan::call('key:generate', ['--force' => true]);
// Run the migration
Artisan::call('migrate', ['--force' => true]);
if (Timezone::count() === 0) {
Artisan::call('db:seed', ['--force' => true]);
}
// Create the "installed" file
$this->createInstalledFile();
// Reload the configuration file (very useful if you use php artisan serve)
Artisan::call('config:clear');
return redirect()->route('showSignup', ['first_run' => 'yup']);
}
/**
* Get data needed before upgrading the system
*
* @return array
*/
protected function constructUpgraderData()
{
$data = [
'remote_version' => null,
'local_version' => null,
'installed_version' => null,
'upgrade_done' => false
];
try {
$http_client = new Client();
$response = $http_client->get('path_to_url
$data["remote_version"] = Utils::parse_version((string)$response->getBody());
} catch (\Exception $exception) {
\Log::warn("Error retrieving the latest Attendize version. InstallerController.getVersionInfo()");
\Log::warn($exception);
}
$data["local_version"] = trim(file_get_contents(base_path('VERSION')));
$data["installed_version"] = trim(file_get_contents(base_path('installed')));
return $data;
}
/**
* Show the application upgrader
*
* @return mixed
*/
public function showUpgrader()
{
/**
* If we haven't yet installed, redirect to installer page.
*/
if (!self::isInstalled()) {
$this->constructInstallerData();
return view('Installer.Installer', $this->data);
}
$data = $this->constructUpgraderData();
return view('Installer.Upgrader', $data);
}
/**
* Attempts to upgrade the system
*
* @param Request $request
* @return JsonResponse|RedirectResponse
*/
public function postUpgrader(Request $request)
{
// Do not run the installation if it is already installed
if (!$this->canUpgrade()) {
// Return 409 Conflict HTTP Code and a friendly message
abort(409, trans('Installer.no_updgrade'));
}
// Increase PHP time limit
set_time_limit(300);
// Run any migrations
Artisan::call('migrate', ['--force' => true]);
// Update the "installed" file with latest version
$this->createInstalledFile();
// Reload the configuration file (very useful if you use php artisan serve)
Artisan::call('config:clear');
$data = $this->constructUpgraderData();
$data["upgrade_done"] = true;
return view('Installer.Upgrader', $data);
}
/**
* Adds default config values for the view blade to use
*/
protected function addDefaultConfig(): void
{
$database_default = Config::get('database.default');
$this->data['default_config'] = [
'application_url' => Config::get('app.url'),
'database_type' => $database_default,
'database_host' => Config::get('database.connections.' . $database_default . '.host'),
'database_name' => Config::get('database.connections.' . $database_default . '.database'),
'database_username' => Config::get('database.connections.' . $database_default . '.username'),
'database_password' => Config::get('database.connections.' . $database_default . '.password'),
'mail_from_address' => Config::get('mail.from.address'),
'mail_from_name' => Config::get('mail.from.name'),
'mail_driver' => Config::get('mail.driver'),
'mail_port' => Config::get('mail.port'),
'mail_encryption' => Config::get('mail.encryption'),
'mail_host' => Config::get('mail.host'),
'mail_username' => Config::get('mail.username'),
'mail_password' => Config::get('mail.password')
];
}
/**
* Adds to the checks the paths that should be writable
*/
protected function addWritablePaths(): void
{
$this->data['paths'] = [
storage_path('app'),
storage_path('framework'),
storage_path('logs'),
public_path(config('attendize.event_images_path')),
public_path(config('attendize.organiser_images_path')),
public_path(config('attendize.event_pdf_tickets_path')),
base_path('bootstrap/cache'),
base_path('.env'),
base_path(),
];
}
/**
* Adds to the checks the required PHP extensions
*/
protected function addPHPExtensions(): void
{
$this->data['requirements'] = [
'openssl',
'pdo',
'mbstring',
'fileinfo',
'tokenizer',
'gd',
'zip',
];
}
/**
* Adds to the checks the optional PHP extensions
*/
protected function addPHPOptionalExtensions(): void
{
$this->data['optional_requirements'] = [
'pdo_mysql',
'pdo_pgsql',
];
$database_default = Config::get('database.default');
$this->data['default_config'] = [
'application_url' => Config::get('app.url'),
'database_type' => $database_default,
'database_host' => Config::get('database.connections.' . $database_default . '.host'),
'database_name' => Config::get('database.connections.' . $database_default . '.database'),
'database_username' => Config::get('database.connections.' . $database_default . '.username'),
'database_password' => Config::get('database.connections.' . $database_default . '.password'),
'mail_from_address' => Config::get('mail.from.address'),
'mail_from_name' => Config::get('mail.from.name'),
'mail_driver' => Config::get('mail.driver'),
'mail_port' => Config::get('mail.port'),
'mail_encryption' => Config::get('mail.encryption'),
'mail_host' => Config::get('mail.host'),
'mail_username' => Config::get('mail.username'),
'mail_password' => Config::get('mail.password')
];
}
/**
* Check if Attendize is already installed
*
* @return bool true if installed false if not
*/
public static function isInstalled(): bool
{
return file_exists(base_path('installed'));
}
/**
* Check if an upgrade is possible
*
* @return bool true if upgrade possible false if not
*/
public function canUpgrade(): bool
{
$data = $this->constructUpgraderData();
if (
(version_compare($data['local_version'], $data['remote_version']) === -1) ||
(
version_compare($data['local_version'], $data['remote_version']) === 0 &&
version_compare($data['installed_version'], $data['local_version']) === -1
)) {
return true;
}
return false;
}
/**
* Checks the database and returns a JSON response with the result
*
* @param Request $request
* @return JsonResponse
*/
protected function checkDatabaseJSON(Request $request): JsonResponse
{
// If we can connect to database, return a success message
if ($this->validateConnectionDetails($request) && $this->testDatabase($this->getDatabaseData($request))) {
return response()->json([
'status' => 'success',
'message' => trans('Installer.connection_success'),
'test' => 1,
]);
}
// If the database configuration is invalid or we cannot connect to the database, return an error message
return response()->json([
'status' => 'error',
'message' => trans('Installer.connection_failure'),
'test' => 1,
]);
}
/**
* Checks whether the database connection data in the request is valid.
*
* @param Request $request
* @return bool
*/
protected function validateConnectionDetails(Request $request): bool
{
try {
$this->validate($request, [
'database_type' => 'required',
'database_host' => 'required',
'database_name' => 'required',
'database_username' => 'required',
'database_password' => 'required'
]);
return true;
} catch (Exception $e) {
Log::error('Please enter all app settings. '.$e->getMessage());
}
return false;
}
/**
* Test the database connection
*
* @param $database
* @return bool
*/
private function testDatabase($database): bool
{
// Replaces database configuration
Config::set('database.default', $database['type']);
Config::set('database.connections.'.$database['type'].'.host', $database['host']);
Config::set('database.connections.'.$database['type'].'.database', $database['name']);
Config::set('database.connections.'.$database['type'].'.username', $database['username']);
Config::set('database.connections.'.$database['type'].'.password', $database['password']);
// Try to connect
try {
DB::reconnect();
$pdo = DB::connection()->getPdo();
if (!empty($pdo)) {
return true;
}
} catch (Exception $e) {
Log::error('Database connection details invalid'.$e->getMessage());
}
return false;
}
/**
* Get the database data from request
*
* @param Request $request
* @return array
*/
protected function getDatabaseData(Request $request): array
{
return [
'type' => $request->get('database_type'),
'host' => $request->get('database_host'),
'name' => $request->get('database_name'),
'username' => $request->get('database_username'),
'password' => $request->get('database_password')
];
}
/**
* @param Request $request
*/
protected function getInstallationData(Request $request): void
{
// Create the database data array
$this->installation_data['database'] = $this->getDatabaseData($request);
// Create the mail data array
$this->installation_data['mail'] = $this->getMailData($request);
$this->installation_data['app_url'] = $request->get('app_url');
$this->installation_data['app_key'] = Str::random(32);
}
/**
* @param Request $request
* @return array
*/
protected function getMailData(Request $request): array
{
return [
'driver' => $request->get('mail_driver'),
'port' => $request->get('mail_port'),
'username' => $request->get('mail_username'),
'password' => $request->get('mail_password'),
'encryption' => $request->get('mail_encryption'),
'from_address' => $request->get('mail_from_address'),
'from_name' => $request->get('mail_from_name'),
'host' => $request->get('mail_host')
];
}
/**
* Write the .env file
*/
protected function writeEnvFile(): void
{
// Get the example env data
$example_env = file_get_contents(base_path().DIRECTORY_SEPARATOR.'.env.example');
$env_lines = explode(PHP_EOL, $example_env);
// Parse each line
foreach ($env_lines as $key => $line) {
$env_lines[$key] = explode('=', $line, 2);
}
// Installer data to be stored in the new env file
$config = [
'APP_ENV' => 'production',
'APP_DEBUG' => 'false',
'APP_URL' => $this->installation_data['app_url'],
'APP_KEY' => $this->installation_data['app_key'],
'DB_TYPE' => $this->installation_data['database']['type'],
'DB_HOST' => $this->installation_data['database']['host'],
'DB_DATABASE' => $this->installation_data['database']['name'],
'DB_USERNAME' => $this->installation_data['database']['username'],
'DB_PASSWORD' => $this->installation_data['database']['password'],
'MAIL_DRIVER' => $this->installation_data['mail']['driver'],
'MAIL_PORT' => $this->installation_data['mail']['port'],
'MAIL_ENCRYPTION' => $this->installation_data['mail']['encryption'],
'MAIL_HOST' => $this->installation_data['mail']['host'],
'MAIL_USERNAME' => $this->installation_data['mail']['username'],
'MAIL_FROM_NAME' => $this->installation_data['mail']['from_name'],
'MAIL_FROM_ADDRESS' => $this->installation_data['mail']['from_address'],
'MAIL_PASSWORD' => $this->installation_data['mail']['password'],
];
// Merge new config data with example env
foreach ($config as $key => $val) {
$replaced_line = false;
// Check if config already exist in example env and replace it
foreach ($env_lines as $line_number => $line) {
if ($line[0] === $key) {
$env_lines[$line_number][1] = $val;
$replaced_line = true;
}
}
// If no replaced is a new config key/value set
if (!$replaced_line) {
$env_lines[] = [$key, $val];
}
}
// Creates the new env file
$new_env = '';
foreach ($env_lines as $line) {
$new_env .= implode(count($line) > 1 ? '=' : '', $line).PHP_EOL;
}
// Store the env file
$fp = fopen(base_path().DIRECTORY_SEPARATOR.'.env', 'wb');
fwrite($fp, $new_env);
fclose($fp);
}
/**
* Creates the installation file
*/
protected function createInstalledFile(): void
{
$version = trim(file_get_contents(base_path('VERSION')));
$fp = fopen(base_path().DIRECTORY_SEPARATOR.'installed', 'wb');
fwrite($fp, $version);
fclose($fp);
}
}
``` | /content/code_sandbox/app/Http/Controllers/InstallerController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 3,946 |
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
``` | /content/code_sandbox/app/Http/Controllers/Controller.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 66 |
```php
<?php
namespace App\Http\Controllers\API;
use App\Models\Event;
use Illuminate\Http\Request;
class EventsApiController extends ApiBaseController
{
/**
* @param Request $request
* @return mixed
*/
public function index(Request $request)
{
return Event::scope($this->account_id)->paginate(20);
}
/**
* @param Request $request
* @param $attendee_id
* @return mixed
*/
public function show(Request $request, $attendee_id)
{
if ($attendee_id) {
return Event::scope($this->account_id)->find($attendee_id);
}
return response('Event Not Found', 404);
}
public function store(Request $request)
{
}
public function update(Request $request)
{
}
public function destroy(Request $request)
{
}
}
``` | /content/code_sandbox/app/Http/Controllers/API/EventsApiController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 193 |
```php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class ApiBaseController extends Controller
{
protected $account_id;
public function __construct()
{
$this->account_id = Auth::guard('api')->check() ? Auth::guard('api')->user()->account_id : null;
}
}
``` | /content/code_sandbox/app/Http/Controllers/API/ApiBaseController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 76 |
```php
<?php
namespace App\Http\Controllers\API;
use App\Models\Attendee;
use Illuminate\Http\Request;
class AttendeesApiController extends ApiBaseController
{
/**
* @param Request $request
* @return mixed
*/
public function index(Request $request)
{
return Attendee::scope($this->account_id)->paginate($request->get('per_page', 25));
}
/**
* @param Request $request
* @param $attendee_id
* @return mixed
*/
public function show(Request $request, $attendee_id)
{
if ($attendee_id) {
return Attendee::scope($this->account_id)->find($attendee_id);
}
return response('Attendee Not Found', 404);
}
public function store(Request $request)
{
}
public function update(Request $request)
{
}
public function destroy(Request $request)
{
}
}
``` | /content/code_sandbox/app/Http/Controllers/API/AttendeesApiController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 207 |
```php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest
{
//
}
``` | /content/code_sandbox/app/Http/Requests/Request.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 27 |
```php
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Http\Request;
class RemindersController extends Controller
{
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* The password broker implementation.
*
* @var PasswordBroker
*/
protected $passwords;
public function __construct(Guard $auth, PasswordBroker $passwords)
{
$this->auth = $auth;
$this->passwords = $passwords;
$this->middleware('guest');
}
/**
* Get the e-mail subject line to be used for the reset link email.
*
* @return string
*/
protected function getEmailSubject()
{
return isset($this->subject) ? $this->subject : trans("Controllers.your_password_reset_link");
}
/**
* Display the password reminder view.
*
* @return Response
*/
public function getRemind()
{
return \View::make('Public.LoginAndRegister.ForgotPassword');
}
/**
* Handle a POST request to remind a user of their password.
*
* @return Response
*/
public function postRemind(Request $request)
{
$this->validate($request, ['email' => 'required']);
$response = $this->passwords->sendResetLink($request->only('email'));
switch ($response) {
case PasswordBroker::RESET_LINK_SENT:
return redirect()->back()->with('status', trans($response));
case PasswordBroker::INVALID_USER:
return redirect()->back()->withErrors(['email' => trans($response)]);
}
}
/**
* Display the password reset view for the given token.
*
* @param string $token
*
* @return Response
*/
public function getReset($token = null)
{
if (is_null($token)) {
\App::abort(404);
}
return \View::make('Public.LoginAndRegister.ResetPassword')->with('token', $token);
}
/**
* Handle a POST request to reset a user's password.
*
* @return Response
*/
public function postReset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required',
'password' => 'required|confirmed',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = $this->passwords->reset($credentials, function ($user, $password) {
$user->password = bcrypt($password);
$user->save();
$this->auth->login($user);
});
switch ($response) {
case PasswordBroker::PASSWORD_RESET:
\Session::flash('message', trans("Controllers.password_successfully_reset"));
return redirect(route('login'));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
}
``` | /content/code_sandbox/app/Http/Controllers/RemindersController.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 682 |
```php
<?php
namespace App\Http\Requests;
class StoreEventQuestionRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required',
'option' => 'array',
];
}
}
``` | /content/code_sandbox/app/Http/Requests/StoreEventQuestionRequest.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 112 |
```php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}
``` | /content/code_sandbox/app/Http/Middleware/TrimStrings.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 70 |
```php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'install/*',
];
}
``` | /content/code_sandbox/app/Http/Middleware/VerifyCsrfToken.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 109 |
```php
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
``` | /content/code_sandbox/app/Http/Middleware/EncryptCookies.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 63 |
```php
<?php
namespace App\Http\Middleware;
use App\Attendize\Utils;
use App\Models\Account;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class CheckInstalled
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
/*
* Check if the 'installed' file has been created
*/
if (!Utils::isAttendize() && !Utils::installed()) {
return Redirect::to('install');
}
/*
* Redirect user to signup page if there are no accounts
*/
if (Account::count() === 0 && !$request->is('signup*')) {
return redirect()->to('signup');
}
return $next($request);
}
}
``` | /content/code_sandbox/app/Http/Middleware/CheckInstalled.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 192 |
```php
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string
*/
protected $proxies = [
'192.168.1.1',
'192.168.1.2',
];
/**
* The headers that should be used to detect proxies.
*
* @var string
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
``` | /content/code_sandbox/app/Http/Middleware/TrustProxies.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 124 |
```php
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
class CheckForMaintenanceMode extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
'install',
'upgrade',
];
}
``` | /content/code_sandbox/app/Http/Middleware/CheckForMaintenanceMode.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 75 |
```php
<?php
namespace App\Http\Middleware;
use Closure;
class GeneralChecks
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Illuminate\Session\TokenMismatchException
*/
public function handle($request, Closure $next)
{
// Show message to IE 8 and before users
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(?i)msie [2-8]/', $_SERVER['HTTP_USER_AGENT'])) {
session()->flash('message', 'Please update your browser. This application requires a modern browser.');
}
return $next($request);
}
}
``` | /content/code_sandbox/app/Http/Middleware/GeneralChecks.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 165 |
```php
<?php
namespace App\Http\Middleware;
use App\Attendize\Utils;
use App\Models\Organiser;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use JavaScript;
class SetViewVariables
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Utils::installed()) {
/*
* Share the organizers across all views
*/
View::share('organisers', Organiser::scope()->get());
/*
* Set up JS across all views
*/
JavaScript::put([
'User' => [
'full_name' => Auth::check() ? Auth::user()->full_name : '',
'email' => Auth::check() ? Auth::user()->email : '',
'is_confirmed' => Auth::check() ? Auth::user()->is_confirmed : false,
],
'DateTimeFormat' => config('attendize.default_date_picker_format'),
'DateSeparator' => config('attendize.default_date_picker_seperator'),
'GenericErrorMessage' => trans('Controllers.whoops'),
]);
}
return $next($request);
}
}
``` | /content/code_sandbox/app/Http/Middleware/SetViewVariables.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 287 |
```php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Auth;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
if (Auth::guard($guards)->guest()) {
if ($request->is('api/*') || $request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
}
return redirect()->guest('login');
}
$this->authenticate($request, $guards);
return $next($request);
}
}
``` | /content/code_sandbox/app/Http/Middleware/Authenticate.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 268 |
```php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(route('showSelectOrganiser'));
}
return $next($request);
}
}
``` | /content/code_sandbox/app/Http/Middleware/RedirectIfAuthenticated.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 130 |
```php
<?php
namespace App\Http\Middleware;
use App\Models\Organiser;
use Closure;
class FirstRunMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
/*
* If there are no organisers then redirect the user to create one
* else - if there's only one organiser bring the user straight there.
*/
$organizerCount = Organiser::scope()->count();
if ($organizerCount === 0 && !($request->route()->getName() === 'showCreateOrganiser') && !($request->route()->getName() === 'postCreateOrganiser')) {
return redirect(route('showCreateOrganiser', [
'first_run' => '1',
]));
} elseif ($organizerCount === 1 && ($request->route()->getName() === 'showSelectOrganiser')) {
return redirect(route('showOrganiserDashboard', [
'organiser_id' => Organiser::scope()->first()->id,
]));
}
return $next($request);
}
}
``` | /content/code_sandbox/app/Http/Middleware/FirstRunMiddleware.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 260 |
```php
<?php
namespace App\Cancellation;
use App\Models\Attendee;
use App\Models\EventStats;
use Superbalist\Money\Money;
use Services\PaymentGateway\Factory;
use Log;
class OrderCancel extends OrderRefundAbstract
{
public function __construct($order, $attendees)
{
$this->order = $order;
$this->attendees = $attendees;
// We need to set the refund starting amounts first
$this->setRefundAmounts();
}
public static function make($order, $attendees)
{
return new static($order, $attendees);
}
public function cancel()
{
// New refunded amount needs to be saved on the order
$updatedRefundedAmount = $this->refundedAmount->add($this->refundAmount);
// Update the amount refunded on the order
$this->order->amount_refunded = $updatedRefundedAmount->toFloat();
if ($this->organiserAmount->subtract($updatedRefundedAmount)->isZero()) {
$this->order->is_cancelled = true;
// Order can't be both partially and fully refunded at the same time
$this->order->is_partially_refunded = false;
$this->order->order_status_id = config('attendize.order.cancelled');
}
$this->order->save();
// Persist the order refund updates
// With the refunds done, we can mark the attendees as cancelled and refunded as well
$currency = $this->currency;
$this->attendees->map(function (Attendee $attendee) use ($currency) {
$ticketPrice = new Money($attendee->ticket->price, $currency);
$attendee->ticket->decrement('quantity_sold', 1);
$attendee->ticket->decrement('sales_volume', $ticketPrice->toFloat());
$organiserFee = $attendee->event->getOrganiserFee($ticketPrice);
$attendee->ticket->decrement('organiser_fees_volume', $organiserFee->toFloat());
$attendee->is_refunded = true;
$attendee->save();
/** @var EventStats $eventStats */
$eventStats = EventStats::where('event_id', $attendee->event_id)
->where('date', $attendee->created_at->format('Y-m-d'))
->first();
if ($eventStats) {
$eventStats->decrement('tickets_sold', 1);
$eventStats->decrement('sales_volume', $ticketPrice->toFloat());
$eventStats->decrement('organiser_fees_volume', $organiserFee->toFloat());
}
});
}
}
``` | /content/code_sandbox/app/Cancellation/OrderCancel.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 585 |
```php
<?php
namespace App\Cancellation;
use App\Models\Attendee;
use Superbalist\Money\Money;
use Log;
abstract class OrderRefundAbstract
{
protected $order;
protected $attendees;
protected $currency;
protected $organiserAmount;
protected $refundedAmount;
protected $maximumRefundableAmount;
protected $organiserTaxRate;
protected $refundAmount;
protected $gateway;
protected function setRefundAmounts()
{
$this->currency = $this->order->getEventCurrency();
// Get the full order amount, tax and booking fees included
$this->organiserAmount = new Money($this->order->organiser_amount, $this->currency);
Log::debug(sprintf("Total Order Value: %s", $this->organiserAmount->display()));
$this->refundedAmount = new Money($this->order->amount_refunded, $this->currency);
Log::debug(sprintf("Already refunded amount: %s", $this->refundedAmount->display()));
$this->maximumRefundableAmount = $this->organiserAmount->subtract($this->refundedAmount);
Log::debug(sprintf("Maxmimum refundable amount: %s", $this->maximumRefundableAmount->display()));
// We need the organiser tax value to calculate what the attendee would've paid
$event = $this->order->event;
$organiserTaxAmount = new Money($event->organiser->tax_value);
$this->organiserTaxRate = $organiserTaxAmount->divide(100)->__toString();
Log::debug(sprintf("Organiser Tax Rate: %s", $organiserTaxAmount->format() . '%'));
// Sets refund total based on attendees, their ticket prices and the organiser tax rate
$this->setRefundTotal();
}
/**
* Calculates the refund amount from the selected attendees from the ticket price perspective.
*
* It will add the tax value from the organiser if it's set and build the refund amount to equal
* the amount of tickets purchased by the selected attendees. Ex:
* Refunding 2 attendees @ 100EUR with 15% VAT = 230EUR
*/
protected function setRefundTotal()
{
$organiserTaxRate = $this->organiserTaxRate;
$currency = $this->currency;
/**
* Subtotal = (Ticket price + Organiser Fee)
* Tax Amount = Subtotal * Tax rate
* Refund Amount = Subtotal + Tax Amount
*/
$this->refundAmount = new Money($this->attendees->map(function (Attendee $attendee) use (
$organiserTaxRate,
$currency
) {
$ticketPrice = new Money($attendee->ticket->price, $currency);
$organiserFee = new Money($attendee->event->getOrganiserFee($ticketPrice), $currency);
$subTotal = $ticketPrice->add($organiserFee);
Log::debug(sprintf("Ticket Price: %s", $ticketPrice->display()));
Log::debug(sprintf("Ticket Organiser Fee: %s", $organiserFee->display()));
Log::debug(sprintf("Ticket Tax: %s", $subTotal->multiply($organiserTaxRate)->display()));
return $subTotal->add($subTotal->multiply($organiserTaxRate));
})->reduce(function ($carry, $singleTicketWithTax) use ($currency) {
$refundTotal = (new Money($carry, $currency));
return $refundTotal->add($singleTicketWithTax)->format();
}), $currency);
Log::debug(sprintf("Requested Refund should include Tax: %s", $this->refundAmount->display()));
}
}
``` | /content/code_sandbox/app/Cancellation/OrderRefundAbstract.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 818 |
```php
<?php namespace App\Cancellation;
use Symfony\Component\HttpFoundation\Response;
use Exception;
class OrderRefundException extends Exception
{
public function __construct($message)
{
parent::__construct($message, Response::HTTP_UNPROCESSABLE_ENTITY);
}
}
``` | /content/code_sandbox/app/Cancellation/OrderRefundException.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 54 |
```php
<?php namespace App\Cancellation;
use App\Models\Attendee;
use App\Models\Order;
use Superbalist\Money\Money;
class OrderCancellation
{
/** @var Order $order */
private $order;
/** @var array $attendees */
private $attendees;
/** @var OrderRefund $orderRefund */
private $orderRefund;
/**
* OrderCancellation constructor.
*
* @param Order $order
* @param $attendees
*/
public function __construct(Order $order, $attendees)
{
$this->order = $order;
$this->attendees = $attendees;
}
/**
* Create a new instance to be used statically
*
* @param Order $order
* @param $attendees
* @return OrderCancellation
*/
public static function make(Order $order, $attendees): OrderCancellation
{
return new static($order, $attendees);
}
/**
* Cancels an order
*
* @throws OrderRefundException
*/
public function cancel(): void
{
$orderAwaitingPayment = false;
if ($this->order->order_status_id == config('attendize.order.awaiting_payment')) {
$orderAwaitingPayment = true;
$orderCancel = OrderCancel::make($this->order, $this->attendees);
$orderCancel->cancel();
}
// If order can do a refund then refund first
if ($this->order->canRefund() && !$orderAwaitingPayment) {
$orderRefund = OrderRefund::make($this->order, $this->attendees);
$orderRefund->refund();
$this->orderRefund = $orderRefund;
}
// TODO if no refunds can be done, mark the order as cancelled to indicate attendees are cancelled
// Cancel the attendees
$this->attendees->map(static function (Attendee $attendee) {
$attendee->is_cancelled = true;
$attendee->save();
});
}
/**
* Returns the return amount
*
* @return Money
*/
public function getRefundAmount()
{
if ($this->orderRefund === null) {
return new Money('0');
}
return $this->orderRefund->getRefundAmount();
}
}
``` | /content/code_sandbox/app/Cancellation/OrderCancellation.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 526 |
```php
<?php
namespace App\Cancellation;
use App\Models\Attendee;
use App\Models\EventStats;
use Superbalist\Money\Money;
use Services\PaymentGateway\Factory;
use Log;
class OrderRefund extends OrderRefundAbstract
{
public function __construct($order, $attendees)
{
$this->order = $order;
$this->attendees = $attendees;
// We need to set the refund starting amounts first
$this->setRefundAmounts();
// Then we need to check for a valid refund state before we can continue
$this->checkValidRefundState();
$paymentGateway = $order->payment_gateway;
$accountPaymentGateway = $order->account->getGateway($paymentGateway->id);
$config = array_merge($accountPaymentGateway->config, [
'testMode' => config('attendize.enable_test_payments')
]);
$this->gateway = (new Factory())->create($paymentGateway->name, $config);
}
public static function make($order, $attendees)
{
return new static($order, $attendees);
}
public function refund()
{
try {
$response = $this->sendRefundRequest();
} catch (\Exception $e) {
Log::error($e->getMessage());
throw new OrderRefundException(trans("Controllers.refund_exception"));
}
if ($response['successful']) { // Successful is a Boolean
// New refunded amount needs to be saved on the order
$updatedRefundedAmount = $this->refundedAmount->add($this->refundAmount);
// Update the amount refunded on the order
$this->order->amount_refunded = $updatedRefundedAmount->toFloat();
if ($this->organiserAmount->subtract($updatedRefundedAmount)->isZero()) {
$this->order->is_refunded = true;
// Order can't be both partially and fully refunded at the same time
$this->order->is_partially_refunded = false;
$this->order->order_status_id = config('attendize.order.refunded');
} else {
$this->order->is_partially_refunded = true;
$this->order->order_status_id = config('attendize.order.partially_refunded');
}
// Persist the order refund updates
$this->order->save();
// With the refunds done, we can mark the attendees as cancelled and refunded as well
$currency = $this->currency;
$this->attendees->map(function (Attendee $attendee) use ($currency) {
$ticketPrice = new Money($attendee->ticket->price, $currency);
$attendee->ticket->decrement('quantity_sold', 1);
$attendee->ticket->decrement('sales_volume', $ticketPrice->toFloat());
$organiserFee = $attendee->event->getOrganiserFee($ticketPrice);
$attendee->ticket->decrement('organiser_fees_volume', $organiserFee->toFloat());
$attendee->is_refunded = true;
$attendee->save();
/** @var EventStats $eventStats */
$eventStats = EventStats::where('event_id', $attendee->event_id)
->where('date', $attendee->created_at->format('Y-m-d'))
->first();
if ($eventStats) {
$eventStats->decrement('tickets_sold', 1);
$eventStats->decrement('sales_volume', $ticketPrice->toFloat());
$eventStats->decrement('organiser_fees_volume', $organiserFee->toFloat());
}
});
} else {
throw new OrderRefundException($response['error_message']);
}
}
/**
* string
*/
public function getRefundAmount()
{
return $this->refundAmount->format();
}
private function sendRefundRequest()
{
$response = $this->gateway->refundTransaction(
$this->order,
$this->refundAmount->toFloat(),
floatval($this->order->booking_fee) > 0 ? true : false
);
Log::debug(strtoupper($this->order->payment_gateway->name), [
'transactionReference' => $this->order->transaction_id,
'amount' => $this->refundAmount->toFloat(),
'refundApplicationFee' => floatval($this->order->booking_fee) > 0 ? true : false,
]);
return $response;
}
private function checkValidRefundState()
{
$errorMessage = false;
if (!$this->order->transaction_id) {
$errorMessage = trans("Controllers.order_cant_be_refunded");
}
if ($this->order->is_refunded) {
$errorMessage = trans('Controllers.order_already_refunded');
} elseif ($this->maximumRefundableAmount->isZero()) {
$errorMessage = trans('Controllers.nothing_to_refund');
} elseif ($this->refundAmount->isGreaterThan($this->maximumRefundableAmount)) {
// Error if the partial refund tries to refund more than allowed
$errorMessage = trans('Controllers.maximum_refund_amount', [
'money' => $this->maximumRefundableAmount->display(),
]);
}
if ($errorMessage) {
throw new OrderRefundException($errorMessage);
}
}
}
``` | /content/code_sandbox/app/Cancellation/OrderRefund.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 1,164 |
```php
<?php
namespace App\Jobs;
use App\Mail\SendAttendeeInviteMail;
use App\Models\Attendee;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Config;
use Mail;
class SendAttendeeInviteJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $attendee;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Attendee $attendee)
{
$this->attendee = $attendee;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
GenerateTicketJob::dispatchNow($this->attendee);
$mail = new SendAttendeeInviteMail($this->attendee);
Mail::to($this->attendee->email)
->locale(Config::get('app.locale'))
->send($mail);
}
}
``` | /content/code_sandbox/app/Jobs/SendAttendeeInviteJob.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 239 |
```php
<?php
namespace App\Jobs;
use App\Models\Order;
/**
* Generate all the tickets in 1 order
*/
class GenerateTicketsJob extends GenerateTicketsJobBase
{
public $order;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Order $order)
{
$this->attendees = $order->attendees;
$this->event = $order->event;
$this->file_name = $order->order_reference;
$this->order = $order;
}
}
``` | /content/code_sandbox/app/Jobs/GenerateTicketsJob.php | php | 2016-03-03T01:33:10 | 2024-08-16T12:05:02 | Attendize | Attendize/Attendize | 3,955 | 122 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.