give the baseclass the ability to have arbitrary api calls passed through (make site...
[project/badgeville_gamification.git] / includes / badgeville.php
1 <?php
2
3 /**
4 * @file
5 * A PHP wrapper for the API for the badgevilel gamification service.
6 * The goal of this class is to simplify the process of working with
7 * badgvilles standard API, providing methods to return needed javascript
8 * scripts, do HTTP requests and ease the standard API calls.
9 *
10 * It can run as a native PHP class, getting its config from a
11 * badgeville.ini file also by extending this class, and overriding
12 * configure() and setUser() (even httpRequest if desired).
13 * It can itegrate seemlessly with existing systems (eg: drupal).
14 */
15
16 class Badgeville {
17 protected $urlCommonCurl;
18 protected $urlCommonJs;
19 protected $apiPrivate;
20 protected $apiPublic;
21 protected $domain;
22 protected $siteUrl;
23 protected $autoRewards;
24 protected $siteData;
25 public $httpCodes;
26
27 // Set loggin level.
28 // 0 == No error loging.
29 // 1 == Log everything.
30 // 2 == Only log failures.
31 public $logLevel;
32
33 public $user;
34
35 /**
36 * Constructor method.
37 *
38 * Upon instantiation, collect or the necessary options and data.
39 */
40 public function __construct($uid = NULL) {
41 // Define the httpCodes lookup array.
42 $this->httpCodes();
43 // Setup basic properties.
44 $this->configure($uid);
45 // Set up the common url.
46 // Do this before set user setUser may use a user in badgeville.
47 $this->urlCommonCurl();
48 // Define in an extended class.
49 $this->setUser();
50 // Turn on full error logging.
51 $this->log_level = 1;
52 $this->autoRewards = array();
53
54 $this->siteData = json_decode($this->siteData()->data)->data;
55 }
56
57
58 /**
59 * Configuration method used for standalone mode.
60 *
61 * Reads configutation options from badgeville.ini
62 * and set the relevent properties.
63 */
64 protected function configure($uid = NULL) {
65
66 // Load settings from badgeville.ini.
67 $settings = parse_ini_file('badgeville.ini', TRUE);
68
69 // Store relevant settings in appropriate properties.
70 // Store the private API key.
71 $this->apiPrivate = $settings['api_keys']['private'];
72
73 // Store the public API key.
74 $this->apiPublic = $settings['api_keys']['public'];
75
76 // Store the environment we wish to work in (sandbox or production).
77 $this->domain = $settings['domains'][$settings['environment']];
78
79 // Store the site_url (id of the 'site' in badgeville).
80 $this->siteUrl = $settings['site_url'];
81
82 }
83
84 /**
85 * Map HTTP codes to their textual status.
86 *
87 * Provide and array of HTTP codes mapped to their textual description
88 * and split into SUCESS codes and ERROR codes.
89 */
90 protected function httpCodes() {
91
92 if (empty($this->httpCodes)) {
93 $this->httpCodes = array(
94 'success' => array(
95 'OK' => 200,
96 'Created' => 202,
97 ),
98 'failure' => array(
99 'Bad Request' => 400,
100 'Unprocessable entity' => 403,
101 'Permission denied' => 403,
102 'Not Found' => 404,
103 'Invalid object' => 422,
104 'Internal Server Error' => 500,
105 ),
106 );
107 }
108
109 }
110
111 /**
112 * Instantiate a badgeville_user object and store it.
113 *
114 * Creates an emptbadgeville user object and stores it.
115 * We need a badgeville user object to operate, but often this
116 * is instatiated before a user is available.
117 */
118 protected function setUser() {
119 // No user needed for what we are doing, create a dummy one.
120 $this->user = new BadgevilleUser(
121 array(
122 'firstname' => NULL,
123 'lastname' => NULL,
124 'mail' => NULL,
125 'profile_pic' => NULL,
126 'player_id' => NULL,
127 'displayname' => NULL,
128 )
129 );
130 }
131
132 /**
133 * Returns the protected networkId.
134 */
135 public function networkId() {
136 return $this->networkId;
137 }
138
139 /**
140 * Returns the URL of the badgeeville REST API.
141 */
142 public function siteUrl() {
143 return $this->siteUrl;
144 }
145
146 /**
147 * Returns the URL of the badgeeville REST API.
148 */
149 public function urlCommonCurl() {
150 if (empty($this->urlCommonCurl)) {
151 $this->urlCommonCurl = "http://$this->domain/api/berlin/$this->apiPrivate";
152 }
153 return $this->urlCommonCurl;
154 }
155
156 /**
157 * Returns the URL of the badgeville Javascript API.
158 *
159 * The output of this method is intended to be displayed
160 * within <script src=""> tags in your HTML file.
161 * It pulls together the badgeville services domain name,
162 * public API and the site_id and fomulates the URL.
163 */
164 public function urlCommonJs() {
165 if (empty($this->urlCommonJs)) {
166 $this->urlCommonJs = "http://$this->domain/v3/badgeville-current.js?key=$this->apiPublic&domain=$this->siteUrl";
167 }
168 return $this->urlCommonJs;
169 }
170
171 /**
172 * Returns all the require inline scripts for display on a page.
173 *
174 * The output of this method is intended to be displayed
175 * within <script src=""> tags in your HTML file.
176 * It pulls together all the inline scripts that are set to
177 * run for the badgeville API on this page request.
178 */
179 public function inlineJs() {
180
181 // Collect inline scripts into a single collection.
182 $scripts = '';
183
184 // Set the user.
185 $user_js = $this->userJs();
186 if ($user_js) {
187 $scripts .= $user_js . "\n";
188 }
189
190 // Trigger any set autorewards.
191 $auto_rewards_js = $this->autoRewardsJs();
192 if ($auto_rewards_js) {
193 $scripts .= $auto_rewards_js . "\n";
194 }
195
196 // Insert Badgeville.ready({}) block if it contains anything.
197 $ready_js = $this->readyJs();
198 if ($ready_js) {
199 $scripts .= $ready_js . "\n";
200 }
201
202 return $scripts;
203
204 }
205
206 /**
207 * Returns javascript to register user with the javascript API.
208 */
209 public function userJs() {
210 $script = 'Badgeville.setPlayer(' . $this->userDataJSon() . ');';
211 return $script;
212 }
213
214 /**
215 * Returns badgeville playerdata has user data.
216 */
217 public function userDataJson() {
218 $json = '{ "email": "' . $this->user->mail() . '", "display_name": "' . $this->user->displayName() . '", "first_name": "' . $this->user->firstname() . '", "last_name": "' . $this->user->lastname() . '", "picture_url": "' . $this->user->profilePic() . '" }';
219 return $json;
220 }
221
222 /**
223 * Suggest readyScripts to be displayed in the Badgeville.ready({}) block.
224 *
225 * These scripts will be included in the return of $this->badgevilleReadyJs().
226 */
227 public function addReadyScript($script) {
228 $this->readyScripts[] = $script;
229 }
230
231 /**
232 * Returns Badgville.ready() function fille with javascript.
233 */
234 public function readyJs($clear = 1) {
235
236 if (!empty($this->readyScripts)) {
237
238 // Generate badgeville.ready style autorewards javascript.
239 $ready_scripts = '';
240 foreach ($this->readyScripts as $script) {
241 $ready_scripts .= "\t$script\n";
242 }
243 if (!empty($ready_scripts)) {
244 $script = "Badgeville.ready( function () {\n$ready_scripts} );";
245 }
246
247 // Clear the Badgeville.ready array.
248 if ($clear) {
249 $this->readyScripts = array();
250 }
251
252 return $script;
253 }
254 else {
255 return 0;
256 }
257 }
258
259 /**
260 * Suggest another autoreward to be triggered by badgeville.
261 *
262 * These rewards will be included in the return of $this->autoRewardsJs().
263 */
264 public function addAutoReward($reward) {
265 $this->autoRewards[] = $reward;
266 }
267
268 /**
269 * Returns javascript to trigger badgeville autorewards.
270 */
271 public function autoRewardsJs($clear = 1) {
272
273 if (!empty($this->autoRewards)) {
274
275 // Generate the autorewards script.
276 $script = 'Badgeville.Settings.autoReward = [\'' . implode('\',\'', $this->autoRewards) . '\'];';
277
278 // Clear the autorewards array.
279 if ($clear) {
280 $this->autoRewards = array();
281 }
282
283 return $script;
284 }
285 else {
286 return 0;
287 }
288 }
289
290 /**
291 * Register user's points against a behaviour in badgeville.
292 */
293 public function registerActivity($activity) {
294
295 $service_uri = "$this->urlCommonCurl/activities.json";
296
297 $data = array(
298 'activity' => array('verb' => $activity),
299 );
300
301 if ($this->user->playerId()) {
302 $data['player_id'] = $this->user->playerId();
303 }
304 else {
305 $data['site'] = $this->siteUrl;
306 $data['user'] = $this->user->mail();
307 }
308
309 return $this->httpRequestLogger($service_uri, $data, 'POST');
310
311 }
312
313 /**
314 * Register user's points against a behaviour in badgeville.
315 */
316 public function registerReward($reward_id) {
317
318 $service_uri = "$this->urlCommonCurl/rewards.json";
319
320 $data = array(
321 'reward' => array(
322 'definition_id' => $reward_id,
323 'site_id' => $this->siteData->id,
324 'player_id' => $this->user->playerId(),
325 ),
326 );
327
328 return $this->httpRequestLogger($service_uri, $data, 'POST');
329
330 }
331
332 /**
333 * Register user's points against a behaviour in badgeville.
334 */
335 public function missionData($group_id) {
336 $service_uri = "$this->urlCommonCurl/groups/$group_id.json";
337 $data = array();
338 return json_decode($this->httpRequestLogger($service_uri, $data, 'GET')->data)->data;
339 }
340
341 /**
342 * Get all the reward definitions from badgeville.
343 */
344 public function rewardDefinitionsData() {
345
346 $page = 0;
347 // Badgeville maximum page size is 50, do not set this higher.
348 $page_size = 50;
349 $data = array();
350
351 $complete = FALSE;
352 while (!$complete) {
353 $page++;
354 $service_uri = "$this->urlCommonCurl/reward_definitions.json?site=$this->siteUrl&per_page=$page_size&page=$page";
355
356 $response = $this->httpRequestLogger($service_uri, array(), 'GET');
357 // If we got a failure response, return false.
358 if (!in_array($response->code, $this->httpCodes['success'])) {
359 return FALSE;
360 }
361 $result = json_decode($response->data, TRUE);
362 foreach ($result['data'] as $key => $value) {
363 $result['data'][$value['id']] = $value;
364 unset($result['data'][$key]);
365 }
366 $data += $result['data'];
367
368 if (count($result['data']) == 0 || count($result['data']) < $page_size) {
369 $complete = TRUE;
370 }
371 }
372
373 return $data;
374 }
375
376 /**
377 * Get all the activity definitions from badgeville.
378 */
379 public function activityDefinitionsData() {
380
381 $page = 0;
382 // Badgeville maximum page size is 50, do not set this higher.
383 $page_size = 50;
384 $data = array();
385
386 $complete = FALSE;
387 while (!$complete) {
388 $page++;
389 $service_uri = "$this->urlCommonCurl/activity_definitions.json?site=$this->siteUrl&per_page=$page_size&page=$page";
390
391 $response = $this->httpRequestLogger($service_uri, array(), 'GET');
392 // If we got a failure response, return false.
393 if (!in_array($response->code, $this->httpCodes['success'])) {
394 return FALSE;
395 }
396 $result = json_decode($response->data, TRUE);
397 $data += $result['data'];
398
399 if (count($result['data']) == 0 || count($result['data']) < $page_size) {
400 $complete = TRUE;
401 }
402 }
403
404 return $data;
405 }
406
407 /**
408 * Retrieve information from badgeville about the current site.
409 */
410 public function siteData() {
411 $service_uri = "{$this->urlCommonCurl}/sites/{$this->siteUrl}.json";
412 return $this->httpRequestLogger($service_uri);
413 }
414
415 /**
416 * Retrieve information from badgeville about player.
417 *
418 * Provide an email to get info about that player or get
419 * information on the current player.
420 */
421 public function playerData($email = 0) {
422 if ($email) {
423 $email = urlencode($email);
424 $service_uri = "{$this->urlCommonCurl}/players/info.json?site={$this->siteUrl}&email={$email}";
425 }
426 else {
427 $service_uri = "{$this->urlCommonCurl}/players/" . $this->user->playerId() . '.json';
428 }
429 return $this->httpRequestLogger($service_uri);
430 }
431
432 /**
433 * Retrieve information from badgeville about a user.
434 *
435 * Provide an email to get info about that user or get
436 * info on the current user.
437 */
438 public function userData($email = 0) {
439 $service_uri = "{$this->urlCommonCurl}/users/$email.json";
440 return $this->httpRequestLogger($service_uri);
441 }
442
443 /**
444 * Create a user in badgeville.
445 *
446 * Create a user in badgveille based on the currently loaded user data.
447 */
448 public function createUser() {
449
450 $service_uri = "{$this->urlCommonCurl}/users.json";
451 $data = array(
452 'user' => array(
453 'network_id' => $this->networkId(),
454 'name' => $this->user->displayName(),
455 'email' => $this->user->mail(),
456 ),
457 );
458
459 $res = array();
460
461 $res = $this->httpRequestLogger($service_uri, $data, 'POST');
462
463 return $res;
464
465 }
466
467 /**
468 * Create a player in badgeville.
469 *
470 * Create a player in badgveille based on the currently loaded player data.
471 */
472 protected function createPlayer() {
473
474 $service_uri = "$this->urlCommonCurl/players.json";
475
476 $data = array(
477 'site' => $this->siteUrl,
478 'email' => $this->user->mail(),
479 'player' => array(
480 'email' => $this->user->mail(),
481 'displayName' => $this->user->displayName(),
482 'first_name' => $this->user->firstname(),
483 'last_name' => $this->user->lastname(),
484 'picture_url' => $this->user->profilePic(),
485 ),
486 );
487
488 return $this->httpRequestLogger($service_uri, $data, 'POST');
489
490 }
491
492 /**
493 * Delete a user from badgeville.
494 */
495 public function deleteUser($account) {
496
497 // No BV UserID? Try and use email.
498 if (empty($account->badgeville->userId)) {
499 $email = urlencode($account->mail);
500 $service_uri = "{$this->urlCommonCurl}/users/users.json?site={$this->siteUrl}&email={$email}";
501 }
502 else {
503 $service_uri = "$this->urlCommonCurl/users/{$account->badgeville->userId}.json";
504 }
505
506 $data = array();
507 return $this->httpRequestLogger($service_uri, $data, 'DELETE');
508
509 }
510
511 /**
512 * Delete a player from badgeville.
513 */
514 public function deletePlayer($account) {
515 // No BV UserID? Try and use email.
516 if (empty($account->badgeville->userId)) {
517 $email = urlencode($account->mail);
518 $service_uri = "{$this->urlCommonCurl}/users/players.json?site={$this->siteUrl}&email={$email}";
519 }
520 else {
521 $service_uri = "$this->urlCommonCurl/players/{$account->badgeville->playerId}.json";
522 }
523 $data = array();
524 return $this->httpRequestLogger($service_uri, $data, 'DELETE');
525 }
526
527 /**
528 * Send an HTTP request.
529 */
530 protected function httpRequest($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
531 global $db_prefix;
532
533 $result = new stdClass();
534
535 // Parse the URL and make sure we can handle the schema.
536 $uri = parse_url($url);
537
538 if ($uri == FALSE) {
539 $result->error = 'unable to parse URL';
540 $result->code = -1001;
541 return $result;
542 }
543
544 if (!isset($uri['scheme'])) {
545 $result->error = 'missing schema';
546 $result->code = -1002;
547 return $result;
548 }
549
550 switch ($uri['scheme']) {
551 case 'http':
552 case 'feed':
553 $port = isset($uri['port']) ? $uri['port'] : 80;
554 $host = $uri['host'] . ($port != 80 ? ':' . $port : '');
555 $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
556 break;
557
558 case 'https':
559 // Note: Only works for PHP 4.3 compiled with OpenSSL.
560 $port = isset($uri['port']) ? $uri['port'] : 443;
561 $host = $uri['host'] . ($port != 443 ? ':' . $port : '');
562 $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, 20);
563 break;
564
565 default:
566 $result->error = 'invalid schema ' . $uri['scheme'];
567 $result->code = -1003;
568 return $result;
569 }
570
571 // Make sure the socket opened properly.
572 if (!$fp) {
573 // When a network error occurs, we use a negative number so it does not
574 // clash with the HTTP status codes.
575 $result->code = -$errno;
576 $result->error = trim($errstr);
577
578 // Log that the request failed.
579 error_log('http_request_failed');
580
581 return $result;
582 }
583
584 // Construct the path to act on.
585 $path = isset($uri['path']) ? $uri['path'] : '/';
586 if (isset($uri['query'])) {
587 $path .= '?' . $uri['query'];
588 }
589
590 // Create HTTP request.
591 $defaults = array(
592 /*
593 * RFC 2616:"non-standard ports MUST, default ports MAY be included".
594 * We don't add the port to prevent from breaking rewrite rules
595 * checking the host that do not take into account the port number.
596 */
597 'Host' => "Host: $host",
598 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
599 );
600
601 /*
602 * Only add Content-Length if we actually have any content or if it is
603 * a POST * or PUT request. Some non-standard servers get confused by
604 * Content-Length in at least HEAD/GET requests, and Squid always
605 * requires Content-Length in POST/PUT requests.
606 */
607 $content_length = strlen($data);
608 if ($content_length > 0 || $method == 'POST' || $method == 'PUT') {
609 $defaults['Content-Length'] = 'Content-Length: ' . $content_length;
610 }
611
612 // If the server url has a user then attempt to use basic authentication.
613 if (isset($uri['user'])) {
614 $defaults['Authorization'] = 'Authorization: Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
615 }
616
617 /*
618 * If the database prefix is being used by SimpleTest to run the tests in
619 * a copied. database then set the user-agent header to the database
620 * prefix so that any calls to other Drupal pages will run the SimpleTest
621 * prefixed database. The user-agent is used to ensure that multiple
622 * testing sessions running at the same time won't interfere with each
623 * other as they would if the database prefix were stored statically in
624 * a file or database variable.
625 */
626 if (is_string($db_prefix) && preg_match("/^simpletest\d+$/", $db_prefix, $matches)) {
627 $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
628 }
629
630 foreach ($headers as $header => $value) {
631 $defaults[$header] = $header . ': ' . $value;
632 }
633
634 $request = $method . ' ' . $path . " HTTP/1.0\r\n";
635 $request .= implode("\r\n", $defaults);
636 $request .= "\r\n\r\n";
637 $request .= $data;
638
639 $result->request = $request;
640
641 fwrite($fp, $request);
642
643 // Fetch response.
644 $response = '';
645 while (!feof($fp) && $chunk = fread($fp, 1024)) {
646 $response .= $chunk;
647 }
648 fclose($fp);
649
650 // Parse response.
651 list($split, $result->data) = explode("\r\n\r\n", $response, 2);
652 $split = preg_split("/\r\n|\n|\r/", $split);
653
654 list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
655 $result->protocol = $protocol;
656 $result->status_message = $status_message;
657
658 $result->headers = array();
659
660 // Parse headers.
661 while ($line = trim(array_shift($split))) {
662 list($header, $value) = explode(':', $line, 2);
663 if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
664 // RFC 2109: the Set-Cookie response header comprises the token Set-
665 // Cookie:, followed by a comma-separated list of one or more cookies.
666 $result->headers[$header] .= ',' . trim($value);
667 }
668 else {
669 $result->headers[$header] = trim($value);
670 }
671 }
672
673 $responses = array(
674 100 => 'Continue',
675 101 => 'Switching Protocols',
676 200 => 'OK',
677 201 => 'Created',
678 202 => 'Accepted',
679 203 => 'Non-Authoritative Information',
680 204 => 'No Content',
681 205 => 'Reset Content',
682 206 => 'Partial Content',
683 300 => 'Multiple Choices',
684 301 => 'Moved Permanently',
685 302 => 'Found',
686 303 => 'See Other',
687 304 => 'Not Modified',
688 305 => 'Use Proxy',
689 307 => 'Temporary Redirect',
690 400 => 'Bad Request',
691 401 => 'Unauthorized',
692 402 => 'Payment Required',
693 403 => 'Forbidden',
694 404 => 'Not Found',
695 405 => 'Method Not Allowed',
696 406 => 'Not Acceptable',
697 407 => 'Proxy Authentication Required',
698 408 => 'Request Time-out',
699 409 => 'Conflict',
700 410 => 'Gone',
701 411 => 'Length Required',
702 412 => 'Precondition Failed',
703 413 => 'Request Entity Too Large',
704 414 => 'Request-URI Too Large',
705 415 => 'Unsupported Media Type',
706 416 => 'Requested range not satisfiable',
707 417 => 'Expectation Failed',
708 500 => 'Internal Server Error',
709 501 => 'Not Implemented',
710 502 => 'Bad Gateway',
711 503 => 'Service Unavailable',
712 504 => 'Gateway Time-out',
713 505 => 'HTTP Version not supported',
714 );
715 /*
716 * RFC 2616 states that all unknown HTTP codes must be treated
717 * the same as the base code in their class.
718 */
719 if (!isset($responses[$code])) {
720 $code = floor($code / 100) * 100;
721 }
722
723 /*
724 * Codes:
725 * 200 OK.
726 * 304 Not Modified.
727 * 301 Moved permanently.
728 * 302 Moved temporarily.
729 * 307 Moved temporarily.
730 */
731
732 switch ($code) {
733 case 200:
734 case 304:
735 break;
736
737 case 301:
738 case 302:
739 case 307:
740 $location = $result->headers['Location'];
741
742 if ($retry) {
743 $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
744 $result->redirect_code = $result->code;
745 }
746 $result->redirect_url = $location;
747
748 break;
749
750 default:
751 $result->error = $status_message;
752 }
753
754 $result->code = $code;
755 $result->error = '';
756 return $result;
757 }
758
759
760 /**
761 * Send an http request and log it.
762 */
763 public function httpRequestLogger($service_uri, $data = array(), $method = 'GET') {
764
765 $log['sent']['service_uri'] = $service_uri;
766 $log['sent']['method'] = $method;
767
768 if (!empty($data)) {
769 $log['sent']['service_uri'] .= '?' . http_build_query($data);
770 }
771
772 $ret = $this->httpRequest($service_uri, $data, $method);
773
774 $log['received'] = $ret;
775
776 $trace = debug_backtrace();
777 $caller = $trace[1];
778
779 $this->log($log, $caller['function']);
780
781 return $ret;
782 }
783
784 /**
785 * Write to the error log.
786 */
787 protected function log($log, $caller = NULL) {
788
789 if ($this->logLevel == 0) {
790 // Don't log anything.
791 return;
792 }
793
794 if (!isset($caller)) {
795 $trace = debug_backtrace();
796 $caller = $trace[1];
797 $caller = $caller['function'];
798 }
799
800 if (($this->logLevel == 2 && !in_array($log['received']->code, $this->httpCodes['success'])) || $this->logLevel == 1) {
801
802 // Write the send request to the error log.
803 error_log("badgeville $caller > {$log['sent']['method']} {$log['sent']['service_uri']} {$log['sent']['data']}");
804
805 // Only try and write data to the log if we got some.
806 if (isset($log['received']->data)) {
807 $data = ' ' . $log['received']->data;
808 }
809 else {
810 $data = '';
811 }
812
813 // Only try and write errors to the log if we got some.
814 if (isset($log['received']->error)) {
815 $error = ' ' . $log['received']->error;
816 }
817 else {
818 $error = '';
819 }
820
821 // Write the response to the error log.
822 // Errors return the error property, other results a status message.
823 if (isset($log['received']->status_message)) {
824 error_log("badgeville < {$log['received']->code} {$log['received']->status_message} {$log['received']->data}");
825 }
826 else {
827 error_log("badgeville < {$log['received']->code}{$error}{$data}");
828 }
829 }
830
831 }
832
833 }
834
835
836 class BadgevilleUser {
837
838 protected $name = array('firstname' => NULL, 'lastname' => NULL);
839 protected $mail;
840 protected $profilePic;
841 protected $playerId;
842
843 /**
844 * Constructor method for BadgevilleUser class.
845 */
846 public function __construct($user) {
847 $this->name['firstname'] = $user['firstname'];
848 $this->name['lastname'] = $user['lastname'];
849 $this->name['displayname'] = $user['displayname'];
850 $this->mail = strtolower($user['mail']);
851 $this->profilePic = $user['profile_pic'];
852
853 $this->playerId = $user['player_id'];
854 }
855
856 /**
857 * Get user's firstname.
858 */
859 public function firstname() {
860 return $this->name['firstname'];
861 }
862
863 /**
864 * Get user's lastname.
865 */
866 public function lastname() {
867 return $this->name['lastname'];
868 }
869
870 /**
871 * Get user's display_name.
872 *
873 * Returns the user's display name.
874 * If the display name is not set, it defaults to the firstname and lastname
875 * concatenated by a space.
876 */
877 public function displayName() {
878 if (empty($this->name['displayname'])) {
879 $this->name['displayname'] = implode($this->name, ' ');
880 }
881 return $this->name['displayname'];
882 }
883
884 /**
885 * Get user's email address.
886 */
887 public function mail() {
888 return $this->mail;
889 }
890
891 /**
892 * Get user's displayName.
893 *
894 * Returns the url of the user's profile_pic.
895 */
896 public function profilePic() {
897 return $this->profilePic;
898 }
899
900 /**
901 * Get user's user_id.
902 */
903 public function userId() {
904 return $this->userId;
905 }
906
907 /**
908 * Get user's player_id.
909 */
910 public function playerId() {
911 return $this->playerId;
912 }
913
914 /**
915 * Get the jquery code to set the user in badgeville javascript API.
916 */
917 public function userJs() {
918 return "jQuery(document).ready( function () { Badgeville.setPlayer({ email: '$this->mail', display_name: '" . $this->displayName() . "', first_name: '{$this->name['firstname']}', last_name: '{$this->name['lastname']}', }); });";
919 }
920
921 }