Passed
Push — master ( 957fad...041cd5 )
by Davide
24:56
created

EventController::mailToOrganizer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 10
c 1
b 0
f 1
dl 0
loc 22
ccs 0
cts 11
cp 0
rs 9.9332
cc 1
nc 1
nop 1
crap 2
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 4
    public function show(Event $event, EventRepetition $firstRpDates)
161
    {
162
        //dd($firstRpDates);
163 4
        $category = EventCategory::find($event->category_id);
164 4
        $teachers = $event->teachers()->get();
165 4
        $organizers = $event->organizers()->get();
166
167 4
        $venue = DB::table('event_venues')
168 4
                ->select('id', 'name', 'city', 'address', 'zip_code', 'country_id', 'region_id', 'description', 'website', 'extra_info')
169 4
                ->where('id', $event->venue_id)
170 4
                ->first();
171
172 4
        $country = Country::find($venue->country_id);
173 4
        $region = Region::listsTranslations('name')->find($venue->region_id);
174
175 4
        $continent = Continent::find($country->continent_id);
176
177
        // Repetition text to show
178 4
        switch ($event->repeat_type) {
179 4
                case '1': // noRepeat
180 2
                    $repetition_text = null;
181 2
                    break;
182 2
                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 1
                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
                case '4': //repeatMultipleDays
208
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
209
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
210
211
                    // Sort the datas
212
                       usort($singleDaysRepeatDatas, function ($a, $b) {
213
                           $a = Carbon::createFromFormat('d/m/Y', $a);
214
                           $b = Carbon::createFromFormat('d/m/Y', $b);
215
216
                           return strtotime($a) - strtotime($b);
217
                       });
218
219
                    //$repetition_text = 'The event happens on this dates: ';
220
                    $repetition_text = __('laravel-events-calendar::event.the_event_happens_on_this_dates');
221
222
                    $repetition_text .= $dateStart.', ';
223
                    $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
                    break;
226
            }
227
228
        // True if the repetition start and end on the same day
229 4
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
230
231 4
        return view('laravel-events-calendar::events.show', compact('event'))
232 4
                ->with('category', $category)
233 4
                ->with('teachers', $teachers)
234 4
                ->with('organizers', $organizers)
235 4
                ->with('venue', $venue)
236 4
                ->with('country', $country)
237 4
                ->with('region', $region)
238 4
                ->with('continent', $continent)
239 4
                ->with('datesTimes', $firstRpDates)
240 4
                ->with('repetition_text', $repetition_text)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $repetition_text does not seem to be defined for all execution paths leading up to this point.
Loading history...
241 4
                ->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 1
            $teachersDatas = $event->teachers;
282 1
            $teachersSelected = [];
283 1
            foreach ($teachersDatas as $teacherDatas) {
284
                array_push($teachersSelected, $teacherDatas->id);
285
            }
286 1
            $multiple_teachers = implode(',', $teachersSelected);
287
288
            // GET Multiple Organizers
289 1
            $organizersDatas = $event->organizers;
290 1
            $organizersSelected = [];
291 1
            foreach ($organizersDatas as $organizerDatas) {
292
                array_push($organizersSelected, $organizerDatas->id);
293
            }
294 1
            $multiple_organizers = implode(',', $organizersSelected);
295
296 1
            return view('laravel-events-calendar::events.edit', compact('event'))
297 1
                        ->with('eventCategories', $eventCategories)
298 1
                        ->with('users', $users)
299 1
                        ->with('teachers', $teachers)
300 1
                        ->with('multiple_teachers', $multiple_teachers)
301 1
                        ->with('organizers', $organizers)
302 1
                        ->with('multiple_organizers', $multiple_organizers)
303 1
                        ->with('venues', $venues)
304 1
                        ->with('dateTime', $dateTime)
305 1
                        ->with('authorUserId', $authorUserId);
306
        } else {
307
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
308
        }
309
    }
310
311
    /***************************************************************************/
312
313
    /**
314
     * Update the specified resource in storage.
315
     *
316
     * @param  \Illuminate\Http\Request  $request
317
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
318
     * @return \Illuminate\Http\Response
319
     */
320 2
    public function update(Request $request, Event $event)
321
    {
322
        // Validate form datas
323 2
        $validator = $this->eventsValidator($request);
324 2
        if ($validator->fails()) {
325 1
            return back()->withErrors($validator)->withInput();
326
        }
327
328 1
        $this->saveOnDb($request, $event);
329
330 1
        return redirect()->route('events.index')
331 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
332
    }
333
334
    /***************************************************************************/
335
336
    /**
337
     * Remove the specified resource from storage.
338
     *
339
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
340
     * @return \Illuminate\Http\Response
341
     */
342 1
    public function destroy(Event $event)
343
    {
344 1
        DB::table('event_repetitions')
345 1
                ->where('event_id', $event->id)
346 1
                ->delete();
347
348 1
        $event->delete();
349
350 1
        return redirect()->route('events.index')
351 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
352
    }
353
354
    /***************************************************************************/
355
356
    /**
357
     * To save event repetitions for create and update methods.
358
     *
359
     * @param  \Illuminate\Http\Request  $request
360
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
361
     * @return void
362
     */
363 21
    public function saveEventRepetitions(Request $request, Event $event)
364
    {
365 21
        Event::deletePreviousRepetitions($event->id);
366
367
        // Saving repetitions - If it's a single event will be stored with just one repetition
368
        //$timeStart = date('H:i:s', strtotime($request->get('time_start')));
369
        //$timeEnd = date('H:i:s', strtotime($request->get('time_end')));
370
        //$timeStart = $request->get('time_start');
371
        //$timeEnd = $request->get('time_end');
372 21
        $timeStart = date('H:i', strtotime($request->get('time_start')));
373 21
        $timeEnd = date('H:i', strtotime($request->get('time_end')));
374
375 21
        switch ($request->get('repeat_type')) {
376 21
                case '1':  // noRepeat
377 14
                    $eventRepetition = new EventRepetition();
378 14
                    $eventRepetition->event_id = $event->id;
379
380 14
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
381 14
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
382
383 14
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
384 14
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
385 14
                    $eventRepetition->save();
386
387 14
                    break;
388
389 7
                case '2':   // repeatWeekly
390
                    // Convert the start date in a format that can be used for strtotime
391 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
392
393
                    // Calculate repeat until day
394 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
395 2
                        EventRepetition::saveWeeklyRepeatDates($event->id, $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

395
                        EventRepetition::saveWeeklyRepeatDates($event->id, /** @scrutinizer ignore-type */ $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
Loading history...
396
397 2
                    break;
398
399 5
                case '3':  //repeatMonthly
400
                    // Same of repeatWeekly
401 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
402 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
403
404
                    // Get the array with month repeat details
405 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
406
                        //dump("pp_1");
407 5
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
408
409 5
                    break;
410
411
                case '4':  //repeatMultipleDays
412
                    // Same of repeatWeekly
413
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
414
415
                    // Get the array with single day repeat details
416
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
417
418
                        $this->saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
$event->id of type integer is incompatible with the type DavideCasiraghi\LaravelEventsCalendar\Models\Event expected by parameter $event of DavideCasiraghi\LaravelE...veMultipleRepeatDates(). ( Ignorable by Annotation )

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

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

618
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
619
620 1
        array_push($monthlySelectOptions, [
621 1
            'value' => '0|'.$dayNumber,
622 1
            'text' => $repeatText,
623
        ]);
624
625
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
626 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
627 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

627
            /** @scrutinizer ignore-call */ 
628
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
628
629 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfTheMonth).'_x_of_the_month');
630 1
        $repeatText = sprintf($format, $dayOfWeekString);
631
632 1
        array_push($monthlySelectOptions, [
633 1
            'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
634 1
            'text' => $repeatText,
635
        ]);
636
637
        // 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)
638 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

638
            /** @scrutinizer ignore-call */ 
639
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
639
640 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($dayOfMonthFromTheEnd + 1).'_to_last_x_of_the_month');
641 1
        $repeatText = sprintf($format, 'day');
642
643 1
        array_push($monthlySelectOptions, [
644 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
645 1
            'text' => $repeatText,
646
        ]);
647
648
        // 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)
649 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

649
            /** @scrutinizer ignore-call */ 
650
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
650
651 1
            if ($weekOfMonthFromTheEnd == 1) {
652
                $weekValue = 0;
653
            } else {
654 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
655
            }
656
657 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
658 1
        $repeatText = sprintf($format, $dayOfWeekString);
659
660 1
        array_push($monthlySelectOptions, [
661 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
662 1
            'text' => $repeatText,
663
        ]);
664
665
        // GENERATE the HTML to return
666 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
667 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

667
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='"./** @scrutinizer ignore-type */ $selectTitle."'>";
Loading history...
668 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
669 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
670
        }
671 1
        $onMonthlyKindSelect .= '</select>';
672
673 1
        return $onMonthlyKindSelect;
674
    }
675
676
    // **********************************************************************
677
678
    /**
679
     * Save/Update the record on DB.
680
     *
681
     * @param  \Illuminate\Http\Request $request
682
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
683
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
684
     */
685 21
    public function saveOnDb(Request $request, Event $event)
686
    {
687
        //$countries = Country::getCountries();
688 21
        $teachers = Teacher::pluck('name', 'id');
689
690
        /*$venue = DB::table('event_venues')
691
                ->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')
692
                ->where('event_venues.id', '=', $request->get('venue_id'))
693
                ->first();*/
694
695 21
        $event->title = $request->get('title');
696 21
        $event->description = clean($request->get('description'));
697
698 21
        if ($request->get('created_by')) {
699 21
            $event->created_by = $request->get('created_by');
700
        }
701
702 21
        if (! $event->slug) {
703 21
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
704
        }
705 21
        $event->category_id = $request->get('category_id');
706 21
        $event->venue_id = $request->get('venue_id');
707 21
        $event->image = $request->get('image');
708 21
        $event->contact_email = $request->get('contact_email');
709 21
        $event->website_event_link = $request->get('website_event_link');
710 21
        $event->facebook_event_link = $request->get('facebook_event_link');
711 21
        $event->status = $request->get('status');
712 21
        $event->on_monthly_kind = $request->get('on_monthly_kind');
713 21
        $event->multiple_dates = $request->get('multiple_dates');
714
715
        // Event teaser image upload
716 21
        if ($request->file('image')) {
717
            $imageFile = $request->file('image');
718
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
719
            $imageSubdir = 'events_teaser';
720
            $imageWidth = 968;
721
            $thumbWidth = 310;
722
723
            $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

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