Passed
Push — master ( 62ce37...c5f967 )
by Davide
16:45
created

EventController::reportMisuseThankyou()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

198
                            /** @scrutinizer ignore-call */ 
199
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
Loading history...
199
                        }
200
                        // create from an array a string with all the values divided by " and "
201 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
202
203 1
                    $repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
204 1
                    break;
205 1
                case '3': //repeatMonthly
206 1
                    $repeatUntil = new DateTime($event->repeat_until);
207 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

207
                    /** @scrutinizer ignore-call */ 
208
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
Loading history...
208 1
                    $repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
209 1
                    break;
210
211
                case '4': //repeatMultipleDays
212
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
213
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
214
                    
215
                    // Sort the datas  
216
                       usort($singleDaysRepeatDatas, function($a, $b) {
217
                           $a = Carbon::createFromFormat('d/m/Y', $a);
218
                           $b = Carbon::createFromFormat('d/m/Y', $b);
219
          
220
                           return strtotime($a) - strtotime($b);
221
                       });
222
                    
223
                    $repetition_text = 'The event happens on this dates: ';
224
                    $repetition_text .= $dateStart.', ';
225
                    $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

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

445
                if (LaravelEventsCalendar::/** @scrutinizer ignore-call */ isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
Loading history...
446 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
447
                }
448
            }
449
        }
450 2
    }
451
452
    /***************************************************************************/
453
454
    /**
455
     * Save all the weekly repetitions inthe event_repetitions table
456
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
457
     *
458
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
459
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
460
     *                      0|28 the 28th day of the month
461
     *                      1|2|2 the 2nd Tuesday of the month
462
     *                      2|17 the 18th to last day of the month
463
     *                      3|1|3 the 2nd to last Wednesday of the month
464
     * @param  string  $startDate (Y-m-d)
465
     * @param  string  $repeatUntilDate (Y-m-d)
466
     * @param  string  $timeStart (H:i:s)
467
     * @param  string  $timeEnd (H:i:s)
468
     * @return void
469
     */
470 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
471
    {
472 5
        $start = $month = Carbon::create($startDate);
0 ignored issues
show
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

472
        $start = $month = Carbon::create(/** @scrutinizer ignore-type */ $startDate);
Loading history...
Unused Code introduced by
The assignment to $start is dead and can be removed.
Loading history...
473 5
        $end = Carbon::create($repeatUntilDate);
474
475 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...
476 5
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
477
478 5
        switch ($monthRepeatDatas[0]) {
479 5
            case '0':  // Same day number - eg. "the 28th day of the month"
480 2
                while ($month < $end) {
481 2
                    $day = $month->format('Y-m-d');
482
483 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
484 2
                    $month = $month->addMonth();
485
                }
486 2
                break;
487 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
488 1
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
489 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
490
491 1
                while ($month < $end) {
492 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
493 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
494
495 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

495
                    $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...
496
497 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

497
                    $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

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

741
        /** @scrutinizer ignore-call */ 
742
        $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayNumber);
Loading history...
742
743 1
        array_push($monthlySelectOptions, [
744 1
                'value' => '0|'.$dayNumber,
745 1
                'text' => 'the '.$dayNumber.$ordinalIndicator.' day of the month',
746
            ]);
747
748
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
749 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
750 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

750
            /** @scrutinizer ignore-call */ 
751
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
751 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
752
753 1
            array_push($monthlySelectOptions, [
754 1
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
755 1
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
756
            ]);
757
758
        // 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)
759 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

759
            /** @scrutinizer ignore-call */ 
760
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
760
761 1
        if ($dayOfMonthFromTheEnd == 0) {
762
            $dayText = 'last';
763
        } else {
764 1
            $numberOfTheDay = $dayOfMonthFromTheEnd + 1;
765 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($numberOfTheDay);
766 1
            $dayText = $numberOfTheDay.$ordinalIndicator.' to last';
767
        }
768
769 1
        array_push($monthlySelectOptions, [
770 1
                'value' => '2|'.$dayOfMonthFromTheEnd,
771 1
                'text' => 'the '.$dayText.' day of the month',
772
            ]);
773
774
        // 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)
775 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

775
            /** @scrutinizer ignore-call */ 
776
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
776
777 1
        if ($weekOfMonthFromTheEnd == 1) {
778
            $weekText = 'last ';
779
            $weekValue = 0;
780
        } else {
781 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfMonthFromTheEnd);
782 1
            $weekText = $weekOfMonthFromTheEnd.$ordinalIndicator.' to last ';
783 1
            $weekValue = $weekOfMonthFromTheEnd - 1;
784
        }
785
786 1
        array_push($monthlySelectOptions, [
787 1
                'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
788 1
                'text' => 'the '.$weekText.$dayOfWeekString.' of the month',
789
            ]);
790
791
        // GENERATE the HTML to return
792 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='Select repeat monthly kind'>";
793 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
794 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
795
        }
796 1
        $onMonthlyKindSelect .= '</select>';
797
798 1
        return $onMonthlyKindSelect;
799
    }
800
801
    // **********************************************************************
802
803
    /**
804
     * Save/Update the record on DB.
805
     *
806
     * @param  \Illuminate\Http\Request $request
807
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
808
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
809
     */
810 20
    public function saveOnDb($request, $event)
811
    {
812 20
        $countries = Country::getCountries();
813 20
        $teachers = Teacher::pluck('name', 'id');
814
815 20
        $venue = DB::table('event_venues')
816 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')
817 20
                ->where('event_venues.id', '=', $request->get('venue_id'))
818 20
                ->first();
819
820 20
        $event->title = $request->get('title');
821 20
        $event->description = clean($request->get('description'));
822
823
        //$event->created_by = (isset(Auth::id())) ? Auth::id() : null;
824
        //$event->created_by = Auth::id();
825 20
        if ($request->get('created_by')) {
826 20
            $event->created_by = $request->get('created_by');
827
        }
828
829 20
        if (! $event->slug) {
830 20
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
831
        }
832 20
        $event->category_id = $request->get('category_id');
833 20
        $event->venue_id = $request->get('venue_id');
834 20
        $event->image = $request->get('image');
835 20
        $event->contact_email = $request->get('contact_email');
836 20
        $event->website_event_link = $request->get('website_event_link');
837 20
        $event->facebook_event_link = $request->get('facebook_event_link');
838 20
        $event->status = $request->get('status');
839 20
        $event->on_monthly_kind = $request->get('on_monthly_kind');
840 20
        $event->multiple_dates = $request->get('multiple_dates');
841
842
        // Event teaser image upload
843
        //dd($request->file('image'));
844 20
        if ($request->file('image')) {
845
            $imageFile = $request->file('image');
846
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
847
            $imageSubdir = 'events_teaser';
848
            $imageWidth = '968';
849
            $thumbWidth = '310';
850
851
            $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

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