Passed
Push — master ( 3a64c6...6fa527 )
by Davide
35:56 queued 11:22
created

EventController   F

Complexity

Total Complexity 63

Size/Duplication

Total Lines 813
Duplicated Lines 0 %

Test Coverage

Coverage 82.26%

Importance

Changes 54
Bugs 13 Features 17
Metric Value
wmc 63
eloc 364
c 54
b 13
f 17
dl 0
loc 813
ccs 306
cts 372
cp 0.8226
rs 3.36

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A index() 0 48 5
A store() 0 14 2
A create() 0 24 1
A update() 0 12 2
A destroy() 0 10 1
B show() 0 82 7
A reportMisuse() 0 35 5
A setEventRepeatFields() 0 30 5
A getCreatorEmail() 0 10 1
A eventsValidator() 0 38 3
A eventBySlugAndRepetition() 0 11 2
A mailToOrganizer() 0 22 1
A mailToOrganizerSent() 0 3 1
B edit() 0 58 8
A eventBySlug() 0 6 1
A calculateMonthlySelectOptions() 0 68 3
A saveEventRepetitions() 0 58 5
A reportMisuseThankyou() 0 3 1
B saveOnDb() 0 79 8

How to fix   Complexity   

Complex Class

Complex classes like EventController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EventController, and based on these observations, apply Extract Interface, too.

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

189
                            /** @scrutinizer ignore-call */ 
190
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
Loading history...
190
                        }
191
                        // create from an array a string with all the values divided by " and "
192 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
193
194
                    //$repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
195 1
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until_x');
196 1
                    $repetition_text = sprintf($format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
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

196
                    $repetition_text = sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
197 1
                    break;
198 2
                case '3': //repeatMonthly
199 1
                    $repeatUntil = new DateTime($event->repeat_until);
200 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

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

223
                    $repetition_text .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
Loading history...
224
225 1
                    break;
226
            }
227
228
        // True if the repetition start and end on the same day
229 5
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
230
231 5
        return view('laravel-events-calendar::events.show', compact('event'))
232 5
                ->with('category', $category)
233 5
                ->with('teachers', $teachers)
234 5
                ->with('organizers', $organizers)
235 5
                ->with('venue', $venue)
236 5
                ->with('country', $country)
237 5
                ->with('region', $region)
238 5
                ->with('continent', $continent)
239 5
                ->with('datesTimes', $firstRpDates)
240 5
                ->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...
241 5
                ->with('sameDateStartEnd', $sameDateStartEnd);
242
    }
243
244
    /***************************************************************************/
245
246
    /**
247
     * Show the form for editing the specified resource.
248
     *
249
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
250
     * @return \Illuminate\Http\Response
251
     */
252 1
    public function edit(Event $event)
253
    {
254
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
255 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...
256 1
            $authorUserId = $this->getLoggedAuthorId();
257
258
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
259 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
260
261 1
            $users = User::orderBy('name')->pluck('name', 'id');
262 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
263 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
264 1
            $venues = DB::table('event_venues')
265 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
266
267 1
            $eventFirstRepetition = DB::table('event_repetitions')
268 1
                    ->select('id', 'start_repeat', 'end_repeat')
269 1
                    ->where('event_id', '=', $event->id)
270 1
                    ->first();
271
272 1
            $dateTime = [];
273 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
274 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
275 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
276 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
277 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
278 1
            $dateTime['multipleDates'] = $event->multiple_dates;
279
280
            // GET Multiple teachers
281
            /*$teachersDatas = $event->teachers;
282
            $teachersSelected = [];
283
            foreach ($teachersDatas as $teacherDatas) {
284
                array_push($teachersSelected, $teacherDatas->id);
285
            }
286
            $multiple_teachers = implode(',', $teachersSelected);*/
287 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

287
            /** @scrutinizer ignore-call */ 
288
            $multiple_teachers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->teachers);
Loading history...
288
289
            // GET Multiple Organizers
290
            /*$organizersDatas = $event->organizers;
291
            $organizersSelected = [];
292
            foreach ($organizersDatas as $organizerDatas) {
293
                array_push($organizersSelected, $organizerDatas->id);
294
            }
295
            $multiple_organizers = implode(',', $organizersSelected);*/
296 1
            $multiple_organizers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->organizers);
297
298 1
            return view('laravel-events-calendar::events.edit', compact('event'))
299 1
                        ->with('eventCategories', $eventCategories)
300 1
                        ->with('users', $users)
301 1
                        ->with('teachers', $teachers)
302 1
                        ->with('multiple_teachers', $multiple_teachers)
303 1
                        ->with('organizers', $organizers)
304 1
                        ->with('multiple_organizers', $multiple_organizers)
305 1
                        ->with('venues', $venues)
306 1
                        ->with('dateTime', $dateTime)
307 1
                        ->with('authorUserId', $authorUserId);
308
        } else {
309
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
310
        }
311
    }
312
313
    /***************************************************************************/
314
315
    /**
316
     * Update the specified resource in storage.
317
     *
318
     * @param  \Illuminate\Http\Request  $request
319
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
320
     * @return \Illuminate\Http\Response
321
     */
322 2
    public function update(Request $request, Event $event)
323
    {
324
        // Validate form datas
325 2
        $validator = $this->eventsValidator($request);
326 2
        if ($validator->fails()) {
327 1
            return back()->withErrors($validator)->withInput();
328
        }
329
330 1
        $this->saveOnDb($request, $event);
331
332 1
        return redirect()->route('events.index')
333 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
334
    }
335
336
    /***************************************************************************/
337
338
    /**
339
     * Remove the specified resource from storage.
340
     *
341
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
342
     * @return \Illuminate\Http\Response
343
     */
344 1
    public function destroy(Event $event)
345
    {
346 1
        DB::table('event_repetitions')
347 1
                ->where('event_id', $event->id)
348 1
                ->delete();
349
350 1
        $event->delete();
351
352 1
        return redirect()->route('events.index')
353 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
354
    }
355
356
    /***************************************************************************/
357
358
    /**
359
     * To save event repetitions for create and update methods.
360
     *
361
     * @param  \Illuminate\Http\Request  $request
362
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
363
     * @return void
364
     */
365 21
    public function saveEventRepetitions(Request $request, int $eventId)
366
    {
367 21
        EventRepetition::deletePreviousRepetitions($eventId);
368
369
        // Saving repetitions - If it's a single event will be stored with just one repetition
370
        //$timeStart = date('H:i:s', strtotime($request->get('time_start')));
371
        //$timeEnd = date('H:i:s', strtotime($request->get('time_end')));
372
        //$timeStart = $request->get('time_start');
373
        //$timeEnd = $request->get('time_end');
374 21
        $timeStart = date('H:i', strtotime($request->get('time_start')));
375 21
        $timeEnd = date('H:i', strtotime($request->get('time_end')));
376
377 21
        switch ($request->get('repeat_type')) {
378 21
                case '1':  // noRepeat
379 13
                    $eventRepetition = new EventRepetition();
380 13
                    $eventRepetition->event_id = $eventId;
381
382 13
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
383 13
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
384
385 13
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
386 13
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
387 13
                    $eventRepetition->save();
388
389 13
                    break;
390
391 8
                case '2':   // repeatWeekly
392
                    // Convert the start date in a format that can be used for strtotime
393 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
394
395
                    // Calculate repeat until day
396 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
397 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

397
                        EventRepetition::saveWeeklyRepeatDates($eventId, /** @scrutinizer ignore-type */ $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
Loading history...
398
399 2
                    break;
400
401 6
                case '3':  //repeatMonthly
402
                    // Same of repeatWeekly
403 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
404 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
405
406
                    // Get the array with month repeat details
407 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
408
                        //dump("pp_1");
409 5
                        EventRepetition::saveMonthlyRepeatDates($eventId, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
410
411 5
                    break;
412
413 1
                case '4':  //repeatMultipleDays
414
                    // Same of repeatWeekly
415 1
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
416
417
                    // Get the array with single day repeat details
418 1
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
419
420 1
                        EventRepetition::saveMultipleRepeatDates($eventId, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
421
422 1
                    break;
423
            }
424 21
    }
425
426
    /***************************************************************************/
427
428
    /**
429
     * Send the Misuse mail.
430
     *
431
     * @param  \Illuminate\Http\Request  $request
432
     * @return \Illuminate\Http\Response
433
     */
434
    public function reportMisuse(Request $request)
435
    {
436
        $report = [];
437
438
        //$report['senderEmail'] = '[email protected]';
439
        $report['senderEmail'] = $request->user_email;
440
        $report['senderName'] = 'Anonymus User';
441
        $report['subject'] = 'Report misuse form';
442
        //$report['adminEmail'] = env('ADMIN_MAIL');
443
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
444
445
        $report['message_misuse'] = $request->message_misuse;
446
        $report['event_title'] = $request->event_title;
447
        $report['event_id'] = $request->event_id;
448
        $report['event_slug'] = $request->slug;
449
450
        switch ($request->reason) {
451
            case '1':
452
                $report['reason'] = 'Not about Contact Improvisation';
453
                break;
454
            case '2':
455
                $report['reason'] = 'Contains wrong informations';
456
                break;
457
            case '3':
458
                $report['reason'] = 'It is not translated in english';
459
                break;
460
            case '4':
461
                $report['reason'] = 'Other (specify in the message)';
462
                break;
463
        }
464
465
        //Mail::to($request->user())->send(new ReportMisuse($report));
466
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
467
468
        return redirect()->route('events.misuse-thankyou');
469
    }
470
471
    /***************************************************************************/
472
473
    /**
474
     * Send the mail to the Organizer (from the event modal in the event show view).
475
     *
476
     * @param  \Illuminate\Http\Request  $request
477
     * @return \Illuminate\Http\Response
478
     */
479
    public function mailToOrganizer(Request $request)
480
    {
481
        $message = [];
482
        $message['senderEmail'] = $request->user_email;
483
        $message['senderName'] = $request->user_name;
484
        $message['subject'] = 'Request from the Global CI Calendar';
485
        //$message['emailTo'] = $organizersEmails;
486
487
        $message['message'] = $request->message;
488
        $message['event_title'] = $request->event_title;
489
        $message['event_id'] = $request->event_id;
490
        $message['event_slug'] = $request->slug;
491
492
        /*
493
        $eventOrganizers = Event::find($request->event_id)->organizers;
494
        foreach ($eventOrganizers as $eventOrganizer) {
495
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
496
        }*/
497
498
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
499
500
        return redirect()->route('events.organizer-sent');
501
    }
502
503
    /***************************************************************************/
504
505
    /**
506
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
507
     *
508
     * @return \Illuminate\Http\Response
509
     */
510 1
    public function mailToOrganizerSent()
511
    {
512 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
513
    }
514
515
    /***************************************************************************/
516
517
    /**
518
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
519
     *
520
     * @return \Illuminate\Http\Response
521
     */
522 1
    public function reportMisuseThankyou()
523
    {
524 1
        return view('laravel-events-calendar::emails.report-thankyou');
525
    }
526
527
    /***************************************************************************/
528
529
    /**
530
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
531
     *
532
     * @param  \Illuminate\Http\Request  $request
533
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
534
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
535
     */
536 21
    public function setEventRepeatFields(Request $request, Event $event)
537
    {
538
        // Set Repeat Until
539 21
        $event->repeat_type = $request->get('repeat_type');
540 21
        if ($request->get('repeat_until')) {
541 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
542 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
543
        }
544
545
        // Weekely - Set multiple week days
546 21
        if ($request->get('repeat_weekly_on_day')) {
547 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
548
            //dd($repeat_weekly_on_day);
549 2
            $i = 0;
550 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
551 2
            $event->repeat_weekly_on = '';
552 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
553 2
                $event->repeat_weekly_on .= $weeek_day;
554 2
                if ($i != $len - 1) {  // not last
555 2
                    $event->repeat_weekly_on .= ',';
556
                }
557 2
                $i++;
558
            }
559
        }
560
561
        // Monthly
562
563
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
564
565 21
        return $event;
566
    }
567
568
    /***************************************************************************/
569
570
    /**
571
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
572
     * - Used by the AJAX in the event repeat view -
573
     * - The HTML contain a <select></select> with four <options></options>.
574
     *
575
     * @param  \Illuminate\Http\Request  $request  - Just the day
576
     * @return string
577
     */
578 1
    public function calculateMonthlySelectOptions(Request $request)
579
    {
580 1
        $monthlySelectOptions = [];
581 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
582 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
583 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
584
585
        // Same day number - eg. "the 28th day of the month"
586 1
        $dateArray = explode('/', $request->day);
587 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
588
589 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
590 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

590
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
591
592 1
        array_push($monthlySelectOptions, [
593 1
            'value' => '0|'.$dayNumber,
594 1
            'text' => $repeatText,
595
        ]);
596
597
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
598 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
599 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

599
            /** @scrutinizer ignore-call */ 
600
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
600
601 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfTheMonth).'_x_of_the_month');
602 1
        $repeatText = sprintf($format, $dayOfWeekString);
603
604 1
        array_push($monthlySelectOptions, [
605 1
            'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
606 1
            'text' => $repeatText,
607
        ]);
608
609
        // 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)
610 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

610
            /** @scrutinizer ignore-call */ 
611
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
611
612 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($dayOfMonthFromTheEnd + 1).'_to_last_x_of_the_month');
613 1
        $repeatText = sprintf($format, 'day');
614
615 1
        array_push($monthlySelectOptions, [
616 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
617 1
            'text' => $repeatText,
618
        ]);
619
620
        // 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)
621 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

621
            /** @scrutinizer ignore-call */ 
622
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
622
623 1
            if ($weekOfMonthFromTheEnd == 1) {
624
                $weekValue = 0;
625
            } else {
626 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
627
            }
628
629 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
630 1
        $repeatText = sprintf($format, $dayOfWeekString);
631
632 1
        array_push($monthlySelectOptions, [
633 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
634 1
            'text' => $repeatText,
635
        ]);
636
637
        // GENERATE the HTML to return
638 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
639 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

639
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='"./** @scrutinizer ignore-type */ $selectTitle."'>";
Loading history...
640 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
641 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
642
        }
643 1
        $onMonthlyKindSelect .= '</select>';
644
645 1
        return $onMonthlyKindSelect;
646
    }
647
648
    // **********************************************************************
649
650
    /**
651
     * Save/Update the record on DB.
652
     *
653
     * @param  \Illuminate\Http\Request $request
654
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
655
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
656
     */
657 21
    public function saveOnDb(Request $request, Event $event)
658
    {
659
        //$countries = Country::getCountries();
660 21
        $teachers = Teacher::pluck('name', 'id');
661
662
        /*$venue = DB::table('event_venues')
663
                ->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')
664
                ->where('event_venues.id', '=', $request->get('venue_id'))
665
                ->first();*/
666
667 21
        $event->title = $request->get('title');
668 21
        $event->description = clean($request->get('description'));
669
670 21
        if ($request->get('created_by')) {
671 21
            $event->created_by = $request->get('created_by');
672
        }
673
674 21
        if (! $event->slug) {
675 21
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
676
        }
677 21
        $event->category_id = $request->get('category_id');
678 21
        $event->venue_id = $request->get('venue_id');
679 21
        $event->image = $request->get('image');
680 21
        $event->contact_email = $request->get('contact_email');
681 21
        $event->website_event_link = $request->get('website_event_link');
682 21
        $event->facebook_event_link = $request->get('facebook_event_link');
683 21
        $event->status = $request->get('status');
684 21
        $event->on_monthly_kind = $request->get('on_monthly_kind');
685 21
        $event->multiple_dates = $request->get('multiple_dates');
686
687
        // Event teaser image upload
688 21
        if ($request->file('image')) {
689
            $imageFile = $request->file('image');
690
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
691
            $imageSubdir = 'events_teaser';
692
            $imageWidth = 968;
693
            $thumbWidth = 310;
694
695
            $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[] and array and null; however, parameter $imageFile of DavideCasiraghi\LaravelE...::uploadImageOnServer() does only seem to accept Illuminate\Http\UploadedFile, 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

695
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
696
            $event->image = $imageName;
697
        } else {
698 21
            $event->image = $request->get('image');
699
        }
700
701
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
702 21
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers'))); // keep just this SC
703
704
        // Multiple teachers - populate support column field
705 21
        $event->sc_teachers_names = '';
706 21
        if ($request->get('multiple_teachers')) {
707 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
708
709 2
            $multiple_teachers_names = [];
710 2
            foreach ($multiple_teachers as $key => $teacher_id) {
711 2
                $multiple_teachers_names[] = $teachers[$teacher_id];
712
            }
713
714 2
            $event->sc_teachers_names .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($multiple_teachers_names);
715
        }
716
717
        // Set the Event attributes about repeating (repeat until field and multiple days)
718 21
        $event = $this->setEventRepeatFields($request, $event);
719
720
        // Save event and repetitions
721 21
        $event->save();
722 21
        $this->saveEventRepetitions($request, $event->id);
723
724
        // Update multi relationships with teachers and organizers tables.
725 21
        if ($request->get('multiple_teachers')) {
726 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
727 2
            $event->teachers()->sync($multiple_teachers);
728
        } else {
729 19
            $event->teachers()->sync([]);
730
        }
731 21
        if ($request->get('multiple_organizers')) {
732
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
733
            $event->organizers()->sync($multiple_organizers);
734
        } else {
735 21
            $event->organizers()->sync([]);
736
        }
737 21
    }
738
739
    /***********************************************************************/
740
741
    /**
742
     * Get creator email.
743
     *
744
     * @param  int $created_by
745
     * @return \Illuminate\Foundation\Auth\User
746
     */
747
    public function getCreatorEmail(int $created_by)
748
    {
749
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
750
                ->select('email')
751
                ->where('id', $created_by)
752
                ->first();
753
754
        $ret = $creatorEmail->email;
755
756
        return $ret;
757
    }
758
759
    /***************************************************************************/
760
761
    /**
762
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
763
     *
764
     * @param  string  $slug
765
     * @return \Illuminate\Http\Response
766
     */
767 1
    public function eventBySlug(string $slug)
768
    {
769 1
        $event = Event::where('slug', $slug)->first();
770 1
        $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
771
772 1
        return $this->show($event, $firstRpDates);
773
    }
774
775
    /***************************************************************************/
776
777
    /**
778
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
779
     * @param  string $slug
780
     * @param  int $repetitionId
781
     * @return \Illuminate\Http\Response
782
     */
783 4
    public function eventBySlugAndRepetition(string $slug, int $repetitionId)
784
    {
785 4
        $event = Event::where('slug', $slug)->first();
786 4
        $firstRpDates = EventRepetition::getFirstEventRpDatesByRepetitionId($repetitionId);
787
788
        // If not found get the first repetion of the event in the future.
789 4
        if (empty($firstRpDates)) {
790 1
            $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
791
        }
792
793 4
        return $this->show($event, $firstRpDates);
794
    }
795
796
    /***************************************************************************/
797
798
    /**
799
     * Return the Event validator with all the defined constraint.
800
     * @param  \Illuminate\Http\Request  $request
801
     * @return \Illuminate\Http\Response
802
     */
803 22
    public function eventsValidator(Request $request)
804
    {
805
        $rules = [
806 22
            'title' => 'required',
807 22
            'description' => 'required',
808 22
            'category_id' => 'required',
809 22
            'venue_id' => 'required',
810 22
            'startDate' => 'required',
811 22
            'endDate' => 'required',
812 22
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
813 22
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
814 22
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
815 22
            'contact_email' => 'nullable|email',
816 22
            'facebook_event_link' => 'nullable|url',
817 22
            'website_event_link' => 'nullable|url',
818
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
819
        ];
820 22
        if ($request->hasFile('image')) {
821
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
822
        }
823
824
        $messages = [
825 22
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
826
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
827
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
828
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
829
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
830
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
831
        ];
832
833 22
        $validator = Validator::make($request->all(), $rules, $messages);
834
835
        // End date and start date must match if the event is repetitive
836
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
837 22
            return $input->repeat_type > 1;
838 22
        });
839
840 22
        return $validator;
841
    }
842
}
843