-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathopen_badges.module
2589 lines (2319 loc) · 97.7 KB
/
open_badges.module
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* @brief Open Badges module file
*
* This file contains all the hook implementations and commonly used functions
*
* @author Jeff Robbins (jjeff), http://drupal.org/user/17190
* @author Chad Phillips (hunmonk), http://drupal.org/user/22079
* @author Heine Deelstra (Heine), http://drupal.org/user/17943
* @author Nuno Veloso (nunoveloso18), http://drupal.org/user/80656
* @author Richard Skinner (Likeless), http://drupal.org/user/310635
* @author Nancy Wichmann (NancyDru), http://drupal.org/user/101412
* @author Kevin Coffman (kwcoffman), http://drupal.org/user/1016508
*
*/
include 'open_badges_constants.inc';
/**
* Implements hook_help().
*/
function open_badges_help($path, $arg) {
global $user;
switch ($path) {
case 'admin/modules#description':
case 'admin/user/open_badges':
return t('User badges are iconic images which can be assigned to users. They can represent accomplishments, status, or anything you\'d like. These badges will show up in the user\'s profile, and could also be used by a theme to appear with user postings on forums, comments, or nodes. Badges can be assigned manually by an administrator by visiting a user\'s profile. They also can be assigned automatically by role or ecommerce purchase (if ecommerce modules are installed). The excellent !link module can also be used to set and unset badges on a wide variety of conditions.', array('!link' => l('Rules', 'http://drupal.org/project/rules', array('absolute' => TRUE))));
//case 'admin/user/open_badges/roles':
// return t("Select the badge that you'd like to associate with each role.");
case 'admin/user/open_badges/images':
return t("This is the open badges image library. Note that this area is not functional if you have private download active. Here you can upload images to display as a open badge, but you can also enter image URLs directly in the badge form, so this area is optional. The images can be anything you like, but it is recommended that you maintain a uniform icon size for all of your badges. Keep in mind that a user may have many badges displayed so you'll probably want to keep them as small as possible (like 16x16 pixels or smaller).");
case 'user/%/open_badges':
case 'user/%/open_badges/list':
$showone = variable_get('open_badges_showone', 0);
if (variable_get('open_badges_userweight', 0) && ($user->uid == $arg[1] || user_access('change badge assignments')) ) {
// Help messages for users who can reorder.
if ($showone) {
return t("You can reorder badges here. Some badges may not appear on the list; these badges cannot be reordered. Only the top !number badges will be shown publicly.", array('!number' => $showone));
}
else {
return t("You can reorder your badges here. Some badges may not appear on the list; these badges cannot be reordered.");
}
}
else {
// Either we don't support reordering, or this user lacks the permission to do it.
return t("These are all the badges owned by this user.");
}
}
}
/**
* Implements hook_perm().
*/
function open_badges_perm() {
return array(
'manage badges',
'change badge assignments',
'show badges in user profile'
);
}
/**
* Implements hook_menu().
*/
function open_badges_menu() {
$items = array();
$access = array('manage badges');
$items['admin/user/open_badges'] = array(
'title' => 'Manage Badges',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_badgelist_form'),
'access arguments' => $access,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/list'] = array(
'title' => 'List',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_badgelist_form'),
'access arguments' => $access,
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/add'] = array(
'title' => 'Add',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_edit_form'),
'access arguments' => $access,
'type' => MENU_LOCAL_TASK,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/images'] = array(
'title' => 'Images',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_images_form'),
'access arguments' => $access,
'type' => MENU_LOCAL_TASK,
'file' => 'open_badges.admin.inc',
);
/* XXX --- Don't support roles stuff for now! --- XXX
$items['admin/user/open_badges/roles'] = array(
'title' => 'Roles',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_roles_form'),
'access arguments' => $access,
'type' => MENU_LOCAL_TASK,
'file' => 'open_badges.admin.inc',
);
*/
$items['admin/user/open_badges/settings'] = array(
'title' => 'Settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_settings_form'),
'access arguments' => $access,
'type' => MENU_LOCAL_TASK,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/recipients/%'] = array(
'title' => 'Recipients',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_recipients_form', 4),
'access arguments' => $access,
'type' => MENU_LOCAL_TASK,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/recipients'] = array(
'title' => 'Recipients',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_recipients_form', NULL),
'access arguments' => $access,
'type' => MENU_LOCAL_TASK,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/edit/%'] = array(
'title' => 'Edit badge',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_edit_form', 4),
'access arguments' => $access,
'type' => MENU_CALLBACK,
'file' => 'open_badges.admin.inc',
);
$items['admin/user/open_badges/delete/%'] = array(
'title' => 'Delete badge',
'page callback' => 'drupal_get_form',
'page arguments' => array('open_badges_delete_form', 4),
'access arguments' => $access,
'type' => MENU_CALLBACK,
'file' => 'open_badges.admin.inc',
);
$items['user/%/open_badges'] = array(
'title' => 'Manage Badges',
'page callback' => 'open_badges_userweight_page',
'page arguments' => array(1),
'access arguments' => array('show badges in user profile'),
'type' => MENU_LOCAL_TASK,
'weight' => 4,
);
$items['user/%/open_badges/list'] = array(
'title' => 'List',
'page callback' => 'open_badges_userweight_page',
'page arguments' => array(1),
'access arguments' => array('show badges in user profile'),
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['user/%/open_badges/edit'] = array(
'title' => 'Edit',
'page callback' => 'open_badges_page',
'page arguments' => array(1),
'access arguments' => array('change badge assignments'),
'type' => MENU_LOCAL_TASK,
'weight' => 5,
);
$items['open_badges/autocomplete'] = array(
'title' => 'Open Badges Badge Name Autocomplete',
'page callback' => 'open_badges_badge_autocomplete',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['open_badges/assertion/%'] = array(
'title' => 'Open Badges Assertion',
'page callback' => 'open_badges_process_assertion_request',
'page arguments' => array(2),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['open_badges/recipients/%'] = array(
'title' => 'Open Badges Recipients',
'page callback' => 'open_badges_show_recipients',
'page arguments' => array(2),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_user().
*
* This handles assignment of badges based on role.
* When a role is assigned or removed, appropriate badges are added or removed.
*/
function open_badges_user($op, &$edit, &$account, $category = 'account') {
global $user;
static $badges = array();
static $badges_all = array();
//dpm("open_badges_user: op: '{$op}' category: '{$category}'");
switch ($op) {
case 'load':
// Have we loaded this user before?
// If so, return both cached values (full and limited lists)
if (isset($badges[$account->uid])) {
//dpm("open_badges_user: setting account->badges to cached value");
$account->badges = $badges[$account->uid];
$account->badges_all = $badges_all[$account->uid];
break;
}
$account->badges = array();
if ($account->uid > 0) {
// Get all open badges for this user, regardless of whether we filter the ones we show.
//dpm("open_badges_user: getting all badges for user '{$account->uid}'");
$account->badges_all = open_badges_get_badges($account->uid, array('nolimit' => TRUE));
// Now make the array of badges we will show.
$account->badges = $account->badges_all;
if ($limit = variable_get('open_badges_showone', 0)) {
//dpm("open_badges_user: limiting what will be shown");
//dpm("Limit: $limit, account->badges: ".print_r($account->badges, true));
// Loop through all potential badges and get the ones we can show.
foreach ($account->badges_all as $bid => $badge) {
$badge->class = 'badge ' . _open_badges_class($badge);
// Display the badge if there's no limit or if the badge is unhideable or if we are within our limit.
if ($limit > 0 || $badge->unhideable == 1) {
$account->badges[$bid] = $badge;
// Count down our limit, unless the badge doesn't count towards it.
if (!$badge->doesnotcounttolimit) {
$limit--;
}
}
}
}
}
// Cache both lists (the full list and the limited list)
$badges_all[$account->uid] = $account->badges_all;
$badges[$account->uid] = $account->badges;
break;
case 'insert':
if (is_array($account->roles)) {
// Get the list of role badges.
$roles = open_badges_get_roles();
$badges = open_badges_get_badges('select');
$message = user_access('manage badges');
$rids = array_keys($account->roles);
foreach ($rids as $rid) {
// If this role has a badge...
if (key_exists($rid, $roles)) {
// and user doesn't already have this badge.
if (!key_exists($roles[$rid], $account->badges)) {
$success = open_badges_user_add_badge($account->uid, $roles[$rid], array('type' => 'role'));
if ($success && $message) {
drupal_set_message(t('User assigned %name badge.', array('%name' => $badges[$roles[$rid]])));
}
}
}
}
}
break;
case 'update':
if (is_array($edit['roles'])) {
// Badges only get assigned or removed when a user's role assignments are changed.
// Add authenticated users (code below only cares about array keys) to prevent badge deletion
$new_roles = $edit['roles'];
$new_roles[2] = 2;
// Get the list of role badges.
$roles = open_badges_get_roles();
$badges = open_badges_get_badges('select');
$message = user_access('manage badges');
// What are the added roles?
$added = array_diff(array_keys($new_roles), array_keys((array)$account->roles));
foreach ($added as $rid) {
// if this role has a badge
if (key_exists($rid, $roles) && !key_exists($roles[$rid], $account->badges_all)) {
$success = open_badges_user_add_badge($account->uid, $roles[$rid], array('type' => 'role'));
if ($success && $message) {
drupal_set_message(t('User assigned %name badge.', array('%name' => $badges[$roles[$rid]])));
}
}
}
// What are the removed roles?
$removed = array_diff(array_keys((array)$account->roles), array_keys($new_roles));
foreach ($removed as $rid) {
// If this role has a badge and user has this badge..
if (key_exists($rid, $roles) && key_exists($roles[$rid], $account->badges_all)) {
$success = open_badges_user_remove_badge($account->uid, $roles[$rid], 'role');
drupal_set_message(t('%name badge removed from user.', array('%name' => $badges[$roles[$rid]])));
}
}
//As we may have altered the badges, we need to refresh them in the $account object
$account->badges = open_badges_get_badges($account->uid);
$account->badges_all = open_badges_get_badges($account->uid, array('nolimit' => TRUE));
}
break;
case 'delete':
db_query('DELETE FROM {open_badges_user} WHERE uid = %d', $account->uid);
break;
case 'view':
//dpm("open_badges_user: doing 'view' probably calling theme for open_badge and open_badge_group");
//dpm($account, FALSE, "The account in open_badges_user");
if (is_array($account->badges) && count($account->badges)) {
$badgeimgs = array();
foreach ($account->badges as $badge) {
$badgeimgs[] = theme('open_badge', $badge, $account);
}
$account->content['open_badges'] = array(
'#type' => 'user_profile_category',
'#title' => t('Open Badges'),
'#weight' => 10,
'#attributes' => array('class' => 'open-badges'),
);
$account->content['open_badges']['link1'] = array(
'#type' => 'user_profile_item',
'#value' => theme('open_badges_link', 'connect/badges', array('text' => t('Earn more badges'))), // XXX Should be configurable
'#weight' => 2,
'#attributes' => array('class' => 'open-badges'),
);
$account->content['open_badges']['badges'] = array(
'#type' => 'user_profile_item',
'#value' => theme('open_badge_group', $badgeimgs),
'#weight' => 3,
'#attributes' => array('class' => 'badges'),
);
$account->content['open_badges']['link2'] = array(
'#type' => 'user_profile_item',
'#value' => t('View your badges in the ') . theme('open_badges_link', 'http://beta.openbadges.org/backpack/login#', array('text' => t('Mozilla OBI Backpack'))), // XXX Should be configurable
'#weight' => 4,
'#attributes' => array('class' => 'open-badges'),
);
$account->content['open_badges']['link3'] = array(
'#type' => 'user_profile_item',
'#value' => t('To learn more about the Mozilla OBI Backpack, go ') . theme('open_badges_link', 'https://wiki.mozilla.org/Badges/About', array('text' => t('here'))), // XXX Should be configurable
'#weight' => 5,
'#attributes' => array('class' => 'open-badges'),
);
}
}
}
/**
* Helper function for building badge class names.
* Was originally using form_clean_id, but it is not secure.
*
* @param $badge - the object describing the badge.
* @return string containing the class name.
*/
function _open_badges_class($badge) {
// Doing separate lines makes changing the algorithm easier.
$class = $badge->name;
$class = strip_tags($class, '');
$class = drupal_strtolower($class);
$class = str_replace(array('"', "'"), '', $class);
$class = str_replace(array('_', ' '), '-', $class);
//dpm("_open_badges_class: badge->name = $badge->name becomes $class.");
return $class;
}
/**
* Implements hook_theme().
*/
function open_badges_theme() {
return array(
'open_badge' => array(
'arguments' => array('badge' => NULL, 'account' => NULL),
),
'open_badge_group' => array(
'arguments' => array('badgeimages' => array()),
),
'open_badges_userweight_form' => array(
'arguments' => array('form' => NULL),
),
'open_badges_badgelist_form' => array(
'arguments' => array('form' => NULL),
),
'open_badges_roles_form' => array(
'arguments' => array('form' => NULL),
),
'open_badges_change_form_theme' => array(
'arguments' => array('form' => NULL),
),
'open_badges_show_recipients' => array(
'arguments' => array('form' => NULL),
),
'open_badges_date' => array(
'arguments' => array('form' => NULL, 'attributes' => NULL),
),
'open_badges_link' => array(
'arguments' => array('form' => NULL, 'attributes' => NULL),
),
'open_badges_allowsharing' => array(
'arguments' => array('form' => NULL, 'attributes' => NULL),
),
);
}
/**
* form for users to weight their own badges
*/
function open_badges_userweight_form(&$form_state, $account) {
$allbadges = $account->badges_all;
$delta = 0;
$form = array('#tree' => TRUE);
//dpm($allbadges, "open_badges_userweight_form: The list of all badges");
//dpm($form_state, "open_badges_userweight_form: The incoming form_state");
// We need to know what the weight delta will be, which depends on the number
// of badges we will list.
foreach ($allbadges as $badge) {
if (!$badge->fixedweight) {
$delta++;
}
}
$userprefs = open_badges_get_userprefs($account->uid);
$userallowsharing = $userprefs['userallowsharing'];
$useremails = $userprefs['useremails'];
//dpm("open_badges_userweight_form: The userallowsharing value returned from open_badges_get_userprefs: " . ($userallowsharing === FALSE ? "FALSE" : $userallowsharing));
// Pass the initial value through to the validation and submission functions
$form_state['open_badges']['initial_values']['userallowsharing'] = $userallowsharing;
$form_state['open_badges']['initial_values']['useremails'] = $useremails;
// Only show 'No Decision' as an option until a decision has been made
if ($userallowsharing == OPEN_BADGES_USER_DECISION_NONE) {
drupal_set_message(t('Note: You have not yet decided whether to share badges with Mozilla\'s OBI (Open Badge Infrastructure)'), 'warning', FALSE);
}
$form['userallowsharing'] = array(
'#type' => 'select',
'#title' => t('Share all badges with Mozilla\'s OBI (Open Badge Infrastructure)?'),
//'#required' => TRUE,
'#default_value' => $userallowsharing,
'#options' => ($userallowsharing == FALSE | $userallowsharing == OPEN_BADGES_USER_DECISION_NONE) ?
array(OPEN_BADGES_USER_DECISION_NONE => t('No Decision'),
OPEN_BADGES_USER_DECISION_NO => t('No'),
OPEN_BADGES_USER_DECISION_YES => t('Yes')) :
array(OPEN_BADGES_USER_DECISION_NO => t('No'),
OPEN_BADGES_USER_DECISION_YES => t('Yes')) ,
);
$form['useremails'] = array(
'#type' => 'select',
'#title' => t('Receive emails when new badges are earned?'),
//'#required' => TRUE,
'#default_value' => $useremails == FALSE ? OPEN_BADGES_USER_DECISION_YES : $useremails,
'#options' => array(OPEN_BADGES_USER_DECISION_NO => t('No'),
OPEN_BADGES_USER_DECISION_YES => t('Yes')) ,
);
// Build a table listing the appropriate badges.
foreach ($allbadges as $badge) {
// We cannot include fixed weight badges.
if ($badge->fixedweight) {
continue;
}
// Set the badge default weight.
$weight = $badge->weight;
if (isset($badge->userweight)) {
$weight = $badge->userweight;
}
$form['badge'][$badge->bid] = array('#value' => theme('open_badge', $badge, $account));
$form['name'][$badge->bid] = array('#value' => check_plain($badge->name));
$form['description'][$badge->bid] = array('#value' => check_plain($badge->description));
$form['issuedate'][$badge->bid] = array('#value' => theme('open_badges_date', $badge->issuedate, array('prefix' => t('Issued: '))));
$form['expirationdate'][$badge->bid] = array('#value' => theme('open_badges_date', $badge->expirationdate, array('prefix' => t('Expires: '))));
$form['criteria'][$badge->bid] = array('#value' => theme('open_badges_link', $badge->criteria, array('text' => t('Criteria'))));
$form['evidenceurl'][$badge->bid] = array('#value' => theme('open_badges_link', $badge->evidenceurl, array('text' => t('Evidence'))));
//dpm("open_badges_userweight_form: Badge {$badge->bid} badgeallowshring is {$badge->allowdisplay}");
$form['allowdisplay'][$badge->bid] = array(
'#type' => 'select',
'#title' => t('Display this badge on this site?'),
//'#required' => TRUE,
'#default_value' => $badge->allowdisplay,
// Only show 'No Decision' as an option until a decision has been made
'#options' => $badge->allowdisplay == OPEN_BADGES_USER_DECISION_NONE ?
array(OPEN_BADGES_USER_DECISION_NONE => t('No Decision'),
OPEN_BADGES_USER_DECISION_NO => t('No'),
OPEN_BADGES_USER_DECISION_YES => t('Yes')) :
array(OPEN_BADGES_USER_DECISION_NO => t('No'),
OPEN_BADGES_USER_DECISION_YES => t('Yes')),
);
//dpm("open_badges_userweight_form: saving initial allowdisplay value of {$badge->allowdisplay} for badge {$badge->bid}");
$form_state['open_badges']['initial_values'][$badge->bid]['allowdisplay'] = $badge->allowdisplay;
//dpm("open_badges_userweight_form: Badge {$badge->bid} has weight {$weight}, delta is {$delta}");
$form['weight'][$badge->bid] = array(
'#type' => 'weight',
'#default_value' => $weight,
'#delta' => $delta,
'#attributes' => array('class' => 'open_badges_userweight_element'),
);
}
$form['uid'] = array(
'#type' => 'value',
'#value' => $account->uid,
);
$form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
//dpm($form, "open_badges_userweight_form: the final form");
//dpm($form_state, "open_badges_userweight_form: the final form_state");
return $form;
}
/**
* Process open_badges_userweight_form form submissions.
*
* Update the badge userweights
*/
function open_badges_userweight_form_submit($form, &$form_state) {
//dpm($form, "open_badges_userweight_form_submit: The submitted form!");
//dpm($form_state, "open_badges_userweight_form_submit: The submitted form_state!");
$wrote_user_preferences = FALSE;
if (isset($form['weight']) && is_array($form['weight'])) {
foreach (element_children($form['weight']) as $bid) {
db_query("UPDATE {open_badges_user} SET userweight = %d WHERE bid = %d AND uid = %d",
$form_state['values'][$bid],
$bid,
$form_state['values']['uid']
);
}
drupal_set_message(t('Your badge order has been updated.'));
}
if (isset($form_state['values']['userallowsharing']) && $form_state['values']['userallowsharing'] != $form_state['open_badges']['initial_values']['userallowsharing']) {
if ($form_state['open_badges']['initial_values']['userallowsharing'] === FALSE && $form_state['open_badges']['initial_values']['useremails'] === FALSE) {
$record = new StdClass();
$record->uid = $form_state['values']['uid'];
$record->userallowsharing = $form_state['values']['userallowsharing'];
$result = drupal_write_record('open_badges_user_preferences', $record);
//dpm("The result of drupal_write_record() was '{$result}'");
$wrote_user_preferences = TRUE;
} else {
db_query("UPDATE {open_badges_user_preferences} SET userallowsharing = %d WHERE uid = %d",
$form_state['values']['userallowsharing'], $form_state['values']['uid']);
}
drupal_set_message(t('Your badges will @yesno be shared with Mozilla OBI',
array('@yesno' => $form_state['values']['userallowsharing'] == OPEN_BADGES_USER_DECISION_NO ? t('NOT') : t('now'))));
}
if (isset($form_state['values']['useremails']) && $form_state['values']['useremails'] != $form_state['open_badges']['initial_values']['useremails']) {
if ($wrote_user_preferences == FALSE && $form_state['open_badges']['initial_values']['userallowsharing'] === FALSE && $form_state['open_badges']['initial_values']['useremails'] === FALSE) {
$record = new StdClass();
$record->uid = $form_state['values']['uid'];
$record->useremails = $form_state['values']['useremails'];
$result = drupal_write_record('open_badges_user_preferences', $record);
//dpm("The result of drupal_write_record() was '{$result}'");
} else {
db_query("UPDATE {open_badges_user_preferences} SET useremails = %d WHERE uid = %d",
$form_state['values']['useremails'], $form_state['values']['uid']);
}
drupal_set_message(t('You will @yesno receive emails when you earn new badges',
array('@yesno' => $form_state['values']['useremails'] == OPEN_BADGES_USER_DECISION_NO ? t('no longer') : t('now'))));
}
if (isset($form['allowdisplay']) && is_array($form['allowdisplay'])) {
foreach (element_children($form['allowdisplay']) as $bid) {
$allowdisplay = $form_state['values']['allowdisplay'][$bid];
//dpm("open_badges_userweight_form_submit: For badge {$bid}, allowdisplay is '{$allowdisplay}' initial value was: " . $form_state['open_badges']['initial_values'][$bid]['allowdisplay']);
if ($allowdisplay != $form_state['open_badges']['initial_values'][$bid]['allowdisplay']) {
if ($allowdisplay == OPEN_BADGES_USER_DECISION_NO || $allowdisplay == OPEN_BADGES_USER_DECISION_YES) {
//dpm("open_badges_userweight_form_submit: updating allowdisplay to {$allowdisplay} for badge {$bid}, uid {$form_state['values']['uid']}");
db_query("UPDATE {open_badges_user} SET allowdisplay = %d WHERE bid = %d AND uid = %d AND state != %d",
$allowdisplay, $bid, $form_state['values']['uid'], OPEN_BADGES_STATE_BAKED_AND_REVOKED);
drupal_set_message(t('Badge \'@name\' will @yesno be displayed',
array('@name' => $form['name'][$bid]['#value'],
'@yesno' => $allowdisplay == OPEN_BADGES_USER_DECISION_NO ? t('NOT') : t('now'))),
'warning', FALSE);
}
}
}
}
// Instead of a redirect, cause the form to be rebuilt and re-displayed
//$form_state['rebuild'] = TRUE;
$form_state['redirect'] = 'user/' . $form_state['values']['uid'] . '/open_badges';
}
/**
* Theme a date to be displayed
*/
function theme_open_badges_date($value, $attributes) {
//dpm("theme_open_badges_date: entered");
//dpm($value, "theme_open_badges_date: value");
//dpm($attributes, "theme_open_badges_date: attribute information");
return $attributes['prefix'] . ($value == 0 ? t('N/A') : format_date($value, 'custom', 'm/d/Y', 0));
}
/**
* Theme a link to be displayed
*/
function theme_open_badges_link($value, $attributes) {
//dpm("theme_open_badges_link: entered");
//dpm($value, "theme_open_badges_link: value");
//dpm($attributes, "theme_open_badges_link: attribute information");
if ($value != '') {
return l($attributes['text'], $value, array());
} else {
return $attributes['text'];
}
}
/**
* Theme information about whether the user has allowed sharing of the badge
*/
function theme_open_badges_allowsharing($value, $attributes) {
//dpm("theme_open_badges_allowsharing: entered");
//dpm($value, "theme_open_badges_allowsharing: form information");
//dpm($attributes, "theme_open_badges_allowsharing: attribute information");
switch($value) {
case OPEN_BADGES_USER_DECISION_YES:
return t('This badge should be displayed/shared');
break;
case OPEN_BADGES_USER_DECISION_NO:
return t('This badge should NOT be displayed/shared');
break;
case OPEN_BADGES_USER_DECISION_NONE:
return t('No choice has been made yet!');
break;
}
}
/**
* Form theming function
*/
function theme_open_badges_userweight_form($form) {
$output = '';
// Loop through the array items in the name array to get all the bids for our listed badges
if (isset($form['name']) && is_array($form['name'])) {
foreach (element_children($form['name']) as $key) {
// We only want bids as values of $key
if (!is_numeric($key)) {
continue;
}
// Create the rows array for the table theme
// We create an inner table within each row for name, description, issuedate, expirationdate, etc.
$row = array();
$subrow1 = array();
$subrow2 = array();
$subrow3 = array();
$row[] = array('data' => drupal_render($form['badge'][$key]), 'colspan' => 1);
$row[] = array('data' => drupal_render($form['weight'][$key]), 'colspan' => 1, /*'width' => '10%'*/);
$subrow1[] = array('data' => drupal_render($form['name'][$key]), 'colspan' => 2, /*'width' => '20%'*/);
$subrow1[] = array('data' => drupal_render($form['description'][$key]), 'colspan' => 4, /*'width' => '40%'*/);
$subrow2[] = array('data' => drupal_render($form['issuedate'][$key]), 'colspan' => 2, /*'width' => '20%'*/);
$subrow2[] = array('data' => drupal_render($form['criteria'][$key]), 'colspan' => 2, /*'width' => '20%'*/);
$subrow2[] = array('data' => drupal_render($form['evidenceurl'][$key]), 'colspan' => 2, /*'width' => '20%'*/);
$subrow3[] = array('data' => drupal_render($form['expirationdate'][$key]), 'colspan' => 2, /*'width' => '20%'*/);
$subrow3[] = array ('data' => drupal_render($form['allowdisplay'][$key]), 'colspan' => 4, /*'width' => '40%'*/);
$row[] = theme('table', NULL, array($subrow1, $subrow2, $subrow3));
// If users are allowed to change weight, add the draggable class to the row
if (variable_get('open_badges_userweight', 0)) {
$rows[] = array('data' => $row, 'class' => 'draggable', '#weight' => $form['weight'][$key]['#value']);
} else {
$rows[] = array('data' => $row, '#weight' => $form['weight'][$key]['#value']);
}
}
// Sort the rows by their weights
usort($rows, 'element_sort');
}
else {
$rows[] = array(array('data' => t('No badges available.'), 'colspan' => '3'));
}
// This makes the table draggable
drupal_add_tabledrag('open_badges_userweight', 'order', 'sibling', 'open_badges_userweight_element');
// Place the general choices before the table of issued badges
$output .= drupal_render($form['userallowsharing']);
$output .= drupal_render($form['useremails']);
// Theme the rows we have processed so far into a table
$output .= theme('table', $form['header']['#value'], $rows, array('id' => 'open_badges_userweight'));
// Render any remaining form elements
$output .= drupal_render($form);
return $output;
}
/**
* Menu callback; Retrieve a JSON object containing autocomplete suggestions for badges
*/
function open_badges_badge_autocomplete($string = '') {
$matches = array();
if (preg_match('/^[^(]+/', $string, $searchstring)) {
$trimstring = trim($searchstring[0]);
$result = db_query_range("SELECT * FROM {open_badges_badges} WHERE name LIKE '%%%s%%'", $trimstring, 0, 10);
while ($badge = db_fetch_object($result)) {
$matches[$badge->name . ' (' . t('Badge ID') . ' ' . $badge->bid .')'] = check_plain($badge->name) . ' ' . theme('open_badge', $badge);
}
}
drupal_json($matches);
}
/**
* Validates submissions for textfields that use open_badges_badge_autocomplete strings
*
* @param $value
* The textfield value
*
* @return array($bid,$result)
* $bid
* the bid detected in the string (integer)
* for an invalid string, this will be NULL
* $result
* 'valid' for a valid string with a real bid
* 'string' for an incorrectly formatted string
* 'nobid' for a correctly formatted string with an invalid badge ID
*/
function open_badges_badge_autocomplete_validation($value) {
if (preg_match('/\('. t('Badge ID') .' (\d+)\)/', $value, $matches)) {
//The format was correct, but we need to check the bid exists
if (db_result(db_query('SELECT COUNT(*) FROM {open_badges_badges} b WHERE b.bid=%d', $matches[1]))) {
//Result found
return array($matches[1], 'valid');
}
else {
//No result found, return the error code
return array($matches[1], 'nobid');
}
}
else {
//Pattern does not match, return the error code
return array(NULL, 'string');
}
}
/**
* Define the page on user/uid/open_badges/edit.
*/
function open_badges_page($uid) {
$account = user_load($uid);
drupal_set_title(t('Edit open badges for %user_name', array('%user_name' => $account->name)));
return drupal_get_form('open_badges_change_form', $account);
}
/**
* Define the page on user/uid/open_badges.
*/
function open_badges_userweight_page($uid) {
$account = user_load($uid);
global $user;
drupal_set_title(t('Open Badges for %user_name', array('%user_name' => $account->name)));
//dpm("open_badges_userweight_page: account uid: {$account->uid} user uid: {$user->uid} variable open_badges_userweight: ". variable_get('open_badges_userweight', 0));
// Do we have the right to rearrange badges?
if (/*variable_get('open_badges_userweight', 0) &&*/ ($account->uid == $user->uid || user_access('change badge assignments')) ) {
// If the setting allows it and we are the badge owner or somebody with permission, yes.
//dpm("open_badges_userweight_page: using open_badges_userweight_form");
return drupal_get_form('open_badges_userweight_form', $account);
}
else {
//dpm("open_badges_userweight_page: doing a list...");
// Otherwise, just list the badges on the page.
$open_badges = open_badges_get_badges($account->uid, array('nolimit' => TRUE));
$badges = array();
foreach ((array)$open_badges as $badge) {
//dpm($badge, "The badge in open_badges_userweight_page");
$badges[] = theme('open_badge', $badge, $account);
}
if ($badges) {
$badges = array(theme('item_list', $badges));
return theme('open_badge_group', $badges);
}
else {
return t('This user is not currently assigned any badges.');
}
}
}
/**
* Form to change badges of a user
*/
// http://drupal.org/node/1245766
function theme_open_badges_change_form_theme($form) {
$rows = array();
// Format the 'add' elements as a table and add
// that table to the 'add' fieldset
for ($id = 1; $id <= 5; $id++) {
$row = array();
$row[] = drupal_render($form['add']['add'. $id]);
$row[] = drupal_render($form['add']['issuedate'. $id]);
$row[] = drupal_render($form['add']['expirationdate'. $id]);
$row[] = drupal_render($form['add']['evidenceurl'. $id]);
$rows[] = $row;
}
$header = array();
$attributes = array();
$addout .= theme('table', $header, $rows, $attributes);
$form['add']['#children'] = $addout;
$output .= drupal_render($form);
return $output;
}
function open_badges_change_form(&$form_state, $account) {
$form = array();
$form['uid'] = array(
'#type' => 'value',
'#value' => $account->uid,
);
$form['add'] = array(
'#type' => 'fieldset',
'#title' => t('Add Badges'),
'#weight' => 3,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
for ($i = 1; $i <= 5; $i++) {
$form['add']['add'. $i] = array(
'#type' => 'textfield',
'#title' => t('New Badge !number', array('!number' => $i)),
'#size' => 40,
'#maxlength' => 255,
'#autocomplete_path' => 'open_badges/autocomplete',
);
$form['add']['issuedate'. $i] = array(
'#type' => 'textfield',
'#default_value' => 'yyyy-mm-dd',
'#title' => t('Issue Date'),
'#description' => t('Defaults to \'now\''),
'#size' => 20,
'#maxlength' => 30
);
$form['add']['expirationdate'. $i] = array(
'#type' => 'textfield',
'#default_value' => 'yyyy-mm-dd',
'#title' => t('Expiration Date'),
'#description' => t('Defaults to \'never\''),
'#size' => 20,
'#maxlength' => 30
);
$form['add']['evidenceurl'. $i] = array(
'#type' => 'textfield',
'#title' => t('Evidence URL'),
'#size' => 30,
'#maxlength' => 255
);
}
if (count($account->badges_all)) {
$form['remove'] = array(
'#type' => 'fieldset',
'#title' => t('Remove Badges'),
'#weight' => 5,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
foreach ($account->badges_all as $badge) {
$form['remove'][$badge->bid] = array(
'#type' => 'checkbox',
'#title' => theme('open_badge', $badge, $account),
'#return_value' => 1,
'#default_value' => 0,
'#description' => check_plain($badge->name),
);
}
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Update Badges'),
'#weight' => 10,
);
$form['#theme'] = 'open_badges_change_form_theme';
return $form;
}
/**
* Validate open_badges_change_form form submissions.
*/
function open_badges_change_form_validate($form, &$form_state) {
for ($i = 1; $i <= 5; $i++) {
if (!empty($form_state['values']['add'. $i])) {
$validation = open_badges_badge_autocomplete_validation($form_state['values']['add'. $i]);
switch ($validation[1]) {
case 'nobid':
form_set_error('add'. $i, t('@value is not a valid badge ID. Try using the autocomplete function (requires javascript).', array('@value' => $validation[0])));
break;
case 'string':
form_set_error('add'. $i, t('"@value" is not a valid badge. Try using the autocomplete function (requires javascript).', array('@value' => $form_state['values']['add'. $i])));
break;
}
}
// Verify dates if something other than the default
if (!empty($form_state['values']['issuedate'. $i]) && $form_state['values']['issuedate'. $i] != 'yyyy-mm-dd') {
if (!preg_match('/\d{4}\-\d{2}-\d{2}/', $form_state['values']['issuedate'. $i])) {
form_set_error('issuedate'. $i, t('@value is not in the required \'yyyy-mm-dd\' format.', array('@value' => $form_state['values']['issuedate'. $i])));
}
}
if (!empty($form_state['values']['expirationdate'. $i]) && $form_state['values']['expirationdate'. $i] != 'yyyy-mm-dd') {
if (!preg_match('/\d{4}\-\d{2}-\d{2}/', $form_state['values']['expirationdate'. $i])) {
form_set_error('expirationdate'. $i, t('@value is not in the required \'yyyy-mm-dd\' format.', array('@value' => $form_state['values']['expirationdate'. $i])));
}
}
}
}
/**
* Process open_badges_change_form form submissions.
*
* Add the named badge. Remove the checked badges.
*/
function open_badges_change_form_submit($form, &$form_state) {
$uid = $form_state['values']['uid'];
//Add badges for non-empty fields
for ($i = 1; $i <= 5; $i++) {
$extras = array();
$extras['type'] = 'user';
if (!empty($form_state['values']['add'. $i])) {
$validation = open_badges_badge_autocomplete_validation($form_state['values']['add'. $i]);
$issuedate = $form_state['values']['issuedate'. $i];
if (!empty($issuedate) && $issuedate != 'yyyy-mm-dd') {
$extras['issuedate'] = strtotime($issuedate);
}
$expirationdate = $form_state['values']['expirationdate'. $i];
if (!empty($expirationdate) && $expirationdate != 'yyyy-mm-dd') {
$extras['expirationdate'] = strtotime($expirationdate);
}
if (!empty($form_state['values']['evidenceurl'. $i])) {
$extras['evidenceurl'] = $form_state['values']['evidenceurl'. $i];
}
//dpm("open_badges_change_form_submit: issuedate: {$extras['issuedate']}, expirationdate: {$extras['expirationdate']}, evidenceurl: {$extras['evidenceurl']}");
open_badges_user_add_badge($uid, $validation[0], $extras);
}
}
//Remove any checked badges
$badges_to_go = array();