Code coverage for /20080809/modules/profile/profile.module

Line #Times calledCode
1
<?php
2
// $Id: profile.module,v 1.243 2008/07/24 16:25:18 dries Exp $
3
4
/**
5
 * @file
6
 * Support for configurable user profiles.
7
 */
8
9
/**
10
 * Private field, content only available to privileged users.
11
 */
12122
define('PROFILE_PRIVATE', 1);
13
14
/**
15
 * Public field, content shown on profile page but not used on member list
pages.
16
 */
17122
define('PROFILE_PUBLIC', 2);
18
19
/**
20
 * Public field, content shown on profile page and on member list pages.
21
 */
22122
define('PROFILE_PUBLIC_LISTINGS', 3);
23
24
/**
25
 * Hidden profile field, only accessible by administrators, modules and
themes.
26
 */
27122
define('PROFILE_HIDDEN', 4);
28
29
/**
30
 * Implementation of hook_help().
31
 */
32122
function profile_help($path, $arg) {
33
  switch ($path) {
3489
    case 'admin/help#profile':
3539
      $output = '<p>' . t('The profile module allows custom fields (such as
country, full name, or age) to be defined and displayed in the <em>My
Account</em> section. This permits users of a site to share more
information about themselves, and can help community-based sites organize
users around specific information.') . '</p>';
3639
      $output .= '<p>' . t('The following types of fields can be added to a
user profile:') . '</p>';
3739
      $output .= '<ul><li>' . t('single-line textfield') . '</li>';
3839
      $output .= '<li>' . t('multi-line textfield') . '</li>';
3939
      $output .= '<li>' . t('checkbox') . '</li>';
4039
      $output .= '<li>' . t('list selection') . '</li>';
4139
      $output .= '<li>' . t('freeform list') . '</li>';
4239
      $output .= '<li>' . t('URL') . '</li>';
4339
      $output .= '<li>' . t('date') . '</li></ul>';
4439
      $output .= '<p>' . t('For more information, see the online handbook
entry for <a href="@profile">Profile module</a>.', array('@profile' =>
'http://drupal.org/handbook/modules/profile/')) . '</p>';
4539
      return $output;
4689
    case 'admin/user/profile':
4723
      return '<p>' . t("This page displays a list of the existing custom
profile fields to be displayed on a user's <em>My Account</em> page. To
provide structure, similar or related fields may be placed inside a
category. To add a new category (or edit an existing one), edit a profile
field and provide a new category name. To change the category of a field or
the order of fields within a category, grab a drag-and-drop handle under
the Title column and drag the field to a new location in the list. (Grab a
handle by clicking and holding the mouse while hovering over a handle
icon.) Remember that your changes will not be saved until you click the
<em>Save configuration</em> button at the bottom of the page.") . '</p>';
480
  }
4966
}
50
51
/**
52
 * Implementation of hook_theme().
53
 */
54122
function profile_theme() {
55
  return array(
56
    'profile_block' => array(
574
      'arguments' => array('account' => NULL, 'fields' => array()),
584
      'template' => 'profile-block',
594
    ),
60
    'profile_listing' => array(
614
      'arguments' => array('account' => NULL, 'fields' => array()),
624
      'template' => 'profile-listing',
634
    ),
64
    'profile_wrapper' => array(
654
      'arguments' => array('content' => NULL),
664
      'template' => 'profile-wrapper',
674
    ),
68
    'profile_admin_overview' => array(
694
      'arguments' => array('form' => NULL),
704
      'file' => 'profile.admin.inc',
71
    )
724
  );
730
}
74
75
/**
76
 * Implementation of hook_menu().
77
 */
78122
function profile_menu() {
7913
  $items['profile'] = array(
8013
    'title' => 'User list',
8113
    'page callback' => 'profile_browse',
8213
    'access arguments' => array('access user profiles'),
8313
    'type' => MENU_SUGGESTED_ITEM,
84
  );
8513
  $items['admin/user/profile'] = array(
8613
    'title' => 'Profiles',
8713
    'description' => 'Create customizable fields for your users.',
8813
    'page callback' => 'drupal_get_form',
8913
    'page arguments' => array('profile_admin_overview'),
9013
    'access arguments' => array('administer users'),
91
  );
9213
  $items['admin/user/profile/add'] = array(
9313
    'title' => 'Add field',
9413
    'page callback' => 'drupal_get_form',
9513
    'page arguments' => array('profile_field_form'),
9613
    'access arguments' => array('administer users'),
9713
    'type' => MENU_CALLBACK,
98
  );
9913
  $items['admin/user/profile/autocomplete'] = array(
10013
    'title' => 'Profile category autocomplete',
10113
    'page callback' => 'profile_admin_settings_autocomplete',
10213
    'access arguments' => array('administer users'),
10313
    'type' => MENU_CALLBACK,
104
  );
10513
  $items['admin/user/profile/edit'] = array(
10613
    'title' => 'Edit field',
10713
    'page callback' => 'drupal_get_form',
10813
    'page arguments' => array('profile_field_form'),
10913
    'access arguments' => array('administer users'),
11013
    'type' => MENU_CALLBACK,
111
  );
11213
  $items['admin/user/profile/delete'] = array(
11313
    'title' => 'Delete field',
11413
    'page callback' => 'drupal_get_form',
11513
    'page arguments' => array('profile_field_delete'),
11613
    'access arguments' => array('administer users'),
11713
    'type' => MENU_CALLBACK,
118
  );
11913
  $items['profile/autocomplete'] = array(
12013
    'title' => 'Profile autocomplete',
12113
    'page callback' => 'profile_autocomplete',
12213
    'access arguments' => array('access user profiles'),
12313
    'type' => MENU_CALLBACK,
124
  );
12513
  return $items;
1260
}
127
128
/**
129
 * Implementation of hook_block().
130
 */
131122
function profile_block($op = 'list', $delta = '', $edit = array()) {
132
1330
  if ($op == 'list') {
1340
    $blocks['author-information']['info'] = t('Author information');
1350
    $blocks['author-information']['cache'] = BLOCK_CACHE_PER_PAGE |
BLOCK_CACHE_PER_ROLE;
1360
    return $blocks;
1370
  }
1380
  else if ($op == 'configure') {
139
    // Compile a list of fields to show
1400
    $fields = array();
1410
    $result = db_query('SELECT name, title, weight, visibility FROM
{profile_fields} WHERE visibility IN (%d, %d) ORDER BY weight',
PROFILE_PUBLIC, PROFILE_PUBLIC_LISTINGS);
1420
    while ($record = db_fetch_object($result)) {
1430
      $fields[$record->name] = check_plain($record->title);
1440
    }
1450
    $fields['user_profile'] = t('Link to full user profile');
1460
    $form['profile_block_author_fields'] = array(
1470
      '#type' => 'checkboxes',
1480
      '#title' => t('Profile fields to display'),
1490
      '#default_value' => variable_get('profile_block_author_fields',
array()),
1500
      '#options' => $fields,
1510
      '#description' => t('Select which profile fields you wish to display
in the block. Only fields designated as public in the <a
href="@profile-admin">profile field configuration</a> are available.',
array('@profile-admin' => url('admin/user/profile'))),
152
    );
1530
    return $form;
1540
  }
1550
  else if ($op == 'save') {
1560
    variable_set('profile_block_author_fields',
$edit['profile_block_author_fields']);
1570
  }
1580
  else if ($op == 'view') {
1590
    if (user_access('access user profiles')) {
1600
      $output = '';
1610
      if ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == NULL)) {
1620
        $node = node_load(arg(1));
1630
        $account = user_load(array('uid' => $node->uid));
164
1650
        if ($use_fields = variable_get('profile_block_author_fields',
array())) {
166
          // Compile a list of fields to show.
1670
          $fields = array();
1680
          $result = db_query('SELECT name, title, type, visibility, weight
FROM {profile_fields} WHERE visibility IN (%d, %d) ORDER BY weight',
PROFILE_PUBLIC, PROFILE_PUBLIC_LISTINGS);
1690
          while ($record = db_fetch_object($result)) {
170
            // Ensure that field is displayed only if it is among the
defined block fields and, if it is private, the user has appropriate
permissions.
1710
            if (isset($use_fields[$record->name]) &&
$use_fields[$record->name]) {
1720
              $fields[] = $record;
1730
            }
1740
          }
1750
        }
176
1770
        if (!empty($fields)) {
1780
          $profile = _profile_update_user_fields($fields, $account);
1790
          $output .= theme('profile_block', $account, $profile, TRUE);
1800
        }
181
1820
        if (isset($use_fields['user_profile']) &&
$use_fields['user_profile']) {
1830
          $output .= '<div>' . l(t('View full user profile'), 'user/' .
$account->uid) . '</div>';
1840
        }
1850
      }
186
1870
      if ($output) {
1880
        $block['subject'] = t('About %name', array('%name' =>
$account->name));
1890
        $block['content'] = $output;
1900
        return $block;
1910
      }
1920
    }
1930
  }
1940
}
195
196
/**
197
 * Implementation of hook_user().
198
 */
199122
function profile_user($type, &$edit, &$user, $category = NULL) {
200
  switch ($type) {
201115
    case 'load':
202106
      return profile_load_profile($user);
20368
    case 'register':
2040
      return profile_form_profile($edit, $user, $category, TRUE);
20568
    case 'update':
2069
    return profile_save_profile($edit, $user, $category);
20768
    case 'insert':
2084
      return profile_save_profile($edit, $user, $category, TRUE);
20968
    case 'view':
21014
      return profile_view_profile($user);
21154
    case 'form':
21237
      return profile_form_profile($edit, $user, $category);
21354
    case 'validate':
2149
      return profile_validate_profile($edit, $category);
21554
    case 'categories':
21650
      return profile_categories();
21713
    case 'delete':
2180
      db_query('DELETE FROM {profile_values} WHERE uid = %d', $user->uid);
2190
  }
22013
}
221
222122
function profile_load_profile(&$user) {
223106
  $result = db_query('SELECT f.name, f.type, v.value FROM {profile_fields}
f INNER JOIN {profile_values} v ON f.fid = v.fid WHERE uid = %d',
$user->uid);
224106
  while ($field = db_fetch_object($result)) {
22530
    if (empty($user->{$field->name})) {
22630
      $user->{$field->name} = _profile_field_serialize($field->type) ?
unserialize($field->value) : $field->value;
22730
    }
22830
  }
229106
}
230
231122
function profile_save_profile(&$edit, &$user, $category, $register = FALSE)
{
23213
  $result = _profile_get_fields($category, $register);
23313
  while ($field = db_fetch_object($result)) {
2349
    if (_profile_field_serialize($field->type)) {
2351
      $edit[$field->name] = serialize($edit[$field->name]);
2361
    }
2379
    db_query("DELETE FROM {profile_values} WHERE fid = %d AND uid = %d",
$field->fid, $user->uid);
2389
    db_query("INSERT INTO {profile_values} (fid, uid, value) VALUES (%d,
%d, '%s')", $field->fid, $user->uid, $edit[$field->name]);
239
    // Mark field as handled (prevents saving to user->data).
2409
    $edit[$field->name] = NULL;
2419
  }
24213
}
243
244122
function profile_view_field($user, $field) {
245
  // Only allow browsing of private fields for admins, if browsing is
enabled,
246
  // and if a user has permission to view profiles. Note that this check
is
247
  // necessary because a user may always see their own profile.
24810
  $browse = user_access('access user profiles')
24910
         && (user_access('administer users') || $field->visibility !=
PROFILE_PRIVATE)
25010
         && !empty($field->page);
251
25210
  if (isset($user->{$field->name}) && $value = $user->{$field->name}) {
25310
    switch ($field->type) {
25410
      case 'textarea':
2551
        return check_markup($value);
2569
      case 'textfield':
2579
      case 'selection':
2585
        return $browse ? l($value, 'profile/' . $field->name . '/' .
$value) : check_plain($value);
2594
      case 'checkbox':
2601
        return $browse ? l($field->title, 'profile/' . $field->name) :
check_plain($field->title);
2613
      case 'url':
2621
        return '<a href="' . check_url($value) . '">' . check_plain($value)
. '</a>';
2632
      case 'date':
2641
        $format = substr(variable_get('date_format_short', 'm/d/Y - H:i'),
0, 5);
265
        // Note: Avoid PHP's date() because it does not handle dates
before
266
        // 1970 on Windows. This would make the date field useless for
e.g.
267
        // birthdays.
268
        $replace = array(
2691
          'd' => sprintf('%02d', $value['day']),
2701
          'j' => $value['day'],
2711
          'm' => sprintf('%02d', $value['month']),
2721
          'M' => map_month($value['month']),
2731
          'Y' => $value['year'],
2741
          'H:i' => NULL,
2751
          'g:ia' => NULL,
2761
        );
2771
        return strtr($format, $replace);
2781
      case 'list':
2791
        $values = split("[,\n\r]", $value);
2801
        $fields = array();
2811
        foreach ($values as $value) {
2821
          if ($value = trim($value)) {
2831
            $fields[] = $browse ? l($value, 'profile/' . $field->name . '/'
. $value) : check_plain($value);
2841
          }
2851
        }
2861
        return implode(', ', $fields);
2870
    }
2880
  }
2891
}
290
291122
function profile_view_profile(&$user) {
292
29314
  profile_load_profile($user);
294
295
  // Show private fields to administrators and people viewing their own
account.
29614
  if (user_access('administer users') || $GLOBALS['user']->uid ==
$user->uid) {
29714
    $result = db_query('SELECT * FROM {profile_fields} WHERE visibility !=
%d ORDER BY category, weight', PROFILE_HIDDEN);
29814
  }
299
  else {
3000
    $result = db_query('SELECT * FROM {profile_fields} WHERE visibility !=
%d AND visibility != %d ORDER BY category, weight', PROFILE_PRIVATE,
PROFILE_HIDDEN);
301
  }
302
30314
  $fields = array();
30414
  while ($field = db_fetch_object($result)) {
30510
    if ($value = profile_view_field($user, $field)) {
30610
      $title = ($field->type != 'checkbox') ? check_plain($field->title) :
NULL;
307
308
      // Create a single fieldset for each category.
30910
      if (!isset($user->content[$field->category])) {
31010
        $user->content[$field->category] = array(
31110
          '#type' => 'user_profile_category',
31210
          '#title' => $field->category,
313
        );
31410
      }
315
31610
      $user->content[$field->category][$field->name] = array(
31710
        '#type' => 'user_profile_item',
31810
        '#title' => $title,
31910
        '#markup' => $value,
32010
        '#weight' => $field->weight,
32110
        '#attributes' => array('class' => 'profile-' . $field->name),
322
      );
32310
    }
32410
  }
32514
}
326
327122
function _profile_form_explanation($field) {
32837
  $output = $field->explanation;
329
33037
  if ($field->type == 'list') {
3314
    $output .= ' ' . t('Put each item on a separate line or separate them
by commas. No HTML allowed.');
3324
  }
333
33437
  if ($field->visibility == PROFILE_PRIVATE) {
3350
    $output .= ' ' . t('The content of this field is kept private and will
not be shown publicly.');
3360
  }
337
33837
  return $output;
3390
}
340
341122
function profile_form_profile($edit, $user, $category, $register = FALSE)
{
34237
  $result = _profile_get_fields($category, $register);
34337
  $weight = 1;
34437
  $fields = array();
34537
  while ($field = db_fetch_object($result)) {
34637
    $category = $field->category;
34737
    if (!isset($fields[$category])) {
34837
      $fields[$category] = array('#type' => 'fieldset', '#title' =>
check_plain($category), '#weight' => $weight++);
34937
    }
35037
    switch ($field->type) {
35137
      case 'textfield':
35237
      case 'url':
35317
        $fields[$category][$field->name] = array('#type' => 'textfield',
35417
          '#title' => check_plain($field->title),
35517
          '#default_value' => isset($edit[$field->name]) ?
$edit[$field->name] : '',
35617
          '#maxlength' => 255,
35717
          '#description' => _profile_form_explanation($field),
35817
          '#required' => $field->required,
359
        );
36017
        if ($field->autocomplete) {
3610
          $fields[$category][$field->name]['#autocomplete_path'] =
"profile/autocomplete/" . $field->fid;
3620
        }
36317
        break;
36420
      case 'textarea':
3654
        $fields[$category][$field->name] = array('#type' => 'textarea',
3664
          '#title' => check_plain($field->title),
3674
          '#default_value' => isset($edit[$field->name]) ?
$edit[$field->name] : '',
3684
          '#description' => _profile_form_explanation($field),
3694
          '#required' => $field->required,
370
        );
3714
        break;
37216
      case 'list':
3734
        $fields[$category][$field->name] = array('#type' => 'textarea',
3744
          '#title' => check_plain($field->title),
3754
          '#default_value' => isset($edit[$field->name]) ?
$edit[$field->name] : '',
3764
          '#description' => _profile_form_explanation($field),
3774
          '#required' => $field->required,
378
        );
3794
        break;
38012
      case 'checkbox':
3814
        $fields[$category][$field->name] = array('#type' => 'checkbox',
3824
          '#title' => check_plain($field->title),
3834
          '#default_value' => isset($edit[$field->name]) ?
$edit[$field->name] : '',
3844
          '#description' => _profile_form_explanation($field),
3854
          '#required' => $field->required,
386
        );
3874
        break;
3888
      case 'selection':
3894
        $options = $field->required ? array() : array('--');
3904
        $lines = split("[,\n\r]", $field->options);
3914
        foreach ($lines as $line) {
3924
          if ($line = trim($line)) {
3934
            $options[$line] = $line;
3944
          }
3954
        }
3964
        $fields[$category][$field->name] = array('#type' => 'select',
3974
          '#title' => check_plain($field->title),
3984
          '#default_value' => isset($edit[$field->name]) ?
$edit[$field->name] : '',
3994
          '#options' => $options,
4004
          '#description' => _profile_form_explanation($field),
4014
          '#required' => $field->required,
402
        );
4034
        break;
4044
      case 'date':
4054
        $fields[$category][$field->name] = array('#type' => 'date',
4064
          '#title' => check_plain($field->title),
4074
          '#default_value' => isset($edit[$field->name]) ?
$edit[$field->name] : '',
4084
          '#description' => _profile_form_explanation($field),
4094
          '#required' => $field->required,
410
        );
4114
        break;
4120
    }
41337
  }
41437
  return $fields;
4150
}
416
417
/**
418
 * Helper function: update an array of user fields by calling
profile_view_field
419
 */
420122
function _profile_update_user_fields($fields, $account) {
4210
  foreach ($fields as $key => $field) {
4220
    $fields[$key]->value = profile_view_field($account, $field);
4230
  }
4240
  return $fields;
4250
}
426
427122
function profile_validate_profile($edit, $category) {
4289
  $result = _profile_get_fields($category);
4299
  while ($field = db_fetch_object($result)) {
4309
    if ($edit[$field->name]) {
4319
      if ($field->type == 'url') {
4321
        if (!valid_url($edit[$field->name], TRUE)) {
4330
          form_set_error($field->name, t('The value provided for %field is
not a valid URL.', array('%field' => $field->title)));
4340
        }
4351
      }
4369
    }
4371
    else if ($field->required && !user_access('administer users')) {
4380
      form_set_error($field->name, t('The field %field is required.',
array('%field' => $field->title)));
4390
    }
4409
  }
441
4429
  return $edit;
4430
}
444
445122
function profile_categories() {
44650
  $result = db_query("SELECT DISTINCT(category) FROM {profile_fields}");
44750
  $data = array();
44850
  while ($category = db_fetch_object($result)) {
44946
    $data[] = array(
45046
      'name' => $category->category,
45146
      'title' => $category->category,
45246
      'weight' => 3,
45346
      'access callback' => 'profile_category_access',
45446
      'access arguments' => array(1, $category->category)
45546
    );
45646
  }
45750
  return $data;
4580
}
459
460
/**
461
 * Menu item access callback - check if a user has access to a profile
category.
462
 */
463122
function profile_category_access($account, $category) {
46447
  if (user_access('administer users') && $account->uid > 0) {
46547
    return TRUE;
4660
  }
467
  else {
4680
    return user_edit_access($account) && db_result(db_query("SELECT
COUNT(*) FROM {profile_fields} WHERE category = '%s' AND visibility <> %d",
$category, PROFILE_HIDDEN));
469
  }
4700
}
471
472
/**
473
 * Process variables for profile-block.tpl.php.
474
 *
475
 * The $variables array contains the following arguments:
476
 * - $account
477
 * - $fields
478
 *
479
 * @see profile-block.tpl.php
480
 */
481122
function template_preprocess_profile_block(&$variables) {
482
4830
  $variables['picture'] = theme('user_picture', $variables['account']);
4840
  $variables['profile'] = array();
485
  // Supply filtered version of $fields that have values.
4860
  foreach ($variables['fields'] as $field) {
4870
    if ($field->value) {
4880
      $variables['profile'][$field->name]->title =
check_plain($field->title);
4890
      $variables['profile'][$field->name]->value = $field->value;
4900
      $variables['profile'][$field->name]->type = $field->type;
4910
    }
4920
  }
493
4940
}
495
496
/**
497
 * Process variables for profile-listing.tpl.php.
498
 *
499
 * The $variables array contains the following arguments:
500
 * - $account
501
 * - $fields
502
 *
503
 * @see profile-listing.tpl.php
504
 */
505122
function template_preprocess_profile_listing(&$variables) {
506
5070
  $variables['picture'] = theme('user_picture', $variables['account']);
5080
  $variables['name'] = theme('username', $variables['account']);
5090
  $variables['profile'] = array();
510
  // Supply filtered version of $fields that have values.
5110
  foreach ($variables['fields'] as $field) {
5120
    if ($field->value) {
5130
      $variables['profile'][$field->name]->title = $field->title;
5140
      $variables['profile'][$field->name]->value = $field->value;
5150
      $variables['profile'][$field->name]->type = $field->type;
5160
    }
5170
  }
518
5190
}
520
521
/**
522
 * Process variables for profile-wrapper.tpl.php.
523
 *
524
 * The $variables array contains the following arguments:
525
 * - $content
526
 *
527
 * @see profile-wrapper.tpl.php
528
 */
529122
function template_preprocess_profile_wrapper(&$variables) {
5300
  $variables['current_field'] = '';
5310
  if ($field = arg(1)) {
5320
    $variables['current_field'] = $field;
533
    // Supply an alternate template suggestion based on the browsable
field.
5340
    $variables['template_files'][] = 'profile-wrapper-' . $field;
5350
  }
5360
}
537
538122
function _profile_field_types($type = NULL) {
53941
  $types = array('textfield' => t('single-line textfield'),
54041
                 'textarea' => t('multi-line textfield'),
54141
                 'checkbox' => t('checkbox'),
54241
                 'selection' => t('list selection'),
54341
                 'list' => t('freeform list'),
54441
                 'url' => t('URL'),
54541
                 'date' => t('date'));
54641
  return isset($type) ? $types[$type] : $types;
5470
}
548
549122
function _profile_field_serialize($type = NULL) {
55030
  return $type == 'date';
5510
}
552
553122
function _profile_get_fields($category, $register = FALSE) {
55441
  $args = array();
55541
  $sql = 'SELECT * FROM {profile_fields} WHERE ';
55641
  $filters = array();
55741
  if ($register) {
5584
    $filters[] = 'register = 1';
5594
  }
560
  else {
561
    // Use LOWER('%s') instead of PHP's strtolower() to avoid UTF-8
conversion issues.
56237
    $filters[] = "LOWER(category) = LOWER('%s')";
56337
    $args[] = $category;
564
  }
56541
  if (!user_access('administer users')) {
5660
    $filters[] = 'visibility != %d';
5670
    $args[] = PROFILE_HIDDEN;
5680
  }
56941
  $sql .= implode(' AND ', $filters);
57041
  $sql .= ' ORDER BY category, weight';
57141
  return db_query($sql, $args);
5720
}
573
574122