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
|
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Booking extends CI_Controller { private function getClient() { $client = new Google_Client(); $client->setApplicationName('Google Calendar API PHP Quickstart'); $client->setScopes(Google_Service_Calendar::CALENDAR_EVENTS); $client->setAuthConfig(FCPATH . 'credentials.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists. // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. $tokenPath = FCPATH . 'token2.json';
if (file_exists($tokenPath)) { $accessToken = json_decode(file_get_contents($tokenPath), TRUE); $client->setAccessToken($accessToken); }
// If there is no previous token or it's expired. if ($client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("Open the following link in your browser:\n%s\n", $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $client->setAccessToken($accessToken);
// Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } } // Save the token to a file. if ( ! file_exists(dirname($tokenPath))) { mkdir(dirname($tokenPath), 0700, TRUE); } file_put_contents($tokenPath, json_encode($client->getAccessToken())); } return $client; }
public function index() { $rows = Booking_model::whereDeleted(0)->get(); $this->load->vars(array( 'rows' => $rows, ));
$this->load->view('main/booking_list'); }
public function booking_conflict() { $rows = Booking_conflict_model::has('Booking')->whereDeleted(0)->get(); $this->load->vars('rows', $rows);
$this->load->view('main/booking_conflict_list'); }
public function booking_form($id = NULL) { if ($id) { $this->load->vars('id', $id); $this->load->vars('row', Booking_model::find($id)); }
$this->load->view('main/booking_form');
}
public function booking_submit() {
if ( ! empty($this->input->post())) { $id = $this->input->post('id', 1); $title = $this->input->post('title', 1); $datefm = $this->input->post('datefm', 1); $dateto = $this->input->post('dateto', 1); $location = $this->input->post('location', 1);
$db_datefm = date('Y-m-d H:i:s', strtotime($datefm)); $db_dateto = date('Y-m-d H:i:s', strtotime($dateto));
$g_datefm = date('c', strtotime($datefm)); $g_dateto = date('c', strtotime($dateto));
//check booking from database $query = Booking_model::where('datefm', '<=', $db_dateto) ->where('dateto', '>', $db_datefm) ->where('location', $location); if ($id) { $query->where('id', '!=', $id); } $count_duplicated = $query->count(); if ($count_duplicated > 0) { if ($id) { redirect(front_url(current_controller('/booking_form/' . $id . '?error=1'))); } else { redirect(front_url(current_controller('/booking_form?error=1'))); } exit; }
// Get the API client and construct the service object. $client = $this->getClient(); $service = new Google_Service_Calendar($client);
$calendarId = 'brunkkghkaced4h0sbjblpef0c@group.calendar.google.com';
$optParams = array( 'maxResults' => 1, 'orderBy' => 'startTime', 'singleEvents' => TRUE, 'timeMin' => date('c', strtotime($datefm)), 'q' => $location );
$results = $service->events->listEvents($calendarId, $optParams); $events = $results->getItems();
if ($id) { $booking = Booking_model::find($id); }
foreach ($events as $event) { //check booking from google calendar if ($event->start->dateTime && $event->end->dateTime) { if (strtotime($event->start->dateTime) <= strtotime($dateto) && strtotime($event->end->dateTime) > strtotime($datefm) && $location == $event->getLocation()) { if ( ! empty($booking)) { if ($booking->google_event_id == $event->getId()) continue; } if ($id) { redirect(front_url(current_controller('/booking_form/' . $id . '?error=2'))); } else { redirect(front_url(current_controller('/booking_form?error=2'))); } exit; } } }
if ( ! $id) { $event = new Google_Service_Calendar_Event(array( 'summary' => $title, 'location' => $location, // 'description' => 'Demo', 'start' => array( 'dateTime' => date('c', strtotime($datefm)), 'timeZone' => 'Asia/Hong_Kong', ), 'end' => array( 'dateTime' => date('c', strtotime($dateto)), 'timeZone' => 'Asia/Hong_Kong', ), // 'recurrence' => array( // 'RRULE:FREQ=DAILY;COUNT=2' // ), // 'attendees' => array( // array('email' => ''), // ), // 'reminders' => array( // 'useDefault' => FALSE, // 'overrides' => array( // // array('method' => 'email', 'minutes' => 24 * 60), // // array('method' => 'popup', 'minutes' => 10), // ), // ), ));
$new_event = $service->events->insert($calendarId, $event);
Booking_model::create(array( 'google_event_id' => $new_event->getId(), 'title' => $title, 'datefm' => $g_datefm, 'dateto' => $g_dateto, 'location' => $location, ));
redirect(front_url(current_controller('/booking_form?success=1'))); } else { // First retrieve the event from the API. if ($booking->google_event_id) { $event = $service->events->get($calendarId, $booking->google_event_id);
$start = new Google_Service_Calendar_EventDateTime(); $start->setDateTime($g_datefm); $start->setTimeZone('Asia/Hong_Kong');
$end = new Google_Service_Calendar_EventDateTime(); $end->setDateTime($g_dateto); $end->setTimeZone('Asia/Hong_Kong');
$event->setSummary($title); $event->setStart($start); $event->setEnd($end); $event->setLocation($location);
$updatedEvent = $service->events->update($calendarId, $event->getId(), $event);
// Print the updated date. // echo $updatedEvent->getUpdated(); } $booking->title = $title; $booking->datefm = $db_datefm; $booking->dateto = $db_dateto; $booking->location = $location; $booking->save();
// redirect(front_url(current_controller('/booking_form/' . $id . '?success=1'))); redirect(front_url(current_controller('?success=1'))); }
} }
public function booking_delete($id) { $booking = Booking_model::find($id); if ($booking->id) { if ($booking->google_event_id) { // Get the API client and construct the service object. $client = $this->getClient(); $service = new Google_Service_Calendar($client);
$calendarId = 'brunkkghkaced4h0sbjblpef0c@group.calendar.google.com';
// First retrieve the event from the API. $event = $service->events->get($calendarId, $booking->google_event_id);
$event->setSummary('[Deleted at ' . date('Y-m-d H:i') . ' by CS] ' . $event->getSummary()); $event->setColorId(4); //1 blue // 2 green // 3 purple // 4 red // 5 yellow // 6 orange // 7 turquoise // 8 gray // 9 bold blue // 10 bold green // 11 bold red
$updatedEvent = $service->events->update($calendarId, $event->getId(), $event); } $booking->delete()->save();
redirect(front_url(current_controller('?deleted=1'))); }
}
public function booking_sync() {
// Get the API client and construct the service object. $client = $this->getClient(); $service = new Google_Service_Calendar($client);
//Synchronize from google to database $calendarId = 'brunkkghkaced4h0sbjblpef0c@group.calendar.google.com';
$events = $service->events->listEvents($calendarId);
$events_id = array();
$count_sync = 0;
while (TRUE) { foreach ($events->getItems() as $event) { $google_event_id = $event->getId(); $title = $event->getSummary(); $datefm = date('Y-m-d H:i:s', strtotime($event->start->dateTime)); $dateto = date('Y-m-d H:i:s', strtotime($event->end->dateTime)); $location = $event->getLocation();
//skip deleted $colorId = $event->getColorId(); if ($colorId == 4) continue;
// if booking not found in database $row = Booking_model::where('google_event_id', $google_event_id)->first(); if ($row->id) { //compare data if ($row->title <> $title || $row->datefm <> $datefm || $row->dateto <> $dateto || $row->location <> $location) {
Booking_conflict_model::firstOrCreate(array( 'google_event_id' => $google_event_id ))->update(array( 'booking_id' => $row->id, 'title' => $row->title, 'datefm' => $row->datefm, 'dateto' => $row->dateto, 'location' => $row->location, 'gTitle' => $title, 'gDatefm' => $datefm, 'gDateto' => $dateto, 'gLocation' => $location, ));
ob_start(); echo 'This booking had different between google calendar and database<br><b>Google Calendar:</b><br>'; echo 'Title: ' . $title . '<br>'; echo 'Start Date: ' . $datefm . '<br>'; echo 'End Date: ' . $dateto . '<br>'; echo 'Location: ' . $location . '<br>'; echo '<hr><b>Database:</b><br>Title: ' . $row->title . '<br>'; echo 'Start Date: ' . $row->datefm . '<br>'; echo 'End Date: ' . $row->dateto . '<br>'; echo 'Location: ' . $row->location . '<br>'; $_SESSION['sync_error'][] = ob_get_clean();
}
} else { Booking_model::create(array( 'google_event_id' => $google_event_id, 'title' => $title, 'datefm' => $datefm, 'dateto' => $dateto, 'location' => $location )); $count_sync++; }
array_push($events_id, $google_event_id); } $pageToken = $events->getNextPageToken(); if ($pageToken) { $optParams = array('pageToken' => $pageToken); $events = $service->events->listEvents($calendarId, $optParams); } else { break; } }
//sync from database to google calendar $bookings = Booking_model::whereNotIn('google_event_id', $events_id)->get(); foreach ($bookings as $booking) { $event = new Google_Service_Calendar_Event(array( 'summary' => $booking->title, 'location' => $booking->location, // 'description' => 'Demo', 'start' => array( 'dateTime' => date('c', strtotime($booking->datefm)), 'timeZone' => 'Asia/Hong_Kong', ), 'end' => array( 'dateTime' => date('c', strtotime($booking->dateto)), 'timeZone' => 'Asia/Hong_Kong', ), // 'recurrence' => array( // 'RRULE:FREQ=DAILY;COUNT=2' // ), // 'attendees' => array( // array('email' => ''), // ), // 'reminders' => array( // 'useDefault' => FALSE, // 'overrides' => array( // // array('method' => 'email', 'minutes' => 24 * 60), // // array('method' => 'popup', 'minutes' => 10), // ), // ), ));
$new_event = $service->events->insert($calendarId, $event);
$booking->google_event_id = $new_event->getId(); $booking->save(); $count_sync++; }
redirect(front_url(current_controller('?count=' . $count_sync))); }
public function booking_conflict_submit() { $count = 0; $conflicts = $this->input->post('conflict');
foreach ($conflicts as $id => $conflict) { $booking = Booking_conflict_model::find($id); if ($booking->id && $booking->google_event_id) { if ($conflict == 'db') { // Get the API client and construct the service object. $client = $this->getClient(); $service = new Google_Service_Calendar($client);
$calendarId = 'brunkkghkaced4h0sbjblpef0c@group.calendar.google.com';
// First retrieve the event from the API. $event = $service->events->get($calendarId, $booking->google_event_id);
$g_datefm = date('c', strtotime($booking->datefm)); $g_dateto = date('c', strtotime($booking->dateto));
$start = new Google_Service_Calendar_EventDateTime(); $start->setDateTime($g_datefm); $start->setTimeZone('Asia/Hong_Kong');
$end = new Google_Service_Calendar_EventDateTime(); $end->setDateTime($g_dateto); $end->setTimeZone('Asia/Hong_Kong');
$event->setSummary($booking->title); $event->setStart($start); $event->setEnd($end); $event->setLocation($booking->location);
$updatedEvent = $service->events->update($calendarId, $event->getId(), $event);
$count++;
} else if ($conflict == 'google') { Booking_model::firstOrCreate(array( 'google_event_id' => $booking->google_event_id ))->update(array( 'title' => $booking->gTitle, 'datefm' => $booking->gDatefm, 'dateto' => $booking->gDateto, 'location' => $booking->gLocation, ));
$count++; }
$booking->delete()->save(); } }
redirect(front_url(current_controller('?success=1'))); } }
|