forked from TheRestartProject/restarters.net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventController.php
More file actions
765 lines (683 loc) · 27.5 KB
/
EventController.php
File metadata and controls
765 lines (683 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\JsonResponse;
use App\Events\EditEvent;
use App\Models\EventsUsers;
use App\Models\Group;
use App\Helpers\Fixometer;
use App\Helpers\FixometerFile;
use App\Http\Controllers\Controller;
use App\Models\Invite;
use App\Models\Network;
use App\Notifications\AdminModerationEvent;
use App\Models\Role;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;
use Notification;
use App\Notifications\JoinGroup;
use App\Models\Party;
use App\Models\User;
use Auth;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
class EventController extends Controller
{
public function getEventsByUsersNetworks(Request $request, $date_from = null, $date_to = null, $timezone = 'UTC')
{
$authenticatedUser = Auth::user();
set_time_limit(240);
$groups = [];
foreach ($authenticatedUser->networks as $network) {
foreach ($network->groups as $group) {
$groups[] = $group;
}
}
$parties = Party::join('groups', 'groups.idgroups', '=', 'events.group')
->join('group_network', 'group_network.group_id', '=', 'groups.idgroups')
->join('networks', 'networks.id', '=', 'group_network.network_id')
->join('user_network', 'networks.id', '=', 'user_network.network_id')
->join('users', 'users.id', '=', 'user_network.user_id')
->orderBy('event_start_utc', 'ASC');
if (!empty($date_from) && !empty($date_to)) {
$start = Carbon::parse($date_from, $timezone);
$startCopy = $start->copy()->setTimezone('UTC');
$end = Carbon::parse($date_to, $timezone);
$endCopy = $end->copy()->setTimezone('UTC');
$parties = $parties->where('events.event_start_utc', '>=', $startCopy->toIso8601String())
->where('events.event_end_utc', '<=', $endCopy->toIso8601String());
}
$parties = $parties->where([
['users.api_token', $authenticatedUser->api_token],
])
->select('events.*')
->get();
// If no parties are found, through 404 error
if (empty($parties)) {
return abort(404, 'No Events found.');
}
$groups_array = collect([]);
foreach ($groups as $group) {
$groupStats = $group->getGroupStats();
$groups_array->push([
'id' => $group->idgroups,
'name' => $group->name,
'area' => $group->area,
'timezone' => $group->timezone,
'postcode' => $group->postcode,
'description' => $group->free_text,
'image_url' => $group->groupImagePath(),
'volunteers' => $group->volunteers,
'participants' => $groupStats['participants'],
'hours_volunteered' => $groupStats['hours_volunteered'],
'parties_thrown' => $groupStats['parties'],
'waste_prevented' => $groupStats['waste_total'],
'co2_emissions_prevented' => $groupStats['co2_total'],
]);
}
$collection = collect([]);
// Send these to getEventStats() to speed things up a bit.
$eEmissionRatio = \App\Helpers\LcaStats::getEmissionRatioPowered();
$uEmissionratio = \App\Helpers\LcaStats::getEmissionRatioUnpowered();
foreach ($parties as $key => $party) {
$group = $groups_array->filter(function ($group) use ($party) {
return $group['id'] == $party->group;
})->first();
$eventStats = $party->getEventStats($eEmissionRatio, $uEmissionratio);
// Push Party to Collection
$collection->push([
'id' => $party->idevents,
'group' => [$group],
'area' => $group['area'],
'postcode' => $group['postcode'],
'timezone' => $party->timezone,
'event_date' => $party->event_date_local,
'start_time' => $party->start_local,
'end_time' => $party->end_local,
'name' => $party->venue,
'link' => $party->link,
'online' => $party->online,
'location' => [
'value' => $party->location,
'latitude' => $party->latitude,
'longitude' => $party->longitude,
'area' => $group['area'],
'postcode' => $group['postcode'],
],
'description' => $party->free_text,
'user' => $party_user = collect(),
'impact' => [
'participants' => $party->pax,
'volunteers' => $eventStats['volunteers'],
'waste_prevented' => $eventStats['waste_powered'],
'co2_emissions_prevented' => $eventStats['co2_powered'],
'devices_fixed' => $eventStats['fixed_devices'],
'devices_repairable' => $eventStats['repairable_devices'],
'devices_dead' => $eventStats['dead_devices'],
],
'widgets' => [
'headline_stats' => url("/party/stats/{$party->idevents}/wide"),
'co2_equivalence_visualisation' => url(
"/outbound/info/party/{$party->idevents}/manufacture"
),
],
'hours_volunteered' => $party->hoursVolunteered(),
'created_at' => Carbon::parse($party->created_at),
'updated_at' => Carbon::parse($party->max_updated_at_devices_updated_at),
]);
if (!empty($party->owner)) {
$party_user->put('id', $party->owner->id);
$party_user->put('name', $party->owner->name);
}
}
return $collection;
}
public function addVolunteer(Request $request, $idevents): JsonResponse
{
$request->validate([
'volunteer_email_address' => ['nullable', 'email'],
]);
$party = Party::findOrFail($idevents);
if (!Fixometer::userHasEditPartyPermission($idevents)) {
abort(403);
}
$volunteer_email_address = $request->input('volunteer_email_address');
// Retrieve name if one exists. If no name exists and user is null as well then this volunteer is anonymous.
if ($request->has('full_name')) {
$full_name = $request->input('full_name');
} else {
$full_name = null;
}
$eventRole = Role::RESTARTER;
if ($request->has('user') && $request->input('user') !== 'not-registered') {
// User is null, this volunteer is either anonymous or no user exists.
$user = $request->input('user');
if ($user) {
$u = User::find($user);
// A host of the group who is added to an event becomes a host of the event.
$eventRole = $u && Fixometer::userIsHostOfGroup($party->group, $user) ? Role::HOST : Role::RESTARTER;
}
} else {
$user = null;
}
// Check if user was invited but not RSVPed.
$invitedUserQuery = EventsUsers::where('event', $idevents)
->where('user', $user)
->where('status', '<>', 1)
->whereNotNull('status')
->where('role', $eventRole);
$userWasInvited = $invitedUserQuery->count() == 1;
if ($userWasInvited) {
$invitedUser = $invitedUserQuery->first();
$invitedUser->status = 1;
$invitedUser->save();
} else {
// Let's add the volunteer.
EventsUsers::create([
'event' => $idevents,
'user' => $user,
'status' => 1,
'role' => $eventRole,
'full_name' => $full_name,
]);
}
if (!is_null($volunteer_email_address)) {
// Send email.
$from = User::find(Auth::user()->id);
$hash = substr(bin2hex(openssl_random_pseudo_bytes(32)), 0, 24);
$url = url('/user/register/'.$hash);
$invite = Invite::create([
'record_id' => $party->theGroup->idgroups,
'email' => $volunteer_email_address,
'hash' => $hash,
'type' => 'group',
]);
Notification::send(
$invite,
new JoinGroup([
'name' => $from->name,
'group' => $party->theGroup->name,
'url' => $url,
'message' => null,
])
);
}
return response()->json([
'success' => 'success'
]);
}
public function listVolunteers(Request $request, $idevents): JsonResponse
{
$party = Party::findOrFail($idevents);
// Get the user that the API has been authenticated as.
$user = auth('api')->user();
// Emails are sensitive.
$showEmails = $user && !Fixometer::userHasEditPartyPermission($idevents, $user->id);
$volunteers = $party->expandVolunteers($party->allConfirmedVolunteers()->get(), $showEmails);
return response()->json([
'success' => 'success',
'volunteers' => $volunteers
]);
}
/**
* @OA\Get(
* path="/api/v2/events/{id}",
* operationId="getEvent",
* tags={"Events"},
* summary="Get Event",
* description="Returns information about an event.",
* @OA\Parameter(
* name="id",
* description="Event id",
* required=true,
* in="path",
* @OA\Schema(
* type="integer"
* )
* ),
* @OA\Response(
* response=200,
* description="Successful operation",
* @OA\JsonContent(
* @OA\Property(
* property="data",
* title="data",
* ref="#/components/schemas/Event"
* )
* )
* ),
* @OA\Response(
* response=404,
* description="Event not found",
* ),
* )
*/
public function getEventv2(Request $request, $idevents)
{
$party = Party::findOrFail($idevents);
return \App\Http\Resources\Party::make($party);
}
private function getUser()
{
// We want to allow this call to work if a) we are logged in as a user, or b) we have a valid API token.
//
// This is a slightly odd thing to do, but it is necessary to get both the PHPUnit tests and the
// real client use of the API to work.
$user = Auth::user();
if (!$user) {
$user = auth('api')->user();
}
if (!$user) {
throw new AuthenticationException();
}
return $user;
}
/**
* @OA\Get(
* path="/api/v2/moderate/events",
* operationId="getEventsModeratev2",
* tags={"Events"},
* summary="Get Events for Moderation",
* description="Only available for Administrators and Network Coordinators.",
* @OA\Parameter(
* name="api_token",
* description="A valid user API token",
* required=true,
* in="query",
* @OA\Schema(
* type="string",
* example="1234"
* )
* ),
* @OA\Response(
* response=200,
* description="Successful operation",
* @OA\JsonContent(
* type="array",
* description="An array of groups",
* @OA\Items(
* ref="#/components/schemas/Event"
* )
* )
* ),
* )
*/
public function moderateEventsv2(Request $request)
{
// Get the user that the API has been authenticated as.
$user = $this->getUser();
$ret = [];
$networks = [];
if ($user->hasRole('Administrator')) {
$networks = Network::all();
} else {
if ($user->hasRole('NetworkCoordinator')) {
$networks = $user->networks;
}
}
$events = [];
foreach ($networks as $network) {
$events = array_merge($events, $network->eventsRequiringModeration());
}
usort($events, function ($a, $b) {
return strtotime($a->event_start_utc) - strtotime($b->event_start_utc);
});
$ret = \App\Http\Resources\Party::collection(collect($events));
return response()->json($ret);
}
/**
* @OA\Post(
* path="/api/v2/events",
* operationId="createEvent",
* tags={"Events"},
* summary="Create Event",
* description="Creates an event.",
* @OA\Parameter(
* name="api_token",
* description="A valid user API token",
* required=true,
* in="query",
* @OA\Schema(
* type="string",
* example="1234"
* )
* ),
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"start","end","title","description","location","lat","lng"},
* @OA\Property(
* property="groupid",
* title="id",
* description="Unique identifier of the group to which the event belongs",
* format="int64",
* example=1
* ),
* @OA\Property(
* property="start",
* ref="#/components/schemas/Event/properties/start",
* ),
* @OA\Property(
* property="end",
* ref="#/components/schemas/Event/properties/start",
* ),
* @OA\Property(
* property="timezone",
* ref="#/components/schemas/Event/properties/timezone",
* ),
* @OA\Property(
* property="title",
* ref="#/components/schemas/Event/properties/title",
* ),
* @OA\Property(
* property="description",
* ref="#/components/schemas/Event/properties/description",
* ),
* @OA\Property(
* property="location",
* ref="#/components/schemas/Event/properties/location",
* ),
* @OA\Property(
* property="online",
* ref="#/components/schemas/Event/properties/online",
* ),
* @OA\Property(
* property="link",
* ref="#/components/schemas/Event/properties/link",
* ),
* @OA\Property(
* description="Network-defined JSON data",
* property="network_data",
* @OA\Schema()
* ),
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Successful operation",
* @OA\JsonContent(
* @OA\Property(
* property="data",
* title="data",
* ref="#/components/schemas/Event"
* )
* ),
* )
* )
*/
public function createEventv2(Request $request): JsonResponse
{
$user = $this->getUser();
list($groupid, $start, $end, $title, $description, $location, $timezone, $latitude, $longitude, $online, $link, $network_data) = $this->validateEventParams(
$request,
true
);
$group = Group::findOrFail($groupid);
// Check whether the event should be auto-approved, if all of the networks it belongs to
// allow it.
$autoapprove = $group->auto_approve;
if (!Fixometer::userCanCreateEvents($user)) {
// TODO: This doesn't check that they are a host of this particular group.
abort(403);
}
// Convert the timezone to UTC, because the timezone is not itself stored in the DB.
$eventStart = Carbon::parse($start);
$eventEnd = Carbon::parse($end);
$event_start_utc = $eventStart->copy()->setTimezone('UTC')->toIso8601String();
$event_end_utc = $eventEnd->copy()->setTimezone('UTC')->toIso8601String();
$hours = Carbon::parse($event_start_utc)->diffInHours(Carbon::parse($event_end_utc));
// timezone needs to be the first attribute set, because it is used in mutators for later attributes.
$data = [
'timezone' => $timezone,
'event_start_utc' => $event_start_utc,
'event_end_utc' => $event_end_utc,
'free_text' => $description,
'link' => $link,
'venue' => $title,
'location' => $location,
'latitude' => $latitude,
'longitude' => $longitude,
'group' => $groupid,
'hours' => $hours,
'user_id' => $user->id,
'created_at' => date('Y-m-d H:i:s'),
'shareable_code' => Fixometer::generateUniqueShareableCode(\App\Models\Party::class, 'shareable_code'),
'online' => $online,
'network_data' => $network_data,
];
$party = Party::create($data);
$idParty = $party->idevents;
EventsUsers::create([
'event' => $idParty,
'user' => $user->id,
'status' => 1,
'role' => Role::HOST,
]);
// Notify relevant users.
$usersToNotify = Fixometer::usersWhoHavePreference('admin-moderate-event');
foreach ($party->associatedNetworkCoordinators() as $coordinator) {
// If the user is an admin, we allow them to turn off the notification.
// Network coordinators must always receive them, for fear of events languishing unapproved.
// So only add network coordinators who aren't admins, and rely on usersWhoHavePreference to have
// added relevant admins.
if (!$coordinator->hasRole('Administrator')) {
$usersToNotify->push($coordinator);
}
}
Notification::send(
$usersToNotify->unique(),
new AdminModerationEvent([
'event_venue' => $title,
'event_url' => url('/party/edit/'.$idParty),
])
);
if (isset($_FILES) && !empty($_FILES) && is_array($_FILES['file']['name'])) {
$File = new FixometerFile;
$files = Fixometer::rearrange($_FILES['file']);
foreach ($files as $upload) {
$File->upload($upload, 'image', $idParty, env('TBL_EVENTS'));
}
}
// Only auto-approve if the feature is enabled AND the user has privileged role (Root, Admin, Host)
if ($autoapprove && $user->role <= ROLE::HOST) {
Log::info("Auto-approve event $idParty for user {$user->id} (role {$user->role})");
Party::find($idParty)->approve();
}
if (isset($_FILES) && !empty($_FILES)) {
$file = new FixometerFile();
$file->upload('image', 'image', $idParty, env('TBL_EVENTS'), false, true, true);
}
return response()->json([
'id' => $idParty,
]);
}
/**
* @OA\Patch(
* path="/api/v2/events/{id}",
* operationId="editEvent",
* tags={"Events"},
* summary="Edit Event",
* description="Edits an event. The event of a group cannot be changed after creation.",
* @OA\Parameter(
* name="api_token",
* description="A valid user API token",
* required=true,
* in="query",
* @OA\Schema(
* type="string",
* example="1234"
* )
* ),
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"start","end","title","description","location","lat","lng"},
* @OA\Property(
* property="start",
* ref="#/components/schemas/Event/properties/start",
* ),
* @OA\Property(
* property="end",
* ref="#/components/schemas/Event/properties/start",
* ),
* @OA\Property(
* property="timezone",
* ref="#/components/schemas/Event/properties/timezone",
* ),
* @OA\Property(
* property="title",
* ref="#/components/schemas/Event/properties/title",
* ),
* @OA\Property(
* property="description",
* ref="#/components/schemas/Event/properties/description",
* ),
* @OA\Property(
* property="location",
* ref="#/components/schemas/Event/properties/location",
* ),
* @OA\Property(
* property="online",
* ref="#/components/schemas/Event/properties/online",
* ),
* @OA\Property(
* property="link",
* ref="#/components/schemas/Event/properties/link",
* ),
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Successful operation",
* @OA\JsonContent(
* @OA\Property(
* property="data",
* title="data",
* ref="#/components/schemas/Event"
* )
* ),
* )
* )
*/
public function updateEventv2(Request $request, $idEvents): JsonResponse
{
$user = $this->getUser();
list($groupid, $start, $end, $title, $description, $location, $timezone, $latitude, $longitude, $online, $link, $network_data) = $this->validateEventParams(
$request,
false
);
if (!Fixometer::userHasEditPartyPermission($idEvents, $user->id)) {
abort(403);
}
// Convert the timezone to UTC, because the timezone is not itself stored in the DB.
$eventStart = Carbon::parse($start);
$eventEnd = Carbon::parse($end);
$event_start_utc = $eventStart->copy()->setTimezone('UTC')->toIso8601String();
$event_end_utc = $eventEnd->copy()->setTimezone('UTC')->toIso8601String();
$hours = Carbon::parse($event_start_utc)->diffInHours(Carbon::parse($event_end_utc));
// We don't let the user change the group that an event is on.
$update = [
'event_start_utc' => $event_start_utc,
'event_end_utc' => $event_end_utc,
'hours' => $hours,
'free_text' => $description,
'online' => $online,
'venue' => $title,
'link' => $link,
'location' => $location,
'latitude' => $latitude,
'longitude' => $longitude,
'timezone' => $timezone,
'network_data' => $network_data,
];
$party = Party::findOrFail($idEvents);
$party->update($update);
if ($request->has('moderate') && $request->input('moderate') == 'approve' && Fixometer::userCanApproveEvent($idEvents, $user->id)) {
$party->approve();
}
event(new EditEvent($party, $update));
return response()->json([
'id' => $idEvents,
]);
}
private function validateEventParams(Request $request, $create): array
{
// We don't validate max lengths of other strings, to avoid duplicating the length information both here
// and in the migrations. If we wanted to do that we should extract the length dynamically from the
// schema, which is possible but not trivial.
if ($create) {
$request->validate([
'groupid' => 'required|integer',
'start' => ['required', 'date_format:Y-m-d\TH:i:sP,Y-m-d\TH:i:s\Z'],
'end' => ['required', 'date_format:Y-m-d\TH:i:sP,Y-m-d\TH:i:s\Z'],
'title' => ['required', 'max:255'],
'description' => ['required'],
'location' => [
function ($attribute, $value, $fail) use ($request) {
if (!$request->filled('online') && !$value) {
$fail(__('events.validate_location'));
}
},
],
'online' => ['boolean'],
]);
} else {
$request->validate([
'start' => ['required', 'date_format:Y-m-d\TH:i:sP,Y-m-d\TH:i:s\Z'],
'end' => ['required', 'date_format:Y-m-d\TH:i:sP,Y-m-d\TH:i:s\Z'],
'title' => ['required', 'max:255'],
'description' => ['required'],
'location' => [
function ($attribute, $value, $fail) use ($request) {
if (!$request->filled('online') && !$value) {
$fail(__('events.validate_location'));
}
},
],
'online' => ['boolean'],
]);
}
$groupid = $request->input('groupid');
$start = $request->input('start');
$end = $request->input('end');
$title = $request->input('title');
$description = $request->input('description');
$location = $request->input('location');
$timezone = $request->input('timezone');
$online = $request->input('online', false);
$link = $request->input('link', null);
$network_data = $request->input('network_data');
$latitude = null;
$longitude = null;
if ($timezone && !in_array($timezone, \DateTimeZone::listIdentifiers(\DateTimeZone::ALL_WITH_BC))) {
throw ValidationException::withMessages(['location ' => __('partials.validate_timezone')]);
}
if (!empty($location)) {
$geocoder = new \App\Helpers\Geocoder();
$geocoded = $geocoder->geocode($location);
if (empty($geocoded)) {
throw ValidationException::withMessages(['location ' => __('events.geocode_failed')]);
}
$latitude = $geocoded['latitude'];
$longitude = $geocoded['longitude'];
}
return [
$groupid,
$start,
$end,
$title,
$description,
$location,
$timezone,
$latitude,
$longitude,
$online,
$link,
$network_data
];
}
}