| Server IP : 210.245.233.93 / Your IP : 216.73.216.226 Web Server : Apache/2.2.15 (CentOS) System : Linux webserver2.onesolution.com.hk 2.6.32-754.35.1.el6.x86_64 #1 SMP Sat Nov 7 12:42:14 UTC 2020 x86_64 User : apache ( 48) PHP Version : 5.3.3 Disable Function : exec, shell_exec, system, passthru, popen, proc_open, pcntl_exec MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /var/www/hkosl.com/demo_google/application/controllers/ |
Upload File : |
<?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')));
}
}