Passed
Push — master ( 0f5c8a...e02280 )
by Davide
38:43
created

EventController::eventBySlugAndRepetition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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

175
        /** @scrutinizer ignore-call */ 
176
        $repetition_text = LaravelEventsCalendar::getRepetitionTextString($event, $firstRpDates);
Loading history...
176
177
        // True if the repetition start and end on the same day
178 5
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
179
180 5
        return view('laravel-events-calendar::events.show', compact('event'))
181 5
                ->with('category', $category)
182 5
                ->with('teachers', $teachers)
183 5
                ->with('organizers', $organizers)
184 5
                ->with('venue', $venue)
185 5
                ->with('country', $country)
186 5
                ->with('region', $region)
187 5
                ->with('continent', $continent)
188 5
                ->with('datesTimes', $firstRpDates)
189 5
                ->with('repetition_text', $repetition_text)
190 5
                ->with('sameDateStartEnd', $sameDateStartEnd);
191
    }
192
193
    /***************************************************************************/
194
195
    /**
196
     * Show the form for editing the specified resource.
197
     *
198
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
199
     * @return \Illuminate\Http\RedirectResponse | \Illuminate\View\View
200
     */
201 1
    public function edit(Event $event)
202
    {
203
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
204 1
        if (Auth::user()->id == $event->created_by || Auth::user()->group == 1 || Auth::user()->group == 2) {
0 ignored issues
show
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...
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...
205 1
            $authorUserId = $this->getLoggedAuthorId();
206
207
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
208 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
209
210 1
            $users = User::orderBy('name')->pluck('name', 'id');
211 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
212 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
213 1
            $venues = DB::table('event_venues')
214 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
215
216 1
            $eventFirstRepetition = DB::table('event_repetitions')
217 1
                    ->select('id', 'start_repeat', 'end_repeat')
218 1
                    ->where('event_id', '=', $event->id)
219 1
                    ->first();
220
221 1
            $dateTime = [];
222 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
223 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
224 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
225 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
226 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
227 1
            $dateTime['multipleDates'] = $event->multiple_dates;
228
229 1
            $multiple_teachers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->teachers);
0 ignored issues
show
Bug introduced by
The method getCollectionIdsSeparatedByComma() 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

229
            /** @scrutinizer ignore-call */ 
230
            $multiple_teachers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->teachers);
Loading history...
230 1
            $multiple_organizers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->organizers);
231
232 1
            return view('laravel-events-calendar::events.edit', compact('event'))
233 1
                        ->with('eventCategories', $eventCategories)
234 1
                        ->with('users', $users)
235 1
                        ->with('teachers', $teachers)
236 1
                        ->with('multiple_teachers', $multiple_teachers)
237 1
                        ->with('organizers', $organizers)
238 1
                        ->with('multiple_organizers', $multiple_organizers)
239 1
                        ->with('venues', $venues)
240 1
                        ->with('dateTime', $dateTime)
241 1
                        ->with('authorUserId', $authorUserId);
242
        } else {
243
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
244
        }
245
    }
246
247
    /***************************************************************************/
248
249
    /**
250
     * Update the specified resource in storage.
251
     *
252
     * @param  \Illuminate\Http\Request  $request
253
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
254
     * @return \Illuminate\Http\RedirectResponse
255
     */
256 2
    public function update(Request $request, Event $event)
257
    {
258
        // Validate form datas
259 2
        $validator = $this->eventsValidator($request);
260 2
        if ($validator->fails()) {
261 1
            return back()->withErrors($validator)->withInput();
262
        }
263
264 1
        $this->saveOnDb($request, $event);
265
266 1
        return redirect()->route('events.index')
267 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
268
    }
269
270
    /***************************************************************************/
271
272
    /**
273
     * Remove the specified resource from storage.
274
     *
275
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
276
     * @return \Illuminate\Http\RedirectResponse
277
     */
278 1
    public function destroy(Event $event)
279
    {
280 1
        DB::table('event_repetitions')
281 1
                ->where('event_id', $event->id)
282 1
                ->delete();
283
284 1
        $event->delete();
285
286 1
        return redirect()->route('events.index')
287 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
288
    }
289
290
    /***************************************************************************/
291
292
    /**
293
     * To save event repetitions for create and update methods.
294
     *
295
     * @param  \Illuminate\Http\Request  $request
296
     * @param  int  $eventId
297
     * @return void
298
     */
299 31
    public function saveEventRepetitions(Request $request, int $eventId)
300
    {
301 31
        EventRepetition::deletePreviousRepetitions($eventId);
302
303
        // Saving repetitions - If it's a single event will be stored with just one repetition
304
        //$timeStart = date('H:i:s', strtotime($request->get('time_start')));
305
        //$timeEnd = date('H:i:s', strtotime($request->get('time_end')));
306
        //$timeStart = $request->get('time_start');
307
        //$timeEnd = $request->get('time_end');
308 31
        $timeStart = date('H:i', strtotime($request->get('time_start')));
309 31
        $timeEnd = date('H:i', strtotime($request->get('time_end')));
310
311 31
        switch ($request->get('repeat_type')) {
312 31
                case '1':  // noRepeat
313 23
                    $eventRepetition = new EventRepetition();
314 23
                    $eventRepetition->event_id = $eventId;
315
316 23
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
317 23
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
318
319 23
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
320 23
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
321 23
                    $eventRepetition->save();
322
323 23
                    break;
324
325 8
                case '2':   // repeatWeekly
326
                    // Convert the start date in a format that can be used for strtotime
327 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
328
329
                    // Calculate repeat until day
330 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
331 2
                        EventRepetition::saveWeeklyRepeatDates($eventId, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $request->get('repeat_weekly_on_day') can also be of type null; however, parameter $weekDays of DavideCasiraghi\LaravelE...saveWeeklyRepeatDates() 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

331
                        EventRepetition::saveWeeklyRepeatDates($eventId, /** @scrutinizer ignore-type */ $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
Loading history...
332
333 2
                    break;
334
335 6
                case '3':  //repeatMonthly
336
                    // Same of repeatWeekly
337 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
338 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
339
340
                    // Get the array with month repeat details
341 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
342
                        //dump("pp_1");
343 5
                        EventRepetition::saveMonthlyRepeatDates($eventId, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
344
345 5
                    break;
346
347 1
                case '4':  //repeatMultipleDays
348
                    // Same of repeatWeekly
349 1
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
350
351
                    // Get the array with single day repeat details
352 1
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
353
354 1
                        EventRepetition::saveMultipleRepeatDates($eventId, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
355
356 1
                    break;
357
            }
358 31
    }
359
360
    /***************************************************************************/
361
362
    /**
363
     * Send the Misuse mail.
364
     *
365
     * @param  \Illuminate\Http\Request  $request
366
     * @return \Illuminate\Http\RedirectResponse
367
     */
368
    public function reportMisuse(Request $request)
369
    {
370
        $report = [];
371
372
        //$report['senderEmail'] = '[email protected]';
373
        $report['senderEmail'] = $request->user_email;
374
        $report['senderName'] = 'Anonymus User';
375
        $report['subject'] = 'Report misuse form';
376
        //$report['adminEmail'] = env('ADMIN_MAIL');
377
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
378
379
        $report['message_misuse'] = $request->message_misuse;
380
        $report['event_title'] = $request->event_title;
381
        $report['event_id'] = $request->event_id;
382
        $report['event_slug'] = $request->slug;
383
384
        $report['reason'] = LaravelEventsCalendar::getReportMisuseReasonDescription($request->reason);
0 ignored issues
show
Bug introduced by
The method getReportMisuseReasonDescription() 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

384
        /** @scrutinizer ignore-call */ 
385
        $report['reason'] = LaravelEventsCalendar::getReportMisuseReasonDescription($request->reason);
Loading history...
385
386
        /*
387
                switch ($request->reason) {
388
                    case '1':
389
                        $report['reason'] = 'Not about Contact Improvisation';
390
                        break;
391
                    case '2':
392
                        $report['reason'] = 'Contains wrong informations';
393
                        break;
394
                    case '3':
395
                        $report['reason'] = 'It is not translated in english';
396
                        break;
397
                    case '4':
398
                        $report['reason'] = 'Other (specify in the message)';
399
                        break;
400
                }
401
        */
402
403
        //Mail::to($request->user())->send(new ReportMisuse($report));
404
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
405
406
        return redirect()->route('events.misuse-thankyou');
407
    }
408
409
    /***************************************************************************/
410
411
    /**
412
     * Send the mail to the Organizer (from the event modal in the event show view).
413
     *
414
     * @param  \Illuminate\Http\Request  $request
415
     * @return \Illuminate\Http\RedirectResponse
416
     */
417
    public function mailToOrganizer(Request $request)
418
    {
419
        $message = [];
420
        $message['senderEmail'] = $request->user_email;
421
        $message['senderName'] = $request->user_name;
422
        $message['subject'] = 'Request from the Global CI Calendar';
423
        //$message['emailTo'] = $organizersEmails;
424
425
        $message['message'] = $request->message;
426
        $message['event_title'] = $request->event_title;
427
        $message['event_id'] = $request->event_id;
428
        $message['event_slug'] = $request->slug;
429
430
        /*
431
        $eventOrganizers = Event::find($request->event_id)->organizers;
432
        foreach ($eventOrganizers as $eventOrganizer) {
433
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
434
        }*/
435
436
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
437
438
        return redirect()->route('events.organizer-sent');
439
    }
440
441
    /***************************************************************************/
442
443
    /**
444
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
445
     *
446
     * @return \Illuminate\View\View
447
     */
448 1
    public function mailToOrganizerSent()
449
    {
450 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
451
    }
452
453
    /***************************************************************************/
454
455
    /**
456
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
457
     *
458
     * @return \Illuminate\View\View
459
     */
460 1
    public function reportMisuseThankyou()
461
    {
462 1
        return view('laravel-events-calendar::emails.report-thankyou');
463
    }
464
465
    /***************************************************************************/
466
467
    /**
468
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
469
     *
470
     * @param  \Illuminate\Http\Request  $request
471
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
472
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
473
     */
474 31
    public function setEventRepeatFields(Request $request, Event $event)
475
    {
476
        // Set Repeat Until
477 31
        $event->repeat_type = $request->get('repeat_type');
478 31
        if ($request->get('repeat_until')) {
479 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
480 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
481
        }
482
483
        // Weekely - Set multiple week days
484 31
        if ($request->get('repeat_weekly_on_day')) {
485 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
486
            //dd($repeat_weekly_on_day);
487 2
            $i = 0;
488 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
489 2
            $event->repeat_weekly_on = '';
490 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
491 2
                $event->repeat_weekly_on .= $weeek_day;
492 2
                if ($i != $len - 1) {  // not last
493 2
                    $event->repeat_weekly_on .= ',';
494
                }
495 2
                $i++;
496
            }
497
        }
498
499
        // Monthly
500
501
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
502
503 31
        return $event;
504
    }
505
506
    /***************************************************************************/
507
508
    /**
509
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
510
     * - Used by the AJAX in the event repeat view -
511
     * - The HTML contain a <select></select> with four <options></options>.
512
     *
513
     * @param  \Illuminate\Http\Request  $request  - Just the day
514
     * @return string
515
     */
516 1
    public function calculateMonthlySelectOptions(Request $request)
517
    {
518 1
        $monthlySelectOptions = [];
519 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
520 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
521 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
522
523
        // Same day number - eg. "the 28th day of the month"
524 1
        $dateArray = explode('/', $request->day);
525 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
526
527 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
528 1
        $repeatText = sprintf($format, 'day');
0 ignored issues
show
Bug introduced by
It seems like $format can also be of type array and array; however, parameter $format of sprintf() 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

528
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
529
530 1
        array_push($monthlySelectOptions, [
531 1
            'value' => '0|'.$dayNumber,
532 1
            'text' => $repeatText,
533
        ]);
534
535
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
536 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
537 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

537
            /** @scrutinizer ignore-call */ 
538
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
538
539 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfTheMonth).'_x_of_the_month');
540 1
        $repeatText = sprintf($format, $dayOfWeekString);
541
542 1
        array_push($monthlySelectOptions, [
543 1
            'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
544 1
            'text' => $repeatText,
545
        ]);
546
547
        // 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)
548 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

548
            /** @scrutinizer ignore-call */ 
549
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
549
550 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($dayOfMonthFromTheEnd + 1).'_to_last_x_of_the_month');
551 1
        $repeatText = sprintf($format, 'day');
552
553 1
        array_push($monthlySelectOptions, [
554 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
555 1
            'text' => $repeatText,
556
        ]);
557
558
        // 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)
559 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

559
            /** @scrutinizer ignore-call */ 
560
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
560
561 1
            if ($weekOfMonthFromTheEnd == 1) {
562
                $weekValue = 0;
563
            } else {
564 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
565
            }
566
567 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
568 1
        $repeatText = sprintf($format, $dayOfWeekString);
569
570 1
        array_push($monthlySelectOptions, [
571 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
572 1
            'text' => $repeatText,
573
        ]);
574
575
        // GENERATE the HTML to return
576 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
577 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='".$selectTitle."'>";
0 ignored issues
show
Bug introduced by
Are you sure $selectTitle of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

577
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='"./** @scrutinizer ignore-type */ $selectTitle."'>";
Loading history...
578 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
579 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
580
        }
581 1
        $onMonthlyKindSelect .= '</select>';
582
583 1
        return $onMonthlyKindSelect;
584
    }
585
586
    // **********************************************************************
587
588
    /**
589
     * Save/Update the record on DB.
590
     *
591
     * @param  \Illuminate\Http\Request $request
592
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
593
     * @return void
594
     */
595 31
    public function saveOnDb(Request $request, Event $event)
596
    {
597
        //$countries = Country::getCountries();
598 31
        $teachers = Teacher::pluck('name', 'id');
599
600
        /*$venue = DB::table('event_venues')
601
                ->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')
602
                ->where('event_venues.id', '=', $request->get('venue_id'))
603
                ->first();*/
604
605 31
        $event->title = $request->get('title');
606 31
        $event->description = clean($request->get('description'));
607
608 31
        if ($request->get('created_by')) {
609 31
            $event->created_by = $request->get('created_by');
610
        }
611
612 31
        if (! $event->slug) {
613 31
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
614
        }
615 31
        $event->category_id = $request->get('category_id');
616 31
        $event->venue_id = $request->get('venue_id');
617 31
        $event->image = $request->get('image');
618 31
        $event->contact_email = $request->get('contact_email');
619 31
        $event->website_event_link = $request->get('website_event_link');
620 31
        $event->facebook_event_link = $request->get('facebook_event_link');
621 31
        $event->status = $request->get('status');
622 31
        $event->on_monthly_kind = $request->get('on_monthly_kind');
623 31
        $event->multiple_dates = $request->get('multiple_dates');
624
625
        // Event teaser image upload
626 31
        if ($request->file('image')) {
627
            $imageFile = $request->file('image');
628
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
629
            $imageSubdir = 'events_teaser';
630
            $imageWidth = 968;
631
            $thumbWidth = 310;
632
633
            $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
634
            $event->image = $imageName;
635
        } else {
636 31
            $event->image = $request->get('image');
637
        }
638
639
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
640 31
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers'))); // keep just this SC
641
642
        // Multiple teachers - populate support column field
643 31
        $event->sc_teachers_names = '';
644 31
        if ($request->get('multiple_teachers')) {
645 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
646
647 2
            $multiple_teachers_names = [];
648 2
            foreach ($multiple_teachers as $key => $teacher_id) {
649 2
                $multiple_teachers_names[] = $teachers[$teacher_id];
650
            }
651
652 2
            $event->sc_teachers_names .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($multiple_teachers_names);
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

652
            $event->sc_teachers_names .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($multiple_teachers_names);
Loading history...
653
        }
654
655
        // Set the Event attributes about repeating (repeat until field and multiple days)
656 31
        $event = $this->setEventRepeatFields($request, $event);
657
658
        // Save event and repetitions
659 31
        $event->save();
660 31
        $this->saveEventRepetitions($request, $event->id);
661
662
        // Update multi relationships with teachers and organizers tables.
663 31
        if ($request->get('multiple_teachers')) {
664 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
665 2
            $event->teachers()->sync($multiple_teachers);
666
        } else {
667 29
            $event->teachers()->sync([]);
668
        }
669 31
        if ($request->get('multiple_organizers')) {
670
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
671
            $event->organizers()->sync($multiple_organizers);
672
        } else {
673 31
            $event->organizers()->sync([]);
674
        }
675
676 31
        Cache::forget('active_events');
677 31
        Cache::forget('active_events_map_markers');
678 31
        Cache::forget('active_events_map_markers_data');
679 31
    }
680
681
    /***********************************************************************/
682
683
    /**
684
     * Get creator email.
685
     *
686
     * @param  int $created_by
687
     * @return \Illuminate\Foundation\Auth\User
688
     */
689
    public function getCreatorEmail(int $created_by)
690
    {
691
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
692
                ->select('email')
693
                ->where('id', $created_by)
694
                ->first();
695
696
        $ret = $creatorEmail->email;
697
698
        return $ret;
699
    }
700
701
    /***************************************************************************/
702
703
    /**
704
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
705
     *
706
     * @param  string  $slug
707
     * @return \Illuminate\View\View
708
     */
709 1
    public function eventBySlug(string $slug)
710
    {
711 1
        $event = Event::where('slug', $slug)->first();
712 1
        $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
713
714 1
        return $this->show($event, $firstRpDates);
715
    }
716
717
    /***************************************************************************/
718
719
    /**
720
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
721
     * @param  string $slug
722
     * @param  int $repetitionId
723
     * @return \Illuminate\View\View
724
     */
725 4
    public function eventBySlugAndRepetition(string $slug, int $repetitionId)
726
    {
727 4
        $event = Event::where('slug', $slug)->first();
728 4
        $firstRpDates = EventRepetition::getFirstEventRpDatesByRepetitionId($repetitionId);
729
730
        // If not found get the first repetion of the event in the future.
731 4
        if (empty($firstRpDates)) {
732 1
            $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
733
        }
734
735 4
        return $this->show($event, $firstRpDates);
736
    }
737
738
    /***************************************************************************/
739
740
    /**
741
     * Return the Event validator with all the defined constraint.
742
     * @param  \Illuminate\Http\Request  $request
743
     * @return \Illuminate\Contracts\Validation\Validator
744
     */
745 32
    public function eventsValidator(Request $request)
746
    {
747
        $rules = [
748 32
            'title' => 'required',
749 32
            'description' => 'required',
750 32
            'category_id' => 'required',
751 32
            'venue_id' => 'required',
752 32
            'startDate' => 'required',
753 32
            'endDate' => 'required',
754 32
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
755 32
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
756 32
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
757 32
            'contact_email' => 'nullable|email',
758 32
            'facebook_event_link' => 'nullable|url',
759 32
            'website_event_link' => 'nullable|url',
760
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
761
        ];
762 32
        if ($request->hasFile('image')) {
763
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
764
        }
765
766
        $messages = [
767 32
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
768
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
769
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
770
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
771
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
772
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
773
        ];
774
775 32
        $validator = Validator::make($request->all(), $rules, $messages);
776
777
        // End date and start date must match if the event is repetitive
778
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
779 32
            return $input->repeat_type > 1;
780 32
        });
781
782 32
        return $validator;
783
    }
784
}
785