Completed
Push — master ( 97b9a3...d270bd )
by Davide
32:21
created

EventController::weekOfMonthFromTheEnd()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.7873

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 29
ccs 13
cts 19
cp 0.6842
rs 9.2888
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 5.7873
1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Http\Controllers;
4
5
use DateTime;
6
use Validator;
7
use DatePeriod;
8
use DateInterval;
9
use Carbon\Carbon;
10
use Illuminate\Support\Str;
11
use Illuminate\Http\Request;
12
use Illuminate\Validation\Rule;
13
use Illuminate\Support\Facades\DB;
14
use Illuminate\Foundation\Auth\User;
15
use Illuminate\Support\Facades\Auth;
16
use Illuminate\Support\Facades\Mail;
17
use DavideCasiraghi\LaravelEventsCalendar\Models\Event;
18
use DavideCasiraghi\LaravelEventsCalendar\Models\Country;
19
use DavideCasiraghi\LaravelEventsCalendar\Models\Teacher;
20
use DavideCasiraghi\LaravelEventsCalendar\Models\Organizer;
21
use DavideCasiraghi\LaravelEventsCalendar\Mail\ReportMisuse;
22
use DavideCasiraghi\LaravelEventsCalendar\Models\EventVenue;
23
use DavideCasiraghi\LaravelEventsCalendar\Models\EventCategory;
24
use DavideCasiraghi\LaravelEventsCalendar\Mail\ContactOrganizer;
25
use DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition;
26
use DavideCasiraghi\LaravelEventsCalendar\Facades\LaravelEventsCalendar;
27
28
class EventController extends Controller
29
{
30
    /***************************************************************************/
31
    /* Restrict the access to this resource just to logged in users except show view */
32 26
    public function __construct()
33
    {
34 26
        $this->middleware('auth', ['except' => ['show', 'reportMisuse', 'reportMisuseThankyou', 'mailToOrganizer', 'mailToOrganizerSent', 'eventBySlug', 'eventBySlugAndRepetition', 'EventsListByCountry', 'calculateMonthlySelectOptions']]);
35 26
    }
36
37
    /***************************************************************************/
38
39
    /**
40
     * Display a listing of the resource.
41
     * @param  \Illuminate\Http\Request  $request
42
     * @return \Illuminate\Http\Response
43
     */
44 1
    public function index(Request $request)
45
    {
46
        // To show just the events created by the the user - If admin or super admin is set to null show all the events
47 1
        $authorUserId = ($this->getLoggedAuthorId()) ? $this->getLoggedAuthorId() : null; // if is 0 (super admin or admin) it's setted to null to avoid include it in the query
48
49 1
        $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
50 1
        $countries = Country::orderBy('name')->pluck('name', 'id');
51 1
        $venues = EventVenue::pluck('country_id', 'id');
52
53 1
        $searchKeywords = $request->input('keywords');
54 1
        $searchCategory = $request->input('category_id');
55 1
        $searchCountry = $request->input('country_id');
56
57 1
        if ($searchKeywords || $searchCategory || $searchCountry) {
58
            $events = Event::
59
                // Show only the events owned by the user, if the user is an admin or super admin show all the events
60
                when(isset($authorUserId), function ($query, $authorUserId) {
61
                    return $query->where('created_by', $authorUserId);
62
                })
63
                ->when($searchKeywords, function ($query, $searchKeywords) {
64
                    return $query->where('title', $searchKeywords)->orWhere('title', 'like', '%'.$searchKeywords.'%');
65
                })
66
                ->when($searchCategory, function ($query, $searchCategory) {
67
                    return $query->where('category_id', '=', $searchCategory);
68
                })
69
                ->when($searchCountry, function ($query, $searchCountry) {
70
                    return $query->join('event_venues', 'events.venue_id', '=', 'event_venues.id')->where('event_venues.country_id', '=', $searchCountry);
71
                })
72
                ->select('*', 'events.id as id', 'events.slug as slug', 'events.image as image') // To keep in the join the id of the Events table - https://stackoverflow.com/questions/28062308/laravel-eloquent-getting-id-field-of-joined-tables-in-eloquent
73
                ->paginate(20);
74
75
        //dd($events);
76
        } else {
77 1
            $events = Event::latest()
78
                ->when($authorUserId, function ($query, $authorUserId) {
79
                    return $query->where('created_by', $authorUserId);
80 1
                })
81 1
                ->paginate(20);
82
        }
83
84 1
        return view('laravel-events-calendar::events.index', compact('events'))
85 1
            ->with('i', (request()->input('page', 1) - 1) * 20)
86 1
            ->with('eventCategories', $eventCategories)
87 1
            ->with('countries', $countries)
88 1
            ->with('venues', $venues)
89 1
            ->with('searchKeywords', $searchKeywords)
90 1
            ->with('searchCategory', $searchCategory)
91 1
            ->with('searchCountry', $searchCountry);
92
    }
93
94
    /***************************************************************************/
95
96
    /**
97
     * Show the form for creating a new resource.
98
     *
99
     * @return \Illuminate\Http\Response
100
     */
101 1
    public function create()
102
    {
103 1
        $authorUserId = $this->getLoggedAuthorId();
104
105 1
        $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
106 1
        $users = User::orderBy('name')->pluck('name', 'id');
107 1
        $teachers = Teacher::orderBy('name')->pluck('name', 'id');
108 1
        $organizers = Organizer::orderBy('name')->pluck('name', 'id');
109
        //$venues = EventVenue::pluck('name', 'id');
110 1
        $venues = DB::table('event_venues')
111 1
                ->select('id', 'name', 'city')->orderBy('name')->get();
112
113 1
        $dateTime = [];
114 1
        $dateTime['repeatUntil'] = null;
115 1
        $dateTime['multipleDates'] = null;
116
117 1
        return view('laravel-events-calendar::events.create')
118 1
            ->with('eventCategories', $eventCategories)
119 1
            ->with('users', $users)
120 1
            ->with('teachers', $teachers)
121 1
            ->with('organizers', $organizers)
122 1
            ->with('venues', $venues)
123 1
            ->with('dateTime', $dateTime)
124 1
            ->with('authorUserId', $authorUserId);
125
    }
126
127
    /***************************************************************************/
128
129
    /**
130
     * Store a newly created resource in storage.
131
     *
132
     * @param  \Illuminate\Http\Request  $request
133
     * @return \Illuminate\Http\Response
134
     */
135 21
    public function store(Request $request)
136
    {
137
        // Validate form datas
138 21
        $validator = $this->eventsValidator($request);
139 21
        if ($validator->fails()) {
140
            //dd($validator->failed());
141 1
            return back()->withErrors($validator)->withInput();
142
        }
143
144 20
        $event = new Event();
145 20
        $this->saveOnDb($request, $event);
146
147 20
        return redirect()->route('events.index')
148 20
                        ->with('success', __('laravel-events-calendar::messages.event_added_successfully'));
149
    }
150
151
    /***************************************************************************/
152
153
    /**
154
     * Display the specified resource.
155
     *
156
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
157
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition $firstRpDates
158
     * @return \Illuminate\Http\Response
159
     */
160 4
    public function show(Event $event, $firstRpDates)
161
    {
162 4
        $category = EventCategory::find($event->category_id);
163 4
        $teachers = $event->teachers()->get();
164 4
        $organizers = $event->organizers()->get();
165
166 4
        $venue = DB::table('event_venues')
167 4
                ->select('id', 'name', 'city', 'address', 'zip_code', 'country_id', 'description', 'website')
168 4
                ->where('id', $event->venue_id)
169 4
                ->first();
170
171 4
        $country = DB::table('countries')
172 4
                ->select('id', 'name', 'continent_id')
173 4
                ->where('id', $venue->country_id)
174 4
                ->first();
175
176 4
        $continent = DB::table('continents')
177 4
                ->select('id', 'name')
178 4
                ->where('id', $country->continent_id)
179 4
                ->first();
180
181
        // Repetition text to show
182 4
        switch ($event->repeat_type) {
183 4
                case '1': // noRepeat
184 2
                    $repetition_text = null;
185 2
                    break;
186 2
                case '2': // repeatWeekly
187 1
                    $repeatUntil = new DateTime($event->repeat_until);
188
189
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
190 1
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
191 1
                        $repetitonWeekdayNamesArray = [];
192 1
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
193 1
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
0 ignored issues
show
Bug introduced by
The method decodeRepeatWeeklyOn() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

193
                            /** @scrutinizer ignore-call */ 
194
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
Loading history...
194
                        }
195
                        // create from an array a string with all the values divided by " and "
196 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
197
198 1
                    $repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
199 1
                    break;
200 1
                case '3': //repeatMonthly
201 1
                    $repeatUntil = new DateTime($event->repeat_until);
202 1
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
0 ignored issues
show
Bug introduced by
The method decodeOnMonthlyKind() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

202
                    /** @scrutinizer ignore-call */ 
203
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
Loading history...
203 1
                    $repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
204 1
                    break;
205
206
                case '4': //repeatMultipleDays
207
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
208
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
209
                    //$repetition_text = 'The event happens on this dates: '.$event->multiple_dates;
210
                    $repetition_text = 'The event happens on this dates: ';
211
                    $repetition_text .= $dateStart.', ';
212
                    $repetition_text .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
0 ignored issues
show
Bug introduced by
The method getStringFromArraySeparatedByComma() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

212
                    $repetition_text .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
Loading history...
213
214
                    break;
215
            }
216
217
        // True if the repetition start and end on the same day
218 4
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
219
220 4
        return view('laravel-events-calendar::events.show', compact('event'))
221 4
                ->with('category', $category)
222 4
                ->with('teachers', $teachers)
223 4
                ->with('organizers', $organizers)
224 4
                ->with('venue', $venue)
225 4
                ->with('country', $country)
226 4
                ->with('continent', $continent)
227 4
                ->with('datesTimes', $firstRpDates)
228 4
                ->with('repetition_text', $repetition_text)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $repetition_text does not seem to be defined for all execution paths leading up to this point.
Loading history...
229 4
                ->with('sameDateStartEnd', $sameDateStartEnd);
230
    }
231
232
    /***************************************************************************/
233
234
    /**
235
     * Show the form for editing the specified resource.
236
     *
237
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
238
     * @return \Illuminate\Http\Response
239
     */
240 1
    public function edit(Event $event)
241
    {
242
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
243 1
        if (Auth::user()->id == $event->created_by || Auth::user()->group == 1 || Auth::user()->group == 2) {
0 ignored issues
show
Bug introduced by
Accessing group on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
244 1
            $authorUserId = $this->getLoggedAuthorId();
245
246
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
247 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
248
249 1
            $users = User::orderBy('name')->pluck('name', 'id');
250 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
251 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
252 1
            $venues = DB::table('event_venues')
253 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
254
255 1
            $eventFirstRepetition = DB::table('event_repetitions')
256 1
                    ->select('id', 'start_repeat', 'end_repeat')
257 1
                    ->where('event_id', '=', $event->id)
258 1
                    ->first();
259
260 1
            $dateTime = [];
261 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
262 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
263 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
264 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
265 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
266 1
            $dateTime['multipleDates'] = $event->multiple_dates;
267
268
            // GET Multiple teachers
269 1
            $teachersDatas = $event->teachers;
270 1
            $teachersSelected = [];
271 1
            foreach ($teachersDatas as $teacherDatas) {
272
                array_push($teachersSelected, $teacherDatas->id);
273
            }
274 1
            $multiple_teachers = implode(',', $teachersSelected);
275
276
            // GET Multiple Organizers
277 1
            $organizersDatas = $event->organizers;
278 1
            $organizersSelected = [];
279 1
            foreach ($organizersDatas as $organizerDatas) {
280
                array_push($organizersSelected, $organizerDatas->id);
281
            }
282 1
            $multiple_organizers = implode(',', $organizersSelected);
283
284 1
            return view('laravel-events-calendar::events.edit', compact('event'))
285 1
                        ->with('eventCategories', $eventCategories)
286 1
                        ->with('users', $users)
287 1
                        ->with('teachers', $teachers)
288 1
                        ->with('multiple_teachers', $multiple_teachers)
289 1
                        ->with('organizers', $organizers)
290 1
                        ->with('multiple_organizers', $multiple_organizers)
291 1
                        ->with('venues', $venues)
292 1
                        ->with('dateTime', $dateTime)
293 1
                        ->with('authorUserId', $authorUserId);
294
        } else {
295
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
296
        }
297
    }
298
299
    /***************************************************************************/
300
301
    /**
302
     * Update the specified resource in storage.
303
     *
304
     * @param  \Illuminate\Http\Request  $request
305
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
306
     * @return \Illuminate\Http\Response
307
     */
308 2
    public function update(Request $request, Event $event)
309
    {
310
        // Validate form datas
311 2
        $validator = $this->eventsValidator($request);
312 2
        if ($validator->fails()) {
313 1
            return back()->withErrors($validator)->withInput();
314
        }
315
316 1
        $this->saveOnDb($request, $event);
317
318 1
        return redirect()->route('events.index')
319 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
320
    }
321
322
    /***************************************************************************/
323
324
    /**
325
     * Remove the specified resource from storage.
326
     *
327
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
328
     * @return \Illuminate\Http\Response
329
     */
330 1
    public function destroy(Event $event)
331
    {
332 1
        DB::table('event_repetitions')
333 1
                ->where('event_id', $event->id)
334 1
                ->delete();
335
336 1
        $event->delete();
337
338 1
        return redirect()->route('events.index')
339 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
340
    }
341
342
    /***************************************************************************/
343
344
    /**
345
     * To save event repetitions for create and update methods.
346
     *
347
     * @param  \Illuminate\Http\Request  $request
348
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
349
     * @return void
350
     */
351 20
    public function saveEventRepetitions($request, $event)
352
    {
353 20
        Event::deletePreviousRepetitions($event->id);
354
355
        // Saving repetitions - If it's a single event will be stored with just one repetition
356 20
        $timeStart = date('H:i:s', strtotime($request->get('time_start')));
357 20
        $timeEnd = date('H:i:s', strtotime($request->get('time_end')));
358 20
        switch ($request->get('repeat_type')) {
359 20
                case '1':  // noRepeat
360 13
                    $eventRepetition = new EventRepetition();
361 13
                    $eventRepetition->event_id = $event->id;
362
363 13
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
364 13
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
365
366 13
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
367 13
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
368 13
                    $eventRepetition->save();
369
370 13
                    break;
371
372 7
                case '2':   // repeatWeekly
373
374
                    // Convert the start date in a format that can be used for strtotime
375 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
376
377
                    // Calculate repeat until day
378 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
379 2
                        $this->saveWeeklyRepeatDates($event, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
380
381 2
                    break;
382
383 5
                case '3':  //repeatMonthly
384
                    // Same of repeatWeekly
385 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
386 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
387
388
                    // Get the array with month repeat details
389 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
390
391 5
                        $this->saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
392
393 5
                    break;
394
395
                case '4':  //repeatMultipleDays
396
                    // Same of repeatWeekly
397
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
398
399
                    // Get the array with single day repeat details
400
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
401
402
                        $this->saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
403
404
                    break;
405
            }
406 20
    }
407
408
    /***************************************************************************/
409
410
    /**
411
     * Save all the weekly repetitions in the event_repetitions table.
412
     * $dateStart and $dateEnd are in the format Y-m-d
413
     * $timeStart and $timeEnd are in the format H:i:s.
414
     * $weekDays - $request->get('repeat_weekly_on_day').
415
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
416
     * @param  string  $weekDays
417
     * @param  string  $startDate
418
     * @param  string  $repeatUntilDate
419
     * @param  string  $timeStart
420
     * @param  string  $timeEnd
421
     * @return void
422
     */
423 2
    public function saveWeeklyRepeatDates($event, $weekDays, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
424
    {
425 2
        $beginPeriod = new DateTime($startDate);
426 2
        $endPeriod = new DateTime($repeatUntilDate);
427 2
        $interval = DateInterval::createFromDateString('1 day');
428 2
        $period = new DatePeriod($beginPeriod, $interval, $endPeriod);
429
430 2
        foreach ($period as $day) {  // Iterate for each day of the period
431 2
            foreach ($weekDays as $weekDayNumber) { // Iterate for every day of the week (1:Monday, 2:Tuesday, 3:Wednesday ...)
0 ignored issues
show
Bug introduced by
The expression $weekDays of type string is not traversable.
Loading history...
432 2
                if (LaravelEventsCalendar::isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
0 ignored issues
show
Bug introduced by
The method isWeekDay() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

432
                if (LaravelEventsCalendar::/** @scrutinizer ignore-call */ isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
Loading history...
433 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
434
                }
435
            }
436
        }
437 2
    }
438
439
    /***************************************************************************/
440
441
    /**
442
     * Save all the weekly repetitions inthe event_repetitions table
443
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
444
     *
445
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
446
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
447
     *                      0|28 the 28th day of the month
448
     *                      1|2|2 the 2nd Tuesday of the month
449
     *                      2|17 the 18th to last day of the month
450
     *                      3|1|3 the 2nd to last Wednesday of the month
451
     * @param  string  $startDate (Y-m-d)
452
     * @param  string  $repeatUntilDate (Y-m-d)
453
     * @param  string  $timeStart (H:i:s)
454
     * @param  string  $timeEnd (H:i:s)
455
     * @return void
456
     */
457 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
458
    {
459 5
        $start = $month = Carbon::create($startDate);
0 ignored issues
show
Unused Code introduced by
The assignment to $start is dead and can be removed.
Loading history...
Bug introduced by
$startDate of type string is incompatible with the type integer|null expected by parameter $year of Carbon\Carbon::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

459
        $start = $month = Carbon::create(/** @scrutinizer ignore-type */ $startDate);
Loading history...
460 5
        $end = Carbon::create($repeatUntilDate);
461
462 5
        $numberOfTheWeekArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
0 ignored issues
show
Unused Code introduced by
The assignment to $numberOfTheWeekArray is dead and can be removed.
Loading history...
463 5
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
464
465 5
        switch ($monthRepeatDatas[0]) {
466 5
            case '0':  // Same day number - eg. "the 28th day of the month"
467 2
                while ($month < $end) {
468 2
                    $day = $month->format('Y-m-d');
469
470 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
471 2
                    $month = $month->addMonth();
472
                }
473 2
                break;
474 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
475 1
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
476 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
477
478 1
                while ($month < $end) {
479 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
480 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
481
482 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
0 ignored issues
show
Bug introduced by
$month_number of type string is incompatible with the type integer|null expected by parameter $month of Carbon\Carbon::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

482
                    $day = Carbon::create($year_number, /** @scrutinizer ignore-type */ $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
Loading history...
483
484 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $day can also be of type false; however, parameter $dateEnd of DavideCasiraghi\LaravelE...veEventRepetitionOnDB() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

484
                    $this->saveEventRepetitionOnDB($event->id, $day, /** @scrutinizer ignore-type */ $day, $timeStart, $timeEnd);
Loading history...
Bug introduced by
It seems like $day can also be of type false; however, parameter $dateStart of DavideCasiraghi\LaravelE...veEventRepetitionOnDB() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

484
                    $this->saveEventRepetitionOnDB($event->id, /** @scrutinizer ignore-type */ $day, $day, $timeStart, $timeEnd);
Loading history...
485 1
                    $month = $month->addMonth();
486
                }
487 1
                break;
488 2
            case '2':  // Same day of the month (from the end) - the 3rd to last day (0 if last day, 1 if 2nd to last day, 2 if 3rd to last day)
489 1
                $dayFromTheEnd = $monthRepeatDatas[1];
490 1
                while ($month < $end) {
491 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
492 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
493
494 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->lastOfMonth()->subDays($dayFromTheEnd);
495
496 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
497 1
                    $month = $month->addMonth();
498
                }
499 1
                break;
500 1
            case '3':  // Same weekday/week of the month (from the end) - the last Friday - (0 if last Friday, 1 if the 2nd to last Friday, 2 if the 3nd to last Friday)
501 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
502 1
                $weeksFromTheEnd = $monthRepeatDatas[1];
503
504 1
                while ($month < $end) {
505 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
506 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
507
508 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->lastOfMonth($weekday)->subWeeks($weeksFromTheEnd);
509
510 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
511 1
                    $month = $month->addMonth();
512
                }
513 1
                break;
514
        }
515 5
    }
516
517
    /***************************************************************************/
518
519
    /**
520
     * Save all the weekly repetitions inthe event_repetitions table
521
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
522
     *
523
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
524
     * @param  array   $singleDaysRepeatDatas - explode of $request->get('multiple_dates')
525
     * @param  string  $startDate (Y-m-d)
526
     * @param  string  $timeStart (H:i:s)
527
     * @param  string  $timeEnd (H:i:s)
528
     * @return void
529
     */
530
    public function saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd)
531
    {
532
        $dateTime = strtotime($startDate);
533
        $day = date('Y-m-d', $dateTime);
534
        $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
535
536
        foreach ($singleDaysRepeatDatas as $key => $singleDayRepeatDatas) {
537
            $dateTime = strtotime($singleDayRepeatDatas);
538
            $day = date('Y-m-d', $dateTime);
539
540
            $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
541
        }
542
    }
543
544
    /***************************************************************************/
545
546
    /**
547
     * Save event repetition in the DB.
548
     * $dateStart and $dateEnd are in the format Y-m-d
549
     * $timeStart and $timeEnd are in the format H:i:s.
550
     * @param  int $eventId
551
     * @param  string $dateStart
552
     * @param  string $dateEnd
553
     * @param  string $timeStart
554
     * @param  string $timeEnd
555
     * @return void
556
     */
557 7
    public function saveEventRepetitionOnDB($eventId, $dateStart, $dateEnd, $timeStart, $timeEnd)
558
    {
559 7
        $eventRepetition = new EventRepetition();
560 7
        $eventRepetition->event_id = $eventId;
561
562 7
        $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
563 7
        $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
564 7
        $eventRepetition->save();
565 7
    }
566
567
    /***************************************************************************/
568
569
    /**
570
     * Send the Misuse mail.
571
     *
572
     * @param  \Illuminate\Http\Request  $request
573
     * @return \Illuminate\Http\Response
574
     */
575
    public function reportMisuse(Request $request)
576
    {
577
        $report = [];
578
579
        $report['senderEmail'] = '[email protected]';
580
        $report['senderName'] = 'Anonymus User';
581
        $report['subject'] = 'Report misuse form';
582
        //$report['adminEmail'] = env('ADMIN_MAIL');
583
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
584
585
        $report['message'] = $request->message;
586
        $report['event_title'] = $request->event_title;
587
        $report['event_id'] = $request->event_id;
588
        $report['event_slug'] = $request->slug;
589
590
        switch ($request->reason) {
591
            case '1':
592
                $report['reason'] = 'Not about Contact Improvisation';
593
                break;
594
            case '2':
595
                $report['reason'] = 'Contains wrong informations';
596
                break;
597
            case '3':
598
                $report['reason'] = 'It is not translated in english';
599
                break;
600
            case '4':
601
                $report['reason'] = 'Other (specify in the message)';
602
                break;
603
        }
604
605
        //Mail::to($request->user())->send(new ReportMisuse($report));
606
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
607
608
        return redirect()->route('events.misuse-thankyou');
609
    }
610
611
    /***************************************************************************/
612
613
    /**
614
     * Send the mail to the Organizer (from the event modal in the event show view).
615
     *
616
     * @param  \Illuminate\Http\Request  $request
617
     * @return \Illuminate\Http\Response
618
     */
619
    public function mailToOrganizer(Request $request)
620
    {
621
        $message = [];
622
        $message['senderEmail'] = $request->user_email;
623
        $message['senderName'] = $request->user_name;
624
        $message['subject'] = 'Request from the Global CI Calendar';
625
        //$message['emailTo'] = $organizersEmails;
626
627
        $message['message'] = $request->message;
628
        $message['event_title'] = $request->event_title;
629
        $message['event_id'] = $request->event_id;
630
        $message['event_slug'] = $request->slug;
631
632
        /*
633
        $eventOrganizers = Event::find($request->event_id)->organizers;
634
        foreach ($eventOrganizers as $eventOrganizer) {
635
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
636
        }*/
637
638
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
639
640
        return redirect()->route('events.organizer-sent');
641
    }
642
643
    /***************************************************************************/
644
645
    /**
646
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
647
     *
648
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
649
     * @return \Illuminate\Http\Response
650
     */
651 1
    public function mailToOrganizerSent()
652
    {
653 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
654
    }
655
656
    /***************************************************************************/
657
658
    /**
659
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
660
     * @return \Illuminate\Http\Response
661
     */
662 1
    public function reportMisuseThankyou()
663
    {
664 1
        return view('laravel-events-calendar::emails.report-thankyou');
665
    }
666
667
    /***************************************************************************/
668
669
    /**
670
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
671
     *
672
     * @param  \Illuminate\Http\Request  $request
673
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
674
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
675
     */
676 20
    public function setEventRepeatFields($request, $event)
677
    {
678
        // Set Repeat Until
679 20
        $event->repeat_type = $request->get('repeat_type');
680 20
        if ($request->get('repeat_until')) {
681 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
682 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
683
        }
684
685
        // Weekely - Set multiple week days
686 20
        if ($request->get('repeat_weekly_on_day')) {
687 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
688
            //dd($repeat_weekly_on_day);
689 2
            $i = 0;
690 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
691 2
            $event->repeat_weekly_on = '';
692 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
693 2
                $event->repeat_weekly_on .= $weeek_day;
694 2
                if ($i != $len - 1) {  // not last
695 2
                    $event->repeat_weekly_on .= ',';
696
                }
697 2
                $i++;
698
            }
699
        }
700
701
        // Monthly
702
703
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
704
705 20
        return $event;
706
    }
707
708
    /***************************************************************************/
709
710
    /**
711
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
712
     * - Used by the AJAX in the event repeat view -
713
     * - The HTML contain a <select></select> with four <options></options>.
714
     *
715
     * @param  \Illuminate\Http\Request  $request  - Just the day
716
     * @return string
717
     */
718 1
    public function calculateMonthlySelectOptions(Request $request)
719
    {
720 1
        $monthlySelectOptions = [];
721 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
722 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
723 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
724
725
        // Same day number - eg. "the 28th day of the month"
726 1
        $dateArray = explode('/', $request->day);
727 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
728 1
        $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayNumber);
0 ignored issues
show
Bug introduced by
The method getOrdinalIndicator() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

728
        /** @scrutinizer ignore-call */ 
729
        $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayNumber);
Loading history...
729
730 1
        array_push($monthlySelectOptions, [
731 1
                'value' => '0|'.$dayNumber,
732 1
                'text' => 'the '.$dayNumber.$ordinalIndicator.' day of the month',
733
            ]);
734
735
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
736 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
737 1
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
0 ignored issues
show
Bug introduced by
The method weekdayNumberOfMonth() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

737
            /** @scrutinizer ignore-call */ 
738
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
738 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
739
740 1
            array_push($monthlySelectOptions, [
741 1
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
742 1
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
743
            ]);
744
745
        // Same day of the month (from the end) - the 3rd to last day (0 if last day, 1 if 2nd to last day, , 2 if 3rd to last day)
746 1
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
0 ignored issues
show
Bug introduced by
The method dayOfMonthFromTheEnd() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

746
            /** @scrutinizer ignore-call */ 
747
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
747 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayOfMonthFromTheEnd);
748
749 1
        if ($dayOfMonthFromTheEnd == 0) {
750
            $dayText = 'last';
751
        } else {
752 1
            $numberOfTheDay = $dayOfMonthFromTheEnd + 1;
753 1
            $dayText = $numberOfTheDay.$ordinalIndicator.' to last';
754
        }
755
756 1
        array_push($monthlySelectOptions, [
757 1
                'value' => '2|'.$dayOfMonthFromTheEnd,
758 1
                'text' => 'the '.$dayText.' day of the month',
759
            ]);
760
761
        // Same weekday/week of the month (from the end) - the last Friday - (0 if last Friday, 1 if the 2nd to last Friday, 2 if the 3nd to last Friday)
762 1
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
0 ignored issues
show
Bug introduced by
The method weekOfMonthFromTheEnd() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

762
            /** @scrutinizer ignore-call */ 
763
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
763 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfMonthFromTheEnd);
764
765 1
        if ($weekOfMonthFromTheEnd == 1) {
766
            $weekText = 'last ';
767
            $weekValue = 0;
768
        } else {
769 1
            $weekText = $weekOfMonthFromTheEnd.$ordinalIndicator.' to last ';
770 1
            $weekValue = $weekOfMonthFromTheEnd - 1;
771
        }
772
773 1
        array_push($monthlySelectOptions, [
774 1
                'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
775 1
                'text' => 'the '.$weekText.$dayOfWeekString.' of the month',
776
            ]);
777
778
        // GENERATE the HTML to return
779 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='Select repeat monthly kind'>";
780 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
781 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
782
        }
783 1
        $onMonthlyKindSelect .= '</select>';
784
785 1
        return $onMonthlyKindSelect;
786
    }
787
788
    // **********************************************************************
789
790
    /**
791
     * Save/Update the record on DB.
792
     *
793
     * @param  \Illuminate\Http\Request $request
794
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
795
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
796
     */
797 20
    public function saveOnDb($request, $event)
798
    {
799 20
        $countries = Country::getCountries();
800 20
        $teachers = Teacher::pluck('name', 'id');
801
802 20
        $venue = DB::table('event_venues')
803 20
                ->select('event_venues.id AS venue_id', 'event_venues.name AS venue_name', 'event_venues.country_id AS country_id', 'event_venues.continent_id', 'event_venues.city')
804 20
                ->where('event_venues.id', '=', $request->get('venue_id'))
805 20
                ->first();
806
807 20
        $event->title = $request->get('title');
808 20
        $event->description = clean($request->get('description'));
809
810
        //$event->created_by = (isset(Auth::id())) ? Auth::id() : null;
811
        //$event->created_by = Auth::id();
812 20
        if ($request->get('created_by')) {
813 20
            $event->created_by = $request->get('created_by');
814
        }
815
816 20
        if (! $event->slug) {
817 20
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
818
        }
819 20
        $event->category_id = $request->get('category_id');
820 20
        $event->venue_id = $request->get('venue_id');
821 20
        $event->image = $request->get('image');
822 20
        $event->contact_email = $request->get('contact_email');
823 20
        $event->website_event_link = $request->get('website_event_link');
824 20
        $event->facebook_event_link = $request->get('facebook_event_link');
825 20
        $event->status = $request->get('status');
826 20
        $event->on_monthly_kind = $request->get('on_monthly_kind');
827 20
        $event->multiple_dates = $request->get('multiple_dates');
828
829
        // Event teaser image upload
830
        //dd($request->file('image'));
831 20
        if ($request->file('image')) {
832
            $imageFile = $request->file('image');
833
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
834
            $imageSubdir = 'events_teaser';
835
            $imageWidth = '968';
836
            $thumbWidth = '310';
837
838
            $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
0 ignored issues
show
Bug introduced by
It seems like $imageFile can also be of type Illuminate\Http\UploadedFile; however, parameter $imageFile of DavideCasiraghi\LaravelE...::uploadImageOnServer() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

838
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
839
            $event->image = $imageName;
840
        } else {
841 20
            $event->image = $request->get('image');
842
        }
843
844
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
845 20
        $event->sc_country_id = $venue->country_id;
846 20
        $event->sc_country_name = $countries[$venue->country_id];
847 20
        $event->sc_city_name = $venue->city;
848 20
        $event->sc_venue_name = $venue->venue_name;
849 20
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers')));
850 20
        $event->sc_continent_id = $venue->continent_id;
851
852
        // Multiple teachers - populate support column field
853 20
        $event->sc_teachers_names = '';
854 20
        if ($request->get('multiple_teachers')) {
855 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
856
857 2
            $multiple_teachers_names = [];
858 2
            foreach ($multiple_teachers as $key => $teacher_id) {
859 2
                $multiple_teachers_names[] = $teachers[$teacher_id];
860
            }
861
862 2
            $event->sc_teachers_names .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($multiple_teachers_names);
863
        }
864
865
        // Set the Event attributes about repeating (repeat until field and multiple days)
866 20
        $event = $this->setEventRepeatFields($request, $event);
867
868
        // Save event and repetitions
869 20
        $event->save();
870 20
        $this->saveEventRepetitions($request, $event);
871
872
        // Update multi relationships with teachers and organizers tables.
873 20
        if ($request->get('multiple_teachers')) {
874 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
875 2
            $event->teachers()->sync($multiple_teachers);
876
        } else {
877 18
            $event->teachers()->sync([]);
878
        }
879 20
        if ($request->get('multiple_organizers')) {
880
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
881
            $event->organizers()->sync($multiple_organizers);
882
        } else {
883 20
            $event->organizers()->sync([]);
884
        }
885 20
    }
886
887
    /***********************************************************************/
888
889
    /**
890
     * Get creator email.
891
     *
892
     * @param  int $created_by
893
     * @return \Illuminate\Foundation\Auth\User
894
     */
895
    public function getCreatorEmail($created_by)
896
    {
897
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
898
                ->select('email')
899
                ->where('id', $created_by)
900
                ->first();
901
902
        $ret = $creatorEmail->email;
903
904
        return $ret;
905
    }
906
907
    /***************************************************************************/
908
909
    /**
910
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
911
     *
912
     * @param  string  $slug
913
     * @return \Illuminate\Http\Response
914
     */
915 1
    public function eventBySlug($slug)
916
    {
917 1
        $event = Event::where('slug', $slug)->first();
918 1
        $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
919
920 1
        return $this->show($event, $firstRpDates);
921
    }
922
923
    /***************************************************************************/
924
925
    /**
926
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
927
     * @param  string $slug
928
     * @param  int $repetitionId
929
     * @return \Illuminate\Http\Response
930
     */
931 3
    public function eventBySlugAndRepetition($slug, $repetitionId)
932
    {
933 3
        $event = Event::where('slug', $slug)->first();
934 3
        $firstRpDates = Event::getFirstEventRpDatesByRepetitionId($repetitionId);
935
936
        // If not found get the first repetion of the event in the future.
937 3
        if (! $firstRpDates) {
0 ignored issues
show
introduced by
$firstRpDates is of type DavideCasiraghi\LaravelE...\Models\EventRepetition, thus it always evaluated to true.
Loading history...
938 1
            $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
939
        }
940
941 3
        return $this->show($event, $firstRpDates);
942
    }
943
944
    /***************************************************************************/
945
946
    /**
947
     * Return the Event validator with all the defined constraint.
948
     * @param  \Illuminate\Http\Request  $request
949
     * @return \Illuminate\Http\Response
950
     */
951 21
    public function eventsValidator($request)
952
    {
953
        $rules = [
954 21
            'title' => 'required',
955 21
            'description' => 'required',
956 21
            'category_id' => 'required',
957 21
            'venue_id' => 'required',
958 21
            'startDate' => 'required',
959 21
            'endDate' => 'required',
960 21
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
961 21
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
962 21
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
963 21
            'contact_email' => 'nullable|email',
964 21
            'facebook_event_link' => 'nullable|url',
965 21
            'website_event_link' => 'nullable|url',
966
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
967
        ];
968 21
        if ($request->hasFile('image')) {
969
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
970
        }
971
972
        $messages = [
973 21
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
974
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
975
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
976
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
977
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
978
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
979
        ];
980
981 21
        $validator = Validator::make($request->all(), $rules, $messages);
982
983
        // End date and start date must match if the event is repetitive
984
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
985 21
            return $input->repeat_type > 1;
986 21
        });
987
988 21
        return $validator;
989
    }
990
}
991