forked from jfuentesa/gengamification
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.gengamification.php
More file actions
612 lines (469 loc) · 19.5 KB
/
Copy pathclass.gengamification.php
File metadata and controls
612 lines (469 loc) · 19.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
<?php
/**
*
* GenGamification - A generic gamification PHP framework
*
* @author Javier Fuentes <javier.fuentes@redalumnos.com>
* @license http://opensource.org/licenses/MIT MIT License
* @version 1.0
*
*/
/*
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE `t_gengamification_alerts` (
`id_user` int(10) unsigned NOT NULL,
`id_badge` int(10) unsigned DEFAULT NULL,
`id_level` int(10) unsigned DEFAULT NULL,
KEY `id_user` (`id_user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `t_gengamification_badges` (
`id_user` int(10) unsigned NOT NULL,
`id_badge` int(10) unsigned NOT NULL,
`badgescounter` int(10) unsigned NOT NULL,
`grantdate` datetime NOT NULL,
PRIMARY KEY (`id_user`,`id_badge`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `t_gengamification_events` (
`id_user` int(10) unsigned NOT NULL,
`id_event` int(10) unsigned NOT NULL,
`eventcounter` int(10) unsigned NOT NULL,
`pointscounter` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_user`,`id_event`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `t_gengamification_log` (
`id_user` int(10) unsigned NOT NULL,
`id_event` int(10) unsigned DEFAULT NULL,
`eventdate` datetime NOT NULL,
`points` int(10) unsigned DEFAULT NULL,
`id_badge` int(10) unsigned DEFAULT NULL,
`id_level` int(10) unsigned DEFAULT NULL,
KEY `id_user` (`id_user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `t_gengamification_scores` (
`id_user` int(10) unsigned NOT NULL,
`points` int(10) unsigned NOT NULL,
`id_level` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
interface gengamificationDAOint {
public function getUserAlerts($userId, $resetAlerts = false);
public function getUserBadges($userId);
public function getUserEvents($userId);
public function getUserEvent($userId, $eventId);
public function getUserScores($userId);
public function grantBadgeToUser($userId, $badgeId);
public function grantLevelToUser($userId, $levelId);
public function grantPointsToUser($userId, $points);
public function saveBadgeAlert($userId, $badgeId);
public function saveLevelAlert($userId, $levelId);
public function increaseEventCounter($userId, $eventId);
public function increaseEventPoints($userId, $eventId, $points);
public function logUserEvent($userId, $eventId, $points = null, $badgeId = null, $levelId = null);
public function getUserLog($userId);
}
class gengamificationEvent {
private $repetitions = null; /* Counter trigger (1 = unique event / null = triggers every execution) */
private $allowrepetitions = false; /* Allows repetitions */
private $badge = null; /* Badge granted when triggers */
private $descriptor = null; /* Event descriptor */
private $points = null; /* Points granted when triggers */
private $maxpoints = null; /* Max points granted for this event */
private $eachcallback = null; /* Each callback function */
private $eventcallback = null; /* Trigger callback function */
public function allowrepetitions() {
return $this->allowrepetitions;
}
public function getBadge() {
return $this->badge;
}
public function getDescriptor() {
return $this->descriptor;
}
public function getEachCallback()
{
return $this->eachcallback;
}
public function getEventCallback()
{
return $this->eventcallback;
}
public function getMaxpoints() {
return $this->maxpoints;
}
public function getPoints() {
return $this->points;
}
public function getRequiredRepetitions() {
return $this->repetitions;
}
public function setAllowRepetitions($b) {
if (!is_bool($b)) throw new Exception(__METHOD__.': Invalid repetitions');
$this->allowrepetitions = $b;
return $this;
}
public function setBadgeGranted($str) {
$str = trim($str);
if (empty($str)) throw new Exception(__METHOD__.': Invalid badge');
$this->badge = $str;
return $this;
}
public function setDescriptor($str) {
$str = trim($str);
if (empty($str)) throw new Exception(__METHOD__.': Invalid descriptor');
$this->descriptor = $str;
return $this;
}
public function setEachCallback($f) {
if (!is_callable($f)) throw new Exception(__METHOD__.': Invalid callback function');
$this->eachcallback = $f;
return $this;
}
public function setEventCallback($f) {
if (!is_callable($f)) throw new Exception(__METHOD__.': Invalid callback function');
$this->eventcallback = $f;
return $this;
}
public function setMaxPointsGranted($n) {
if (!is_numeric($n)) throw new Exception(__METHOD__.': Invalid points');
$this->maxpoints = $n;
return $this;
}
public function setPointsGranted($n) {
if (!is_numeric($n)) throw new Exception(__METHOD__.': Invalid points');
$this->points = $n;
return $this;
}
public function setRequiredRepetitions($n) {
if (!is_numeric($n)) throw new Exception(__METHOD__.': Invalid repetitions');
$this->repetitions = $n;
return $this;
}
}
class gengamification {
/** @var bool $letsGoParty This stops gamification execution */
private $letsGoParty = true;
/** @var array $events Events definitions */
private $events = array();
/** @var array $badges Badges definitions */
private $badges = array();
/** @var array $levels Levels definitions */
private $levels = array();
// User id
private $userId = null;
// Definitions counters
private $badgesCounter = 0;
private $eventsCounter = 0;
private $levelsCounter = 0;
// Events queue
private $eventsQueue = array();
// Data Access Object (DAO)
/** @var gengamificationDAO $dao */
private $dao = null;
public function __construct($dao) {
$this->dao = $dao;
}
/**
*
* Public functions
*
*/
// Add badge to gamification engine
public function addBadge($internalDescriptor, $descriptor, $description, $imageURL, $event = null) {
if (empty($descriptor) || empty($description)) throw new Exception(__METHOD__.': Invalid parameters');
// Add event to gamification events array
$this->badges[$internalDescriptor] = array(
'id' => ++$this->badgesCounter,
'internal' => $internalDescriptor,
'descriptor' => $descriptor,
'description' => $description,
'imageurl' => $imageURL,
'event' => $event
);
return $this;
}
/**
*
* Add event to gamification engine
*
* @param $event gengamificationEvent
*
* @return bool
* @throws Exception
*
*/
public function addEvent($event) {
if (!is_null($event->getBadge())) {
if (!$this->badgeExists($event->getBadge())) throw new Exception(__METHOD__.': Invalid badge');
}
$i = $event->getDescriptor();
// Add new event/trigger to array events
if (isset($this->events[$i])) {
if ($this->events[$i]['allowrepetitions'] != $event->allowRepetitions()) throw new Exception(__METHOD__.': Allow repetitions not match for the event');
} else {
$this->events[$i] = array(
'id' => ++$this->eventsCounter,
'allowrepetitions' => $event->allowRepetitions(),
'triggers' => array()
);
}
// Add trigger to triggers for this event
$this->events[$i]['triggers'][] = $event;
return $this;
}
private function addEventToQueue($descriptor) {
$this->eventsQueue[] = $descriptor;
}
// Add badge to gamification engine
public function addLevel($pointsThreshold, $descriptor, $eventDescriptor = null) {
$descriptor = trim($descriptor);
if (!is_numeric($pointsThreshold) || empty($descriptor)) throw new Exception(__METHOD__.': Invalid parameters');
// Add event to gamification events array
$this->levels[] = array(
'id' => ++$this->levelsCounter,
'threshold' => $pointsThreshold,
'descriptor' => $descriptor,
'event' => $eventDescriptor
);
return $this;
}
// Save alert for received badges
private function alertBadge($id) {
// Save alert
$this->dao->saveBadgeAlert($this->getUserId(), $id);
return true;
}
// Save alert for level upgrade
private function alertLevel($id) {
// Save alert
$this->dao->saveLevelAlert($this->getUserId(), $id);
return true;
}
private function badgeExists($descriptor) {
if (array_key_exists($descriptor, $this->badges)) return true;
else return false;
}
public function getUserAlerts($resetAlerts = false) {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
return $this->dao->getUserAlerts($this->getUserId(), $resetAlerts);
}
// Get badge info from id
public function getBadge($id) {
$r = array();
foreach ($this->badges as $b) {
if ($id == $b['id']) $r = $b;
}
return $r;
}
// Get badge id
private function getBadgeId($descriptor) {
if (empty($this->badges[$descriptor])) throw new Exception(__METHOD__.': Invalid badge');
return $this->badges[$descriptor]['id'];
}
// Get event id
private function getEventId($descriptor) {
if (empty($this->events[$descriptor])) throw new Exception(__METHOD__.': Invalid event');
return $this->events[$descriptor]['id'];
}
// Get event id
public function getLevel($id) {
$r = array();
foreach ($this->levels as $l) {
if ($id == $l['id']) $r = $l;
}
return $r;
}
// Get user log
public function getUserLog() {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
return $this->dao->getUserLog($this->getUserId());
}
// Get a list of user badges
public function getUserBadges() {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
$r = array();
foreach ($this->dao->getUserBadges($this->getUserId()) as $x) {
$b = $this->getBadge($x['id_badge']);
$r[] = array(
'id' => $x['id_badge'],
'counter' => $x['badgescounter'],
'imageurl' => $b['imageurl'],
'internal' => $b['internal'],
'descriptor' => $b['descriptor'],
'description' => $b['description'],
);
}
return $r;
}
// Get user scores
public function getUserScores() {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
$r = $this->dao->getUserScores($this->getUserId());
// Include additional progress data
if (empty($r)) {
$r['id_user'] = $this->getUserId();
$r['points'] = '0';
$r['id_level'] = 1;
}
$level = $this->getLevel($r['id_level']);
$nextLevel = $this->getLevel($r['id_level'] + 1);
$r['progress'] = 0;
$r['levelpoints'] = 0;
$r['levelname'] = $level['descriptor'];
// If exists next level
if (empty($nextlevel)) {
// Points of this level
$totalLevelPoints = $nextLevel['threshold'] - $level['threshold'];
$r['levelpoints'] = $r['points'] - $level['threshold'];
// Progress percentage to reach next level
$r['progress'] = round(($r['levelpoints'] * 100) / $totalLevelPoints);
}
return $r;
}
// Get user id
public function getUserId() {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
return $this->userId;
}
// Execute gamification event
public function executeEvent($descriptor, $additional = null) {
if (!$this->letsGoParty) return false;
if (!isset($this->events[$descriptor])) throw new Exception(__METHOD__.': Invalid event');
// Get id of event in $this->events array
$currentEventId = $this->getEventId($descriptor);
// Get event counter and current points for this event
$userEvent = $this->dao->getUserEvent($this->getUserId(), $currentEventId);
// Counters initialization (max repetitions and current points for this event)
if (empty($userEvent)) {
$eventCounter = 0;
$eventPoints = 0;
} else {
$eventCounter = $userEvent['eventcounter'];
$eventPoints = $userEvent['pointscounter'];
}
// Is this event allowed to repeat?
$executeEvent = true;
if (!$this->events[$descriptor]['allowrepetitions'] && $eventCounter > 0) $executeEvent = false;
// Is the event allow to execute?
if ($executeEvent) {
// Update counter for this event
$this->dao->increaseEventCounter($this->getUserId(), $currentEventId);
// Increase internal counter for this user/event
$eventCounter++;
// Search triggers counter
/** @var $e gengamificationEvent */
foreach ($this->events[$descriptor]['triggers'] as $e) {
$eachOk = true;
// Execute each function
$callback = $e->getEachCallback();
if (is_callable($callback)) $eachOk = $callback($additional);
// if each iterative function returns false, event cancels execution.
if ($eachOk) {
// Check if counter match trigger or required repetitions is null
if ((is_null($e->getRequiredRepetitions())) || ($e->getRequiredRepetitions() == $eventCounter)) {
$triggerOk = true;
// Execute trigger function
$callback = $e->getEventCallback();
if (is_callable($callback)) $triggerOk = $callback($additional);
// if event trigger function returns false, event cancels execution.
if ($triggerOk) {
// Grant points
if (!is_null($e->getPoints())) {
$grantPoints = true;
// Check max points for this event
if (!is_null($e->getMaxpoints())) {
// If event points OLD counter greater than maxpoints, don't save anything
if ($eventPoints >= $e->getMaxpoints()) $grantPoints = false;
}
// If points not reaches max event points, it saves them.
if ($grantPoints) {
// Grant points to user
$this->grantPoints($e->getPoints(), $this->getEventId($descriptor));
// Update points for this event
$this->dao->increaseEventPoints($this->getUserId(), $currentEventId, $e->getPoints());
}
}
// Grant badges
if (!is_null($e->getBadge())) $this->grantBadge($e->getBadge(), $this->getEventId($descriptor));
}
}
}
}
}
// Process events queue
$this->processEventsQueue($additional);
return true;
}
// Grant badge to user
public function grantBadge($descriptor, $eventId = null) {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
// Grant badge to user
$this->dao->grantBadgeToUser($this->getUserId(), $this->getBadgeId($descriptor));
// Log event
$this->dao->logUserEvent($this->getUserId(), $eventId, null, $this->getBadgeId($descriptor));
// Gamification alert
$this->alertBadge($this->getBadgeId($descriptor));
// Add event to queue when the user reach this level
if (!is_null($this->badges[$descriptor]['event'])) $this->addEventToQueue($this->badges[$descriptor]['event']);
return true;
}
// Grant level to user
public function grantLevel($levelId, $eventId = null) {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
// Grant level
$this->dao->grantLevelToUser($this->getUserId(), $levelId);
// Log event
$this->dao->logUserEvent($this->getUserId(), $eventId, null, null, $levelId);
// Gamification alert
$this->alertLevel($levelId);
// Add event to queue when the user reach this level
$l = $this->getLevel($levelId);
if (!is_null($l['event'])) $this->addEventToQueue($l['event']);
return true;
}
// Grant points to user
public function grantPoints($points, $eventId = null) {
if (is_null($this->userId)) throw new Exception(__METHOD__.': Invalid user id');
// Get user level/points
$scores = $this->dao->getUserScores($this->getUserId());
if (empty($scores)) {
$userCurrentLevel = 1 ; // Initial level: 1 (DON'T CHANGE IT)
$userPoints = 0;
} else {
$userCurrentLevel = $scores['id_level'];
$userPoints = $scores['points'];
}
// Add points to user counter
$this->dao->grantPointsToUser($this->getUserId(), $points);
// Log event
$this->dao->logUserEvent($this->getUserId(), $eventId, $points);
// Updated points for levels comparison
$userPoints += $points;
// Check new level
foreach ($this->levels as $l) {
// Check levels higher than user level
if ($l['id'] > $userCurrentLevel) {
// Check if user reaches next level
if ($userPoints >= $l['threshold']) $this->grantLevel($l['id'], $eventId);
}
}
}
// Execute next event of the events queue
private function processEventsQueue($data = null) {
if (!empty($this->eventsQueue)) {
$eventDescriptor = array_shift($this->eventsQueue);
$this->executeEvent($eventDescriptor, $data);
}
}
// Set Data Access Object
public function setDAO($dao) {
$this->dao = $dao;
}
// Set user id
public function setUserId($userId) {
if (!is_numeric($userId)) throw new Exception(__METHOD__.': Invalid parameters');
$this->userId = $userId;
return true;
}
}