/[drupal]/contributions/modules/user_badges/user_badges.module
ViewVC logotype

Contents of /contributions/modules/user_badges/user_badges.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.16 - (show annotations) (download) (as text)
Fri Dec 5 20:16:02 2008 UTC (11 months, 3 weeks ago) by nunoveloso18
Branch: MAIN
CVS Tags: HEAD
Changes since 1.15: +486 -391 lines
File MIME type: text/x-php
no message
1 <?php
2
3 // $Id$
4
5 /**
6 * @file
7 * @brief User Badges module file
8 *
9 * This file contains all the functions used by the module.
10 *
11 * @author Jeff Robbins (jjeff), http://drupal.org/user/17190
12 * @author Chad Phillips (hunmonk), http://drupal.org/user/22079
13 * @author Heine Deelstra (Heine), http://drupal.org/user/17943
14 * @author Nuno Veloso (nunoveloso18), http://drupal.org/user/80656
15 *
16 * @warning For more information on licensing, read the LICENCE.txt file.
17 *
18 * @todo
19 * - Support for private files
20 */
21
22
23 /**
24 * Implementation of hook_help().
25 */
26 function user_badges_help($section) {
27 switch ($section) {
28 case 'admin/modules#description':
29 // This description is shown in the listing at admin/modules.
30 return t('Merit badges that administrators can assign to users.');
31 case 'admin/settings/user_badges':
32 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).");
33 case 'admin/settings/user_badges/roles':
34 return t("Select the badge that you'd like to associate with each role.");
35 case 'admin/settings/user_badges/images':
36 return t("Upload images to display as a user badge. These 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).");
37 case 'admin/settings/user_badges/products':
38 return t("For each ecommerce product listed below, select the badge that will be assigned to users upon payment completion.");
39 }
40 }
41
42
43 /**
44 * Implementation of hook_perm().
45 */
46 function user_badges_perm() {
47 return array('manage badges');
48 }
49
50
51 /**
52 * Implementation of hook_menu().
53 */
54 function user_badges_menu($may_cache) {
55 $access = user_access('manage badges');
56 if ($may_cache) {
57 $items[] = array(
58 'path' => 'admin/user/user_badges',
59 'title' => t('Badges'),
60 'callback' => 'user_badges_settings_page',
61 'access' => $access,
62 );
63 }
64 else {
65 $items[] = array(
66 'path' => 'admin/user/user_badges/list',
67 'title' => t('Edit user badges'),
68 'access' => $access,
69 'type' => MENU_DEFAULT_LOCAL_TASK,
70 'weight' => -10
71 );
72 $items[] = array(
73 'path' => 'admin/user/user_badges/images',
74 'title' => t('Images'),
75 'callback' => 'drupal_get_form',
76 'callback arguments' => array('user_badges_images_form'),
77 'access' => $access,
78 'type' => MENU_LOCAL_TASK
79 );
80 $items[] = array(
81 'path' => 'admin/user/user_badges/roles',
82 'title' => t('Roles'),
83 'callback' => 'drupal_get_form',
84 'callback arguments' => array('user_badges_roles_form'),
85 'access' => $access,
86 'type' => MENU_LOCAL_TASK
87 );
88 if (module_exists('product')) {
89 $items[] = array(
90 'path' => 'admin/user/user_badges/products',
91 'title' => t('Products'),
92 'callback' => 'user_badges_products_page',
93 'weight' => 8,
94 'access' => $access,
95 'type' => MENU_LOCAL_TASK
96 );
97 }
98 $items[] = array(
99 'path' => 'admin/user/user_badges/settings',
100 'title' => t('Settings'),
101 'callback' => 'drupal_get_form',
102 'callback arguments' => array('user_badges_settings_form'),
103 'access' => $access,
104 'type' => MENU_LOCAL_TASK,
105 );
106 $items[] = array(
107 'path' => 'admin/user/user_badges/delete',
108 'title' => t('Delete badge'),
109 'callback' => 'drupal_get_form',
110 'callback arguments' => array('user_badges_delete_form'),
111 'access' => $access,
112 'type' => MENU_CALLBACK,
113 );
114 if (arg(0) == 'user') {
115 if ($access) {
116 $uid = arg(1);
117 }
118 if (is_numeric($uid)) {
119 $items[] = array(
120 'path' => "user/$uid/badges",
121 'title' => t('Badges'),
122 'callback' => 'user_badges_page',
123 'access' => $access,
124 'type' => MENU_LOCAL_TASK,
125 'weight' => 5,
126 );
127 }
128 }
129 }
130 return $items;
131 }
132
133
134 /**
135 * Implementation of hook_user()
136 * This handles assignment of badges based on role.
137 * When role is assigned or removed, appropriate badges are added or removed.
138 *
139 */
140 function user_badges_user($op, &$edit, &$user, $category = 'account') {
141 switch ($op) {
142
143 case 'load':
144 drupal_set_message($user->uid);
145 if ($user->uid > 0) {
146 $user->badges = user_badges_get_badges($user->uid);
147 }
148 break;
149
150 case 'insert':
151 if (is_array($user->roles)) {
152 // get the list of role badges
153 $roles = user_badges_get_roles();
154 $badges = user_badges_get_badges('select');
155 $message = user_access('manage badges');
156 $rids = array_keys($user->roles);
157 foreach ($rids as $rid) {
158 // if this role has a badge
159 if (key_exists($rid, $roles)) {
160 // and user doesn't already have this badge
161 if (!key_exists($roles[$rid], $user->badges)) {
162 $success = user_badges_user_add_badge($user->uid, $roles[$rid], 'role');
163 if ($success && $message) {
164 drupal_set_message(t('User assigned %name badge.', array('%name' => $badges[$roles[$rid]])));
165 }
166 }
167 }
168 }
169 }
170 break;
171
172 case 'update':
173 if (is_array($edit['roles'])) {
174 // Badges only get assigned or removed when a user's role assignments are changed.
175
176 // Add authenticated users (code below only cares about array keys) to prevent badge deletion
177 $new_roles = $edit['roles'];
178 $new_roles[2] = 2;
179 // Get the list of role badges.
180 $roles = user_badges_get_roles();
181 $badges = user_badges_get_badges('select');
182
183 $message = user_access('manage badges');
184
185 // What are the added roles?
186 $added = array_diff(array_keys($new_roles), array_keys((array)$user->roles));
187 foreach ($added as $rid) {
188 // if this role has a badge
189 if (key_exists($rid, $roles) && !key_exists($roles[$rid], $user->badges)) {
190 $success = user_badges_user_add_badge($user->uid, $roles[$rid], 'role');
191 if ($success && $message) {
192 drupal_set_message(t('User assigned %name badge.', array('%name' => $badges[$roles[$rid]])));
193 }
194 }
195 }
196
197 // What are the removed roles?
198 $removed = array_diff(array_keys((array)$user->roles), array_keys($new_roles));
199 foreach ($removed as $rid) {
200 // If this role has a badge and user has this badge..
201 if (key_exists($rid, $roles) && key_exists($roles[$rid], $user->badges)) {
202 $success = user_badges_user_remove_badge($user->uid, $roles[$rid], 'role');
203 drupal_set_message(t('%name badge removed from user.', array('%name' => $badges[$roles[$rid]])));
204 }
205 }
206 }
207 break;
208
209 case 'delete':
210 db_query('DELETE FROM {user_badges_user} WHERE uid = %d', $user->uid);
211 break;
212
213 case 'view':
214
215 foreach ($user->badges as $badge) {
216 $badgeimgs[] = theme('user_badge', $badge);
217 }
218 if ($badgeimgs) {
219 $badge_group[] = array(
220 'title' => '',
221 'value' => theme('user_badge_group', $badgeimgs),
222 'class' => '',
223 );
224 return array(t('Badges') => $badge_group);
225 }
226 }
227 }
228
229
230 /**
231 * Define the page on user/uid/badges.
232 */
233 function user_badges_page() {
234 $uid = arg(1);
235 $account = user_load(array('uid' => $uid));
236
237 drupal_set_title(t('Edit badges for %user_name', array('%user_name' => $account->name)));
238
239 return drupal_get_form('user_badges_page_form', $account);
240 }
241
242
243 /**
244 * Form to assign badges to users.
245 */
246 function user_badges_page_form($account) {
247 $form = array();
248
249 $form['uid'] = array('#type' => 'value', '#value' => $account->uid);
250 $form['badges'] = array('#tree' => TRUE);
251
252 $badges = user_badges_get_badges('all');
253 foreach ($badges as $badge) {
254 $form['badges'][$badge->bid] = array(
255 '#type' => 'checkbox',
256 '#title' => theme('user_badge', $badge),
257 '#return_value' => 1,
258 '#default_value' => array_key_exists($badge->bid, $account->badges),
259 '#description' => check_plain($badge->name),
260 );
261 }
262
263 $form[] = array(
264 '#type' => 'submit',
265 '#value' => t('Save Badges'),
266 );
267 return $form;
268 }
269
270 function user_badges_page_form_submit($form_id, $form_values) {
271 user_badges_user_save($form_values['badges'], $form_values['uid'], FALSE);
272 }
273
274
275 /**
276 * Assign user badges to a user
277 *
278 * @param $edit is an array containing badges array
279 * @param $uid is the user id
280 * @param $quiet suppresses message display
281 */
282 function user_badges_user_save($edit, $uid, $quiet = TRUE) {
283 $badges = user_badges_get_badges($uid);
284
285 if (is_array($edit)) {
286 // an array of just the checked boxes please
287 $newbadges = array();
288 foreach ($edit as $bid => $is_selected) {
289 if ($is_selected) {
290 $newbadges[] = $bid;
291 }
292 }
293
294 $success = TRUE;
295
296 // what are the added badges?
297 $added = array_diff($newbadges, array_keys($badges));
298
299 foreach ($added as $bid) {
300 if (!key_exists($bid, $badges)) {
301 $success = (boolean) user_badges_user_add_badge($uid, $bid);
302 }
303 }
304
305 // what are the removed badges?
306 $removed = array_diff(array_keys($badges), $newbadges);
307
308 foreach ($removed as $bid) {
309 // and user has this badge
310 if (key_exists($bid, $badges)) {
311 $success = $success && (boolean) user_badges_user_remove_badge($uid, $bid);
312 }
313 }
314 if ($success && !$quiet) {
315 drupal_set_message(t('Badges saved.'));
316 }
317 elseif (!$quiet) {
318 drupal_set_message(t('There was a problem saving badges to the database.'));
319 }
320 }
321 }
322
323
324 /**
325 * Add a badge to user.
326 *
327 * @param $uid User ID.
328 * @param $bid Badge ID.
329 * @param $type Whether set as part of the role, or individually assigned ('user', 'role').
330 *
331 * @return bool with query success
332 */
333 function user_badges_user_add_badge($uid, $bid, $type = NULL) {
334 return db_query('INSERT INTO {user_badges_user} (uid, bid, type) VALUES (%d, %d, \'%s\')', $uid, $bid, $type);
335 }
336
337
338 /**
339 * remove a badge from user.
340 *
341 * @param $uid User ID.
342 * @param $bid Badge ID.
343 * @param $type Whether set as part of the role, or individually assigned ('user', 'role').
344 *
345 * @return bool with query success
346 */
347 function user_badges_user_remove_badge($uid, $bid, $type = NULL) {
348 if (is_null($type)) {
349 return db_query('DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d', $uid, $bid);
350 }
351 else {
352 return db_query('DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d AND type=\'%s\'', $uid, $bid, $type);
353 }
354 }
355
356
357 function user_badges_settings_page($op = NULL, $bid = NULL) {
358
359 switch ($op) {
360 case 'edit':
361 if (is_numeric($bid)) {
362 $output = drupal_get_form('user_badges_edit_form', $bid);
363 break;
364 }
365 case 'delete' :
366 if (is_numeric($bid)) {
367 $output = user_badges_delete($bid);
368 break;
369 }
370 default:
371 $badges = user_badges_get_badges('all');
372 $header = array(t('Name'), t('Image'), t('Operations'));
373 if (is_array($badges)) {
374 foreach ($badges as $badge) {
375 $tablerow[$badge->bid]['name'] = $badge->name;
376 $tablerow[$badge->bid]['image'] = theme('image', $badge->image, $badge->image, $badge->image);
377 $tablerow[$badge->bid]['ops'] = l(t('edit'), 'admin/user/user_badges/edit/'. $badge->bid) .' '.
378 l(t('delete'), 'admin/user/user_badges/delete/'. $badge->bid);
379 }
380 }
381 $output = theme('table', $header, $tablerow, array('style' => 'width:100%'));
382 $output .= "<br/><br/>";
383 $form[] = array(
384 '#type' => 'fieldset',
385 '#title' => t('Add another'),
386 );
387 $output .= drupal_get_form('user_badges_edit_form');
388
389 }
390 return $output;
391 }
392
393 function user_badges_edit_form_submit($form_id, $form_values) {
394 user_badges_save_badge($form_values);
395 }
396
397
398 /**
399 * Define a form to upload the badge images.
400 */
401 function user_badges_images_form() {
402 $form = array('#skip_duplicate_check' => TRUE);
403 if (module_exists('upload')) {
404 $form['new']['upload'] = array('#type' => 'file', '#title' => t('Upload image'), '#size' => 40);
405 $form['new']['attach'] = array('#type' => 'submit', '#value' => t('Upload'));
406 }
407 else {
408 drupal_set_message(t('Upload of images requires the upload module to be enabled.'), 'error');
409 }
410
411 $form['#attributes']['enctype'] = 'multipart/form-data';
412
413 $selects = user_badges_image_selects();
414 if (count($selects)) {
415 $form['images'] = array('#tree' => TRUE);
416 foreach ($selects as $imagepath => $imageimg) {
417 $form['images'][$imagepath] = array(
418 '#type' => 'checkbox',
419 '#title' => $imageimg,
420 '#return_value' => 1,
421 '#default_value' => FALSE,
422 '#description' => check_plain($imagepath),
423 );
424 }
425 $form['delete_image'] = array(
426 '#type' => 'submit',
427 '#value' => t('Delete'),
428 );
429 }
430 return $form;
431 }
432
433
434 /**
435 * Validate the submission.
436 *
437 * Check whether:
438 * Delete has been chosen AND a checkbox has been selected
439 * OR
440 * Upload has been chosen AND the file upload form is not empty.
441 */
442 function user_badges_images_form_validate($form_id, $form_values) {
443 if ($form_values['op'] == t('Upload') && file_check_upload('upload') === FALSE ) {
444 form_set_error('upload', t('Please enter the filename of an image to upload.'));
445 }
446 else if ($form_values['op'] == t('Delete')) {
447 if (count(array_filter($form_values['images'])) == 0) {
448 form_set_error('images', t('Please select images to delete.'));
449 }
450 }
451 }
452
453 function user_badges_images_form_submit($form_id, $form_values) {
454 $op = $form_values['op'];
455 // Save uploaded files
456 if ($op == t('Upload')) {
457 $dir = file_create_path('badges');
458 $is_writable = file_check_directory($dir, 1);
459 if ($is_writable) {
460 if ( $source = file_check_upload('upload')) {
461 // Security measure to prevent exploit of file.php.png
462 $source->filename = upload_munge_filename($source->filename);
463 if ($file = file_save_upload($source, $dir)) {
464 if (image_get_info($file->filepath)) {
465 drupal_set_message(t('New image saved.'));
466 }
467 else {
468 file_delete($file->filepath);
469 drupal_set_message('Uploaded file does not appear to be a valid image file. Please try again.');
470 }
471 }
472 }
473 }
474 }
475 else if ($op == t('Delete')) {
476 foreach ($form_values['images'] as $path => $is_removed) {
477 if ($is_removed) {
478 $to_delete[] = $path;
479 }
480 }
481 if (is_array($to_delete)) {
482 user_badges_image_delete($to_delete);
483 }
484 }
485 }
486
487
488 function user_badges_image_delete($to_delete) {
489 foreach ($to_delete as $path) {
490 if (file_check_location($path, file_create_path('badges'))) {
491 file_delete($path);
492 }
493 }
494 }
495
496
497 function user_badges_roles_form() {
498 $roles = user_roles();
499 $badges = user_badges_get_roles();
500 $selects = array('' => 'inactive') + user_badges_get_badges('select');
501
502 $form['blocked'] = array(
503 '#type' => 'fieldset',
504 '#title' => t('Blocked user badge'),
505 '#collapsible' => TRUE,
506 '#collapsed' => TRUE,
507 '#tree' => TRUE,
508 );
509 $form['blocked'][0] = array(
510 '#type' => 'select',
511 '#default_value' => $badges[0],
512 '#options' => $selects,
513 );
514
515 $form['roles'] = array('#tree' => TRUE);
516 foreach ($roles as $rid => $role) {
517 if ($rid != 1) { // no badges for the anonymous role
518 $form['roles'][$rid] = array(
519 '#type' => 'select',
520 '#title' => $role,
521 '#default_value' => $badges[$rid],
522 '#options' => $selects,
523 );
524 }
525 }
526 $form[] = array(
527 '#type' => 'submit',
528 '#value' => t('Save Roles'),
529 );
530 return $form;
531 }
532
533 function user_badges_roles_form_submit($form_id, $form_values) {
534 $array = $form_values['roles'] + $form_values['blocked'];
535 user_badges_save_roles($array);
536 }
537
538
539 /**
540 * Return array of user badges where keys are badge ids (bid)
541 * and values are object containing badge info
542 * if $uid is a user id, returns badges for that user
543 * if $uid is 'all', returns all badges
544 * if $uid is 'select', returns badges for form_select options
545 * returned values for 'select' are just badge names
546 *
547 */
548 function user_badges_get_badges($user_id) {
549 $badges = array();
550 if ($user_id == 'all' || $uid == 'select') {
551 $sql = db_query('
552 SELECT b.bid, b.weight, b.name, b.image, b.href
553 FROM {user_badges_badges} b
554 ORDER BY b.weight, b.name'
555 );
556 }
557 else {
558 $usr = db_result(db_query('SELECT COUNT(uid) FROM {users} WHERE uid = %d AND status = 0', $uid));
559
560 if ($usr && variable_get('user_badges_showblocked', 0)) {
561 $sql = db_query('
562 SELECT DISTINCT b.bid, b.weight, b.name, b.image, b.href
563 FROM {user_badges_badges} b
564 INNER JOIN {user_badges_user} u ON b.bid = u.bid
565 INNER JOIN {user_badges_roles} r ON b.bid = r.bid
566 WHERE u.uid = %d AND r.rid = 0
567 ORDER BY b.weight, b.name',
568 $uid
569 );
570 }
571 else {
572 $limit = variable_get('user_badges_showone', 0) ? ' LIMIT 1 ' : '';
573 $sql = db_query('
574 SELECT DISTINCT b.bid, b.weight, b.name, b.image, b.href
575 FROM {user_badges_badges} b INNER JOIN {user_badges_user} u ON b.bid = u.bid
576 WHERE u.uid = %d
577 ORDER BY b.weight, b.name
578 %s',
579 $uid, $limit
580 );
581 }
582 }
583 while ($badge = db_fetch_object($sql)) {
584 if ($uid == 'select') {
585 $badges[$badge->bid] = $badge->name;
586 }
587 else {
588 $badges[$badge->bid] = $badge;
589 }
590 }
591 return $badges;
592 }
593
594
595
596 /**
597 * Return badge object for given badge id
598 */
599 function user_badges_get_badge($bid) {
600 return db_fetch_object(db_query('SELECT * FROM {user_badges_badges} WHERE bid = %d', $bid));
601 }
602
603
604 /**
605 * Define the edit form for userbadges.
606 */
607 function user_badges_edit_form($bid = NULL) {
608 if (is_numeric($bid)) {
609 $edit = db_fetch_object(db_query('SELECT * FROM {user_badges_badges} WHERE bid = %d', $bid));
610 if (is_numeric($edit->bid)) {
611 $form['bid'] = array(
612 '#type' => 'hidden',
613 '#value' => $edit->bid,
614 );
615 }
616 }
617 $form['name'] = array(
618 '#type' => 'textfield',
619 '#title' => t('Name'),
620 '#default_value' => $edit->name,
621 '#size' => 40,
622 '#maxlength' => 100,
623 '#description' => t('Name for the badge. Will be displayed as tooltip when rolling over badge image.'),
624 '#attributes' => NULL,
625 '#required' => TRUE,
626 );
627 $selects = user_badges_image_selects();
628 if (count($selects)) {
629 $form['image'] = array(
630 '#type' => 'radios',
631 '#title' => t('Image'),
632 '#default_value' => $edit->image,
633 '#options' => $selects,
634 '#description' => t('Select an image to associate with this badge. You can upload additional images on the <a href="@url">Images page</a>.', array('@url' => url("admin/user/user_badges/images"))),
635 );
636 }
637 else {
638 drupal_set_message('<strong>'. t('You have to <a href="@upload_link">upload badge images</a> first.',
639 array('@upload_link' => url("admin/user/user_badges/images"))) .'</strong>', 'error');
640 }
641 $form['weight'] = array(
642 '#type' => 'weight',
643 '#title' => t('Weight'),
644 '#default_value' => $edit->weight,
645 '#delta' => 10,
646 '#description' => t('Lighter weighted items float to the top of lists. Heavier items go to the bottom.'),
647 );
648 $form['href'] = array(
649 '#type' => 'textfield',
650 '#title' => t('Description URL'),
651 '#description' => t('You can specify here the link where your badge will redirect your user.
652 This is useful for explanation pages about the badge, for instance. If you do not whish
653 your badge to be clickable, please leave this field empty') .'<br />'.
654 '<u>'. t('Tips:') .'</u>'.'<ul>'.
655 '<li>'. t('If you provide the full URL, it will be considered an external URL.') .'</li>'.
656 '<li>'. t('If you provide only the path (e.g. "admin/content/node"), it is considered an
657 internal link.') .'</li>'.
658 '</ul>',
659 '#default_value' => $edit->href,
660 );
661 $form[] = array(
662 '#type' => 'submit',
663 '#value' => 'Submit',
664 );
665 return $form;
666 }
667
668
669 /**
670 * Saves information about a badge into the database
671 */
672 function user_badges_save_badge($edit) {
673 $edit = (object)$edit;
674 if (is_numeric($edit->bid)) {
675 db_query('DELETE FROM {user_badges_badges} WHERE bid = %d', $edit->bid);
676 }
677 else {
678 $edit->bid = db_next_id('user_badges_badges');
679 }
680 $result = db_query("
681 INSERT INTO {user_badges_badges} (bid, name, image, weight, href)
682 VALUES (%d, '%s', '%s', %d, '%s')",
683 $edit->bid, $edit->name, $edit->image, $edit->weight, trim($edit->href));
684 if ($result) {
685 drupal_set_message(t('Badge %badgename saved.', array('%badgename' => $edit->name)));
686 }
687 else {
688 drupal_set_message(t('There was a problem saving the badge information into the database.'));
689 }
690 drupal_goto('admin/user/user_badges');
691 return $result;
692 }
693
694
695 function user_badges_delete_form($bid) {
696 if ($badge = user_badges_get_badge($bid)) {
697 $form = array();
698 $form['badge'] = array('#value' => theme('user_badge_group', array(theme('user_badge', $badge))));
699 $form['bid'] = array('#type' => 'value', '#value' => $bid);
700 return confirm_form($form, t('Are you sure you want to delete the badge %name?', array('%name' => $badge->name)), 'admin/user/user_badges');
701 }
702 form_set_error('', t('This badge does not exist.'));
703 }
704
705 function user_badges_delete_form_submit($form_id, $form_values) {
706 db_query("DELETE FROM {user_badges_badges} WHERE bid = %d", $form_values['bid']);
707 db_query("DELETE FROM {user_badges_user} WHERE bid = %d", $form_values['bid']);
708 db_query("DELETE FROM {user_badges_roles} WHERE bid = %d", $form_values['bid']);
709 drupal_set_message(t('Badge deleted.'));
710 return 'admin/user/user_badges';
711 }
712
713
714 function user_badges_image_selects() {
715 $selects = array();
716 $dir = file_create_path('badges');
717 $files = file_scan_directory($dir, '.*\.(gif|jpg|jpeg|png)', array('.', '..', 'CVS'), 0, FALSE);
718 foreach ($files as $file) {
719 $selects[$file->filename] = theme('image', $file->filename, $file->filename, $file->filename);
720 }
721 return $selects;
722 }
723
724
725 /**
726 * Returns an array where keys are role ids (rid) and values are badge ids (bid)
727 * These values are assigned on admin/user/user_badges/roles
728 *
729 * @param $rid - if set, return only value for this role
730 *
731 * @return a list of roles
732 */
733 function user_badges_get_roles($rid = NULL) {
734 $roles = array();
735 if ($rid) {
736 $sql = db_query('SELECT * FROM {user_badges_roles} WHERE rid = %d', $rid);
737 }
738 else {
739 $sql = db_query('SELECT * FROM {user_badges_roles}');
740 }
741 while ($row = db_fetch_object($sql)) {
742 $roles[$row->rid] = $row->bid;
743 }
744 return $roles;
745 }
746
747
748 /**
749 * Save information about roles for user_badges (in settings)
750 */
751 function user_badges_save_roles($roles) {
752 if (is_array($roles)) {
753 $success = TRUE;
754 db_query('DELETE FROM {user_badges_roles}');
755 db_query("DELETE FROM {user_badges_user} WHERE type='role'");
756 foreach ($roles as $rid => $bid) {
757 if ($bid) {
758 $success = $success && db_query('INSERT INTO {user_badges_roles} (rid, bid) VALUES (%d, %d)', $rid, $bid);
759 // Blocked user (represented as `rid 0«) has no entry in the users_role table
760 if ($rid == 0) {
761 $success = $success && db_query("
762 INSERT INTO {user_badges_user} (uid, bid, type)
763 SELECT uid, %d, 'role' FROM {users} WHERE status = 0", $bid);
764 }
765 // Authenticated user, rid 2 has no entry in the users_role table
766 elseif ($rid == 2) {
767 $success = $success && db_query("
768 INSERT INTO {user_badges_user} (uid, bid, type)
769 SELECT uid, %d, 'role' FROM {users} WHERE uid > 0", $bid);
770 }
771 else {
772 $success = $success && db_query("
773 INSERT INTO {user_badges_user} (uid, bid, type)
774 SELECT uid, %d, 'role' FROM {users_roles} WHERE rid=%d", $bid, $rid);
775 }
776 }
777 }
778 if ($success) {
779 drupal_set_message(t('Roles saved.'));
780 }
781 else {
782 drupal_set_message(t('There was a problem saving roles to the database'));
783 }
784 }
785 }
786
787
788 /**
789 * Returns HTML representation of user badges for given uid
790 * @param $uid the user id
791 * @param $refresh (FALSE) when TRUE, refreshes the cache for $uid
792 *
793 * @return string html representation of userbadges
794 */
795 function user_badges_for_uid($uid, $refresh = FALSE) {
796 static $cache;
797 if ($uid) {
798 if (isset($cache[$uid]) && !$refresh) {
799 return $cache[$uid];
800 }
801 else {
802 $user_badges = user_badges_get_badges($uid);
803 foreach ((array)$user_badges as $badge) {
804 $badges[] = theme('user_badge', $badge);
805 }
806 $cache[$uid] = isset($badges) ? theme('user_badge_group', $badges) : '';
807 return $cache[$uid];
808 }
809 }
810
811 }
812
813
814 /**
815 * Returns HTML representation of user badges for given user
816 * $array is array defining criteria for user_load()
817 * most common use will be:
818 * user_badges_for_user(array('uid'=>123));
819 *
820 */
821 function user_badges_for_user($array) {
822 $account = user_load($array);
823 foreach ((array)$account->badges as $badge) {
824 $badges[] = theme('user_badge', $badge);
825 }
826 if ($badges) {
827 return theme('user_badge_group', $badges);
828 }
829 }
830
831
832 /**
833 * Return html representation of a group of badges
834 * $badgeimages is an array of badge image tags from theme_user_badge()
835 *
836 */
837 function theme_user_badge_group($badgeimages) {
838 if (!empty($badgeimages)) {
839 return '<div class="user_badges">'. implode('', $badgeimages) .'</div>';
840 }
841 }
842
843
844 /**
845 * Return html representation of a badge image
846 * (note: theme_image does the check_plaining)
847 */
848 function theme_user_badge($badge) {
849 $image = theme('image', $badge->image, $badge->name, $badge->name);
850 if ($badge->href != "") {
851 return l($image, $badge->href, array(), NULL, NULL, FALSE, TRUE);
852 }
853 else {
854 return $image;
855 }
856 }
857
858
859 function user_badges_products_page() {
860 $products = user_badges_get_product_list();
861 $badges = user_badges_get_products();
862 $selects = array('' => 'inactive') + user_badges_get_badges('select');
863 $form['products'] = array('#tree' => TRUE);
864 foreach ($products as $key => $val) {
865 $form['products'][$key] = array(
866 '#type' => 'select',
867 '#title' => $val->title,
868 '#default_value' => $badges[$key],
869 '#options' => $selects,
870 '#description' => check_plain($val->sku),
871 );
872 }
873 $form[] = array(
874 '#type' => 'submit',
875 '#value' => 'Save',
876 );
877 $output = drupal_get_form('user_badges_products_page', $form);
878
879 return $output;
880 }
881
882
883 function user_badges_products_page_submit($form_id, $form_values) {
884 user_badges_save_products($form_values['products']);
885 }
886
887
888 function user_badges_save_products($edit) {
889 if (is_array($edit)) {
890 $success = TRUE;
891 db_query('DELETE FROM {user_badges_product}');
892 foreach ($edit as $nid => $bid) {
893 if ($bid) {
894 $success = $success && db_query('INSERT INTO {user_badges_product} (nid, bid) VALUES (%d, %d)', $nid, $bid);
895 }
896 }
897 if ($success) {
898 drupal_set_message(t('Products saved.'));
899 }
900 else {
901 drupal_set_message(t('There was a problem saving product information to the database'));
902 }
903 }
904 }
905
906
907 function user_badges_ecommerceapi($t, $op) {
908 switch ($op) {
909 case 'on payment completion':
910 $productbadges = user_badges_get_products();
911 foreach ($t['items'] as $item) {
912 if (array_key_exists($item->nid, $productbadges)) {
913 // no duplicates please...
914 db_query("DELETE FROM {user_badges_user} WHERE uid=%d AND bid=%d", $t['uid'], $productbadges[$item->nid]);
915 db_query("INSERT INTO {user_badges_user} (uid, bid, type) VALUES (%d, %d, 'product')", $t['uid'], $productbadges[$item->nid]);
916 }
917 }
918 }
919 }
920
921
922 function user_badges_get_sku($nid) {
923 return db_result(db_query('SELECT sku FROM {ec_product} WHERE nid = %d', $nid));
924 }
925
926
927 /**
928 * Get list of all ecommerce products
929 */
930 function user_badges_get_product_list() {
931 $products = array();
932 $sql = db_query('SELECT p.*, n.title FROM {ec_product} p INNER JOIN {node} n ON p.nid = n.nid ORDER BY sku');
933 while ($row = db_fetch_object($sql)) {
934 $products[$row->nid] = $row;
935 }
936 return $products;
937 }
938
939
940 /**
941 * Get list of products that have badges
942 * keys are node ids (nid)
943 * values are badge ids (bid)
944 */
945 function user_badges_get_products() {
946 $products = array();
947 $sql = db_query('SELECT * FROM {user_badges_product}');
948 while ($row = db_fetch_object($sql)) {
949 $products[$row->nid] = $row->bid;
950 }
951 return $products;
952 }
953
954
955 function user_badges_settings_form() {
956 $form['showone'] = array(
957 '#type' => 'checkbox',
958 '#title' => t('Only show the most highest-level badge'),
959 '#default_value' => variable_get('user_badges_showone', 0),
960 '#description' => t('If checked, only the badge with the lightest weight will be shown.') .'<br/>'.
961 t('Note that if multiple badges have the same lightest weight, only one of them will appear
962 (first by alphabetical order).'),
963 );
964 $form['showblocked'] = array(
965 '#type' => 'checkbox',
966 '#title' => t('Only show blocked user badge'),
967 '#default_value' => variable_get('user_badges_showblocked', 0),
968 '#description' => t('If checked, only the badge associated to blocked users will be shown, overriding other badges
969 the user eventually has as well as the preciding options.') .'<br/>'.
970 t('Note that if there is no badge associated to blocked users, no badges will appear.') .'</br>'.
971 t('This option only acts on blocked users and has no repercussions on active user badges.'),
972 );
973 $form[] = array(
974 '#type' => 'submit',
975 '#value' => t('Save Settings'),
976 );
977 return $form;
978 }
979
980
981 function user_badges_settings_form_submit($form_id, $form_values) {
982 variable_set('user_badges_showone', $form_values['showone']);
983 variable_set('user_badges_showblocked', $form_values['showblocked']);
984
985 $message = ($form_values['showone'] ? t('Only the most highest-level user badge will be shown.') :
986 t('All user badges will be shown.')) .' '. ($form_values['showblocked'] ? t('Blocked users only will have blocked
987 user badge displayed.') : '');
988
989 drupal_set_message($message);
990 }

  ViewVC Help
Powered by ViewVC 1.1.2