-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEventDB.php
414 lines (389 loc) · 13.9 KB
/
EventDB.php
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
<?php
class EventDB
{
private static $db;
const DB_SORTBYTIME_DESC = 0;
const DB_SORTBYTIME_ASC = 1;
const DB_SORTBYNAME_DESC = 2;
const DB_SORTBYNAME_ASC = 3;
const DB_SORTBYID_DESC = 4;
const DB_SORTBYID_ASC = 5;
private $sortQueries = [
0 => "ORDER BY start_time DESC",
1 => "ORDER BY start_time ASC",
2 => "ORDER BY name DESC",
3 => "ORDER BY name ASC",
4 => "ORDER BY id DESC",
5 => "ORDER BY id ASC",
];
private $sortQuery = 0; // Default sort order is time descending
private $filterSql = [
"category" => null,
"club" => null,
"date" => null
];
private $overwrite = true;
public function __construct()
{
try {
self::$db = new PDO(Config::DB_TYPE . ":host=" . Config::DB_HOST . ";port=" . Config::DB_PORT . ";dbname=" . Config::DB_NAME . ";charset=" . Config::DB_CHARSET, Config::DB_USER, Config::DB_PASS);
self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Database connection error: " . $e->getMessage() . PHP_EOL;
echo "Stack trace:" . $e->getTrace() . PHP_EOL;
}
}
/**
* Get filtered events from database
*
* @return array|bool Filtered event, or FALSE on failure
*/
public function getFilteredEvents()
{
$events = [];
$clubs = [];
$categories = [];
$categoryCount = 0;
$clubCount = 0;
$sql = /** @lang text */
"SELECT * FROM events WHERE ";
if (!is_null($this->filterSql["club"])) {
$clubs = (array)$this->filterSql["club"];
$clubCount = count($clubs);
if ($clubCount > 0) {
$sql .= "(";
$i = 0;
for (; $i < count($clubs) - 1; ++$i) {
$sql .= "fbpageid = :club{$i} OR ";
}
$sql .= "fbpageid = :club{$i}) ";
}
}
if (!is_null($this->filterSql["category"])) {
if (substr(trim($sql), -5) != "WHERE") $sql .= "AND (";
$categories = (array)$this->filterSql["category"];
$categoryCount = count($categories);
if ($categoryCount > 0) {
$i = 0;
for (; $i < count($categories) - 1; ++$i) {
$sql .= "category = :cat{$i} OR ";
}
$sql .= "category = :cat{$i}) ";
}
}
if (!is_null($this->filterSql["date"])) {
if (substr(trim($sql), -5) != "WHERE") $sql .= "AND ";
$dateStart = $this->filterSql["date"]["start"];
if (empty($dateStart)) $dateStart = date("Y-m-d") . " 00:00:01";
else if (strpos(" ", $dateStart) === false) { // doesn't include h:m:s precision
$dateStart .= " 00:00:01";
}
$dateEnd = $this->filterSql["date"]["end"];
if (empty($dateEnd)) $dateEnd = "2100-12-30 23:59:59";
else if (strpos(" ", $dateEnd) === false) { // doesn't include h:m:s precision
$dateEnd .= " 23:59:59";
}
$sql .= "(start_time BETWEEN :date AND :date2) ";
}
$sql .= $this->sortQueries[$this->sortQuery];
$query = self::$db->prepare($sql);
for ($i = 0; $i < $clubCount; $i++) {
$query->bindValue(":club{$i}", $clubs[$i]);
}
for ($i = 0; $i < $categoryCount; $i++) {
$query->bindValue(":cat{$i}", $categories[$i]);
}
if (isset($dateStart) && isset($dateEnd)) {
$query->bindValue(":date", $dateStart);
$query->bindValue(":date2", $dateEnd);
}
if ($query->execute() === false) return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* Filter events by club, used for getFilteredEvents method
*
* @param String $clubName Club name
*/
public function filterByClub($clubName)
{
$this->filterSql["club"] = $clubName;
}
/**
* Filter events by date, used for getFilteredEvents method
*
* @param String $start Start date
* @param String|null $end End date
*/
public function filterByDate(String $start = null, String $end = null)
{
$this->filterSql["date"]["start"] = !is_null($start) ? trim($start) : null;
$this->filterSql["date"]["end"] = !is_null($end) ? trim($end) : null;
}
/**
* Filter events by category, used for getFilteredEvents method
*
* @param String $category Category name
*/
public function filterByCategory(String $category)
{
$this->filterSql["category"] = $category;
}
/**
* Clear applied filters, used for getFilteredEvents method
*
*/
public function clearFilters()
{
$this->filterSql = [
"category" => null,
"club" => null,
"date" => null
];
}
/**
* Get club facebook page ids and page names from database
*
* @return array Facebook page id => page name key-val paired array of clubs
*/
public function getClubs()
{
$query = self::$db->query("SELECT fbpageid,fbpagename FROM pages");
return $query->fetchAll(PDO::FETCH_NUM);
}
/**
* Get category names from database
*
* @return array Category names
*/
public function getCategories()
{
$query = self::$db->query("SELECT name FROM categories");
return $query->fetchAll(PDO::FETCH_COLUMN);
}
/**
* Get events by date
*
* @param String $dateStart
* @param String|null $dateEnd If set, function returns events in $dateStart an $dateEnd interval
* @return array|bool
*/
public function getEventsByDate(String $dateStart, String $dateEnd = null)
{
$query = self::$db->prepare("SELECT * FROM events WHERE start_time BETWEEN :date AND :date2 {$this->sortQueries[$this->sortQuery]}");
$query->bindValue(":date", $dateStart);
if (is_null($dateEnd)) $dateEnd = "2100-12-30 23:59:59";
else if (strpos(" ", $dateEnd) === false) { // doesn't include h:m:s precision
$dateEnd .= " 23:59:59";
}
$query->bindValue(":date2", $dateEnd);
if ($query->execute() === false) return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* Get events by club name (actually, facebook page ID/name)
*
* @param string $club Facebook page ID/name
* @return array|false Events, or FALSE on failure
*/
public function getEventsByClub(String $club)
{
$query = self::$db->prepare("SELECT * FROM events WHERE fbpageid = :club {$this->sortQueries[$this->sortQuery]}");
if ($query->execute([
":club" => $club
]) === false
)
return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* Get events by category
*
* @param String $category
* @return array|false Events, or FALSE on failure
*/
public function getEventsByCategory(String $category)
{
$query = self::$db->prepare("SELECT * FROM events WHERE category = :cat {$this->sortQueries[$this->sortQuery]}");
if ($query->execute([
":cat" => $category
]) === false
)
return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* Save a single event to database
*
* @param string $pageName Facebook page ID/name
* @param Event $event Event data
* @return boolean TRUE on success, FALSE on failure
*/
public function saveEvent(string $pageName, Event $event)
{
if ($this->getEvent($event->getId()) !== false) {
if ($this->overwrite) {
$query = self::$db->prepare("UPDATE events SET fbpageid = :pageName, name = :name, description = :description, start_time = :start_time, end_time = :end_time, place = :place, owner = :owner, category = :category, cover = :cover, attending_count = :attending_count, ticket_uri = :ticket_uri, timezone = :timezone WHERE id = :id");
} else {
return false;
}
} else {
$query = self::$db->prepare("INSERT INTO events (fbpageid,id,name,description,start_time,end_time,place,owner,category,cover,attending_count,ticket_uri,timezone) VALUES (:pageName,:id,:name,:description,:start_time,:end_time,:place,:owner,:category,:cover,:attending_count,:ticket_uri,:timezone)");
}
try {
$res = $query->execute([
":pageName" => $pageName,
":id" => $event->getId(),
":name" => $event->getName(),
":description" => $event->getDescription(),
":start_time" => $event->getStartTime(),
":end_time" => $event->getEndTime(),
":place" => serialize($event->getPlace()),
":owner" => $event->getOwner(),
":category" => "",
":cover" => serialize($event->getCover()),
":attending_count" => (int)$event->getAttendingCount(),
":ticket_uri" => $event->getTicketUri(),
":timezone" => $event->getTimezone()
]);
} catch (PDOException $e) {
echo "Error on database query while saving the event: " . $e->getMessage() . PHP_EOL;
echo "Stack trace: " . json_encode($e->getTrace(), JSON_PRETTY_PRINT) . PHP_EOL;
}
return (isset($res) && $res === true) ? true : false;
}
/**
* Save events to database in bulk
*
* @param array $events Key value pairs must be "pagename" => Event
* @return null
*/
public function saveEvents(array $events)
{
if (empty($events)) return null;
foreach ($events as $pageName => $pageEvents) {
foreach ($pageEvents as $event)
$this->saveEvent($pageName, $event);
}
}
/**
* Get a single event data by its id
*
* @param string $eventID Facebook event id
* @return array|false Event data, or FALSE on failure
*/
public function getEvent($eventID)
{
$query = self::$db->prepare("SELECT * FROM events WHERE id = :id");
if ($query->execute([":id" => $eventID]) === false) return false;
return $query->fetch();
}
/**
* Get all events from database
*
* @return array|false Events, or FALSE on failure
*/
public function getAllEvents()
{
$query = self::$db->prepare("SELECT * FROM events {$this->sortQueries[$this->sortQuery]}");
if ($query->execute() === false) return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* @param int $start
* @param int $count
* @return array|bool
*/
public function getEvents(int $start, int $count)
{
$query = self::$db->prepare("SELECT * FROM events {$this->sortQueries[$this->sortQuery]} LIMIT :start,:count");
$query->bindValue(":start", $start, PDO::PARAM_INT);
$query->bindValue(":count", $count, PDO::PARAM_INT);
if ($query->execute() === false) return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* Delete an event from database
*
* @param string $eventID Facebook event id
* @return boolean TRUE on success, FALSE on failure
*/
public function deleteEvent($eventID)
{
if ($this->getEvent($eventID) === false) return false;
$query = self::$db->prepare("DELETE FROM events WHERE id = :id");
return $query->execute([":id" => $eventID]);
}
/**
* Get total event count from database
*
* @return int Total event count, or -1 on FAILURE
*/
public function getTotalEventCount()
{
$query = self::$db->prepare("SELECT COUNT(*) FROM events");
if ($query->execute() === false) return -1;
$res = array_values($query->fetch());
if (!empty($res))
return (int)$res[0];
return 0;
}
/**
* Get an event from database with its name
*
* @param String $name Event name, full or part of it, or FALSE on failure
* @return array|false Array of results, or FALSE on failure
*/
public function searchEventByName(String $name)
{
$query = self::$db->prepare("SELECT * FROM events WHERE name LIKE :name {$this->sortQueries[$this->sortQuery]}");
$query->bindValue(":name", "%{$name}%");
if ($query->execute() === false) return false;
return $this->unserializeArray($query->fetchAll());
}
/**
* Set sort order on database queries, default order is time descending
*
* @param int $sortOrder Choose one from constants, ex.: setSortOrder(EventDB::DB_SORTBYTIME_ASC);
*/
public function setSortOrder(int $sortOrder)
{
if (array_key_exists($sortOrder, $this->sortQueries))
$this->sortQuery = $sortOrder;
}
/**
* Unserialize every possible element on an array
*
* @param array $a
* @return array
*/
private function unserializeArray(array $a)
{
foreach ($a as $i => &$el) {
if (is_array($el)) $el = $this->unserializeArray($el);
else if ($this->isSerial($el)) {
$a[$i] = unserialize($el);
}
}
return $a;
}
/**
* Check if a string is serialized
*
* @param string $string
* @return bool
*/
public function isSerial($string)
{
return (@unserialize($string) !== false);
}
/**
* @param bool $overwrite If true, save methods update existing event data on the database
*
*/
public function setOverwrite(boolean $overwrite)
{
$this->overwrite = $overwrite;
}
}