summaryrefslogtreecommitdiff
path: root/modules/profile/profile.module
blob: ea99c4dc21ba623b7d29ddb717189d41fdd91ba1 (plain)
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
<?php
// $Id$

/**
 * @file
 * Support for configurable user profiles.
 */

/**
 * Private field, content only available to privileged users.
 */
define('PROFILE_PRIVATE', 1);

/**
 * Public field, content shown on profile page but not used on member list pages.
 */
define('PROFILE_PUBLIC', 2);

/**
 * Public field, content shown on profile page and on member list pages.
 */
define('PROFILE_PUBLIC_LISTINGS', 3);

/**
 * Hidden profile field, only accessible by administrators, modules and themes.
 */
define('PROFILE_HIDDEN', 4);

/**
 * Implement hook_help().
 */
function profile_help($path, $arg) {
  switch ($path) {
    case 'admin/help#profile':
      $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>';
      $output .= '<p>' . t('The following types of fields can be added to a user profile:') . '</p>';
      $output .= '<ul><li>' . t('single-line textfield') . '</li>';
      $output .= '<li>' . t('multi-line textfield') . '</li>';
      $output .= '<li>' . t('checkbox') . '</li>';
      $output .= '<li>' . t('list selection') . '</li>';
      $output .= '<li>' . t('freeform list') . '</li>';
      $output .= '<li>' . t('URL') . '</li>';
      $output .= '<li>' . t('date') . '</li></ul>';
      $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>';
      return $output;
    case 'admin/config/people/profile':
      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. Remember that your changes will not be saved until you click the <em>Save configuration</em> button at the bottom of the page.") . '</p>';
  }
}

/**
 * Implement hook_theme().
 */
function profile_theme() {
  return array(
    'profile_block' => array(
      'arguments' => array('account' => NULL, 'fields' => array()),
      'template' => 'profile-block',
    ),
    'profile_listing' => array(
      'arguments' => array('account' => NULL, 'fields' => array()),
      'template' => 'profile-listing',
    ),
    'profile_wrapper' => array(
      'arguments' => array('content' => NULL),
      'template' => 'profile-wrapper',
    ),
    'profile_admin_overview' => array(
      'arguments' => array('form' => NULL),
      'file' => 'profile.admin.inc',
    )
  );
}

/**
 * Implement hook_menu().
 */
function profile_menu() {
  $items['profile'] = array(
    'title' => 'User list',
    'page callback' => 'profile_browse',
    'access arguments' => array('access user profiles'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['admin/config/people/profile'] = array(
    'title' => 'Profiles',
    'description' => 'Create customizable fields for your users.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('profile_admin_overview'),
    'access arguments' => array('administer users'),
  );
  $items['admin/config/people/profile/add'] = array(
    'title' => 'Add field',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('profile_field_form'),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/people/profile/autocomplete'] = array(
    'title' => 'Profile category autocomplete',
    'page callback' => 'profile_admin_settings_autocomplete',
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/people/profile/edit'] = array(
    'title' => 'Edit field',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('profile_field_form'),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/people/profile/delete'] = array(
    'title' => 'Delete field',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('profile_field_delete'),
    'access arguments' => array('administer users'),
    'type' => MENU_CALLBACK,
  );
  $items['profile/autocomplete'] = array(
    'title' => 'Profile autocomplete',
    'page callback' => 'profile_autocomplete',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implement hook_block_list().
 */
function profile_block_list() {
  $blocks['author-information']['info'] = t('Author information');
  $blocks['author-information']['cache'] = BLOCK_CACHE_PER_PAGE | BLOCK_CACHE_PER_ROLE;
  return $blocks;
}

/**
 * Implement hook_block_configure().
 */
function profile_block_configure($delta = '') {
  // Compile a list of fields to show
  $fields = array();
  $result = db_query('SELECT name, title, weight, visibility FROM {profile_field} WHERE visibility IN (:visibility) ORDER BY weight', array(':visibility' => array(PROFILE_PUBLIC, PROFILE_PUBLIC_LISTINGS)));
  foreach ($result as $record) {
    $fields[$record->name] = check_plain($record->title);
  }
  $fields['user_profile'] = t('Link to full user profile');
  $form['profile_block_author_fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Profile fields to display'),
    '#default_value' => variable_get('profile_block_author_fields', array()),
    '#options' => $fields,
    '#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/config/people/profile'))),
  );
  return $form;
}

/**
 * Implement hook_block_save().
 */
function profile_block_save($delta = '', $edit = array()) {
  variable_set('profile_block_author_fields', $edit['profile_block_author_fields']);
}

/**
 * Implement hook_block_view().
 */
function profile_block_view($delta = '') {
  if (user_access('access user profiles')) {
    $output = '';
    if ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == NULL)) {
      $node = node_load(arg(1));
      $account = user_load(array('uid' => $node->uid));

      if ($use_fields = variable_get('profile_block_author_fields', array())) {
        // Compile a list of fields to show.
        $fields = array();
        $result = db_query('SELECT name, title, weight, visibility FROM {profile_field} WHERE visibility IN (:visibility) ORDER BY weight', array(':visibility' => array(PROFILE_PUBLIC, PROFILE_PUBLIC_LISTINGS)));
        foreach ($result as $record) {
          // Ensure that field is displayed only if it is among the defined block fields and, if it is private, the user has appropriate permissions.
          if (isset($use_fields[$record->name]) && $use_fields[$record->name]) {
            $fields[] = $record;
          }
        }
      }

      if (!empty($fields)) {
        $profile = _profile_update_user_fields($fields, $account);
        $output .= theme('profile_block', $account, $profile, TRUE);
      }

      if (isset($use_fields['user_profile']) && $use_fields['user_profile']) {
        $output .= '<div>' . l(t('View full user profile'), 'user/' . $account->uid) . '</div>';
      }
    }

    if ($output) {
      $block['subject'] = t('About %name', array('%name' => $account->name));
      $block['content'] = $output;
      return $block;
    }
  }
}

/**
 * Implement hook_user_register().
 */
function profile_user_register(&$edit, $account, $category) {
  return profile_form_profile($edit, $account, $category, TRUE);
}

/**
 * Implement hook_user_update().
 */
function profile_user_update(&$edit, $account, $category) {
  return profile_save_profile($edit, $account, $category);
}

/**
 * Implement hook_user_insert().
 */
function profile_user_insert(&$edit, $account, $category) {
  return profile_save_profile($edit, $account, $category, TRUE);
}

/**
 * Implement hook_user_form().
 */
function profile_user_form(&$edit, $account, $category) {
  return profile_form_profile($edit, $account, $category);
}

/**
 * Implement hook_user_cancel().
 */
function profile_user_cancel(&$edit, $account, $method) {
  switch ($method) {
    case 'user_cancel_reassign':
    case 'user_cancel_delete':
      db_delete('profile_value')
        ->condition('uid', $account->uid)
        ->execute();
      break;
  }
}

/**
 * Implement hook_user_load().
 */
function profile_user_load($users) {
  $result = db_query('SELECT f.name, f.type, v.uid, v.value FROM {profile_field} f INNER JOIN {profile_value} v ON f.fid = v.fid WHERE uid IN (:uids)', array(':uids' => array_keys($users)));
  foreach ($result as $record) {
    if (empty($users[$record->uid]->{$record->name})) {
      $users[$record->uid]->{$record->name} = _profile_field_serialize($record->type) ? unserialize($record->value) : $record->value;
    }
  }
}

function profile_save_profile(&$edit, $account, $category, $register = FALSE) {
  $result = _profile_get_fields($category, $register);
  foreach ($result as $field) {
    if (_profile_field_serialize($field->type)) {
      $edit[$field->name] = serialize($edit[$field->name]);
    }
    db_merge('profile_value')
      ->key(array(
        'fid' => $field->fid,
        'uid' => $account->uid,
      ))
      ->fields(array('value' => $edit[$field->name]))
      ->execute();
    // Mark field as handled (prevents saving to user->data).
    $edit[$field->name] = NULL;
  }
}

function profile_view_field($account, $field) {
  // Only allow browsing of private fields for admins, if browsing is enabled,
  // and if a user has permission to view profiles. Note that this check is
  // necessary because a user may always see their own profile.
  $browse = user_access('access user profiles')
        && (user_access('administer users') || $field->visibility != PROFILE_PRIVATE)
        && !empty($field->page);

  if (isset($account->{$field->name}) && $value = $account->{$field->name}) {
    switch ($field->type) {
      case 'textarea':
        return check_markup($value);
      case 'textfield':
      case 'selection':
        return $browse ? l($value, 'profile/' . $field->name . '/' . $value) : check_plain($value);
      case 'checkbox':
        return $browse ? l($field->title, 'profile/' . $field->name) : check_plain($field->title);
      case 'url':
        return '<a href="' . check_url($value) . '">' . check_plain($value) . '</a>';
      case 'date':
        $format = substr(variable_get('date_format_short', 'm/d/Y - H:i'), 0, 5);
        // Note: Avoid PHP's date() because it does not handle dates before
        // 1970 on Windows. This would make the date field useless for e.g.
        // birthdays.
        $replace = array(
          'd' => sprintf('%02d', $value['day']),
          'j' => $value['day'],
          'm' => sprintf('%02d', $value['month']),
          'M' => map_month($value['month']),
          'Y' => $value['year'],
          'H:i' => NULL,
          'g:ia' => NULL,
        );
        return strtr($format, $replace);
      case 'list':
        $values = preg_split("/[,\n\r]/", $value);
        $fields = array();
        foreach ($values as $value) {
          if ($value = trim($value)) {
            $fields[] = $browse ? l($value, 'profile/' . $field->name . '/' . $value) : check_plain($value);
          }
        }
        return implode(', ', $fields);
    }
  }
}

/**
 * Implement hook_user_view().
 */
function profile_user_view($account) {
  // Show private fields to administrators and people viewing their own account.
  if (user_access('administer users') || $GLOBALS['user']->uid == $account->uid) {
    $result = db_query('SELECT * FROM {profile_field} WHERE visibility <> :hidden ORDER BY category, weight', array(':hidden' => PROFILE_HIDDEN));
  }
  else {
    $result = db_query('SELECT * FROM {profile_field} WHERE visibility <> :private AND visibility <> :hidden ORDER BY category, weight', array(':private' => PROFILE_PRIVATE, ':hidden' => PROFILE_HIDDEN));
  }

  $fields = array();
  foreach ($result as $field) {
    if ($value = profile_view_field($account, $field)) {
      $title = ($field->type != 'checkbox') ? check_plain($field->title) : NULL;

      // Create a single fieldset for each category.
      if (!isset($account->content[$field->category])) {
        $account->content[$field->category] = array(
          '#type' => 'user_profile_category',
          '#title' => $field->category,
        );
      }

      $account->content[$field->category][$field->name] = array(
        '#type' => 'user_profile_item',
        '#title' => $title,
        '#markup' => $value,
        '#weight' => $field->weight,
        '#attributes' => array('class' => array('profile-' . $field->name)),
      );
    }
  }
}

function _profile_form_explanation($field) {
  $output = $field->explanation;

  if ($field->type == 'list') {
    $output .= ' ' . t('Put each item on a separate line or separate them by commas. No HTML allowed.');
  }

  if ($field->visibility == PROFILE_PRIVATE) {
    $output .= ' ' . t('The content of this field is kept private and will not be shown publicly.');
  }

  return $output;
}

function profile_form_profile($edit, $account, $category, $register = FALSE) {
  $result = _profile_get_fields($category, $register);
  $weight = 1;
  $fields = array();
  foreach ($result as $field) {
    $category = $field->category;
    if (!isset($fields[$category])) {
      $fields[$category] = array('#type' => 'fieldset', '#title' => check_plain($category), '#weight' => $weight++);
    }
    switch ($field->type) {
      case 'textfield':
      case 'url':
        $fields[$category][$field->name] = array('#type' => 'textfield',
          '#title' => check_plain($field->title),
          '#default_value' => isset($edit[$field->name]) ? $edit[$field->name] : '',
          '#maxlength' => 255,
          '#description' => _profile_form_explanation($field),
          '#required' => $field->required,
        );
        if ($field->autocomplete) {
          $fields[$category][$field->name]['#autocomplete_path'] = "profile/autocomplete/" . $field->fid;
        }
        break;
      case 'textarea':
        $fields[$category][$field->name] = array('#type' => 'textarea',
          '#title' => check_plain($field->title),
          '#default_value' => isset($edit[$field->name]) ? $edit[$field->name] : '',
          '#description' => _profile_form_explanation($field),
          '#required' => $field->required,
        );
        break;
      case 'list':
        $fields[$category][$field->name] = array('#type' => 'textarea',
          '#title' => check_plain($field->title),
          '#default_value' => isset($edit[$field->name]) ? $edit[$field->name] : '',
          '#description' => _profile_form_explanation($field),
          '#required' => $field->required,
        );
        break;
      case 'checkbox':
        $fields[$category][$field->name] = array('#type' => 'checkbox',
          '#title' => check_plain($field->title),
          '#default_value' => isset($edit[$field->name]) ? $edit[$field->name] : '',
          '#description' => _profile_form_explanation($field),
          '#required' => $field->required,
        );
        break;
      case 'selection':
        $options = $field->required ? array() : array('--');
        $lines = preg_split("/[\n\r]/", $field->options);
        foreach ($lines as $line) {
          if ($line = trim($line)) {
            $options[$line] = $line;
          }
        }
        $fields[$category][$field->name] = array('#type' => 'select',
          '#title' => check_plain($field->title),
          '#default_value' => isset($edit[$field->name]) ? $edit[$field->name] : '',
          '#options' => $options,
          '#description' => _profile_form_explanation($field),
          '#required' => $field->required,
        );
        break;
      case 'date':
        $fields[$category][$field->name] = array('#type' => 'date',
          '#title' => check_plain($field->title),
          '#default_value' => isset($edit[$field->name]) ? $edit[$field->name] : '',
          '#description' => _profile_form_explanation($field),
          '#required' => $field->required,
        );
        break;
    }
  }
  return $fields;
}

/**
 * Helper function: update an array of user fields by calling profile_view_field
 */
function _profile_update_user_fields($fields, $account) {
  foreach ($fields as $key => $field) {
    $fields[$key]->value = profile_view_field($account, $field);
  }
  return $fields;
}

/**
 * Implement hook_user_validate().
 */
function profile_user_validate(&$edit, $account, $category) {
  $result = _profile_get_fields($category);
  foreach ($result as $field) {
    if ($edit[$field->name]) {
      if ($field->type == 'url') {
        if (!valid_url($edit[$field->name], TRUE)) {
          form_set_error($field->name, t('The value provided for %field is not a valid URL.', array('%field' => $field->title)));
        }
      }
    }
    elseif ($field->required && !user_access('administer users')) {
      form_set_error($field->name, t('The field %field is required.', array('%field' => $field->title)));
    }
  }

  return $edit;
}
/**
 * Implement hook_user_categories().
 */
function profile_user_categories() {
  $result = db_query("SELECT DISTINCT(category) FROM {profile_field}");
  $data = array();
  foreach ($result as $category) {
    $data[] = array(
      'name' => $category->category,
      'title' => $category->category,
      'weight' => 3,
      'access callback' => 'profile_category_access',
      'access arguments' => array(1, $category->category)
    );
  }
  return $data;
}

/**
 * Menu item access callback - check if a user has access to a profile category.
 */
function profile_category_access($account, $category) {
  if (user_access('administer users') && $account->uid > 0) {
    return TRUE;
  }
  else {
    $category_visible = (bool) db_query_range('SELECT 1 FROM {profile_field} WHERE category = :category AND visibility <> :visibility', array(
      ':category' => $category,
      ':visibility' => PROFILE_HIDDEN
    ), 0, 1)->fetchField();
    return user_edit_access($account) && $category_visible;
  }
}

/**
 * Process variables for profile-block.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 * - $fields
 *
 * @see profile-block.tpl.php
 */
function template_preprocess_profile_block(&$variables) {

  $variables['user_picture'] = theme('user_picture', $variables['account']);
  $variables['profile'] = array();
  // Supply filtered version of $fields that have values.
  foreach ($variables['fields'] as $field) {
    if ($field->value) {
      $variables['profile'][$field->name]->title = check_plain($field->title);
      $variables['profile'][$field->name]->value = $field->value;
      $variables['profile'][$field->name]->type = $field->type;
    }
  }

}

/**
 * Process variables for profile-listing.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 * - $fields
 *
 * @see profile-listing.tpl.php
 */
function template_preprocess_profile_listing(&$variables) {

  $variables['user_picture'] = theme('user_picture', $variables['account']);
  $variables['name'] = theme('username', $variables['account']);
  $variables['profile'] = array();
  // Supply filtered version of $fields that have values.
  foreach ($variables['fields'] as $field) {
    if ($field->value) {
      $variables['profile'][$field->name]->title = $field->title;
      $variables['profile'][$field->name]->value = $field->value;
      $variables['profile'][$field->name]->type = $field->type;
    }
  }

}

/**
 * Process variables for profile-wrapper.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $content
 *
 * @see profile-wrapper.tpl.php
 */
function template_preprocess_profile_wrapper(&$variables) {
  $variables['current_field'] = '';
  if ($field = arg(1)) {
    $variables['current_field'] = $field;
    // Supply an alternate template suggestion based on the browsable field.
    $variables['template_files'][] = 'profile-wrapper-' . $field;
  }
}

function _profile_field_types($type = NULL) {
  $types = array('textfield' => t('single-line textfield'),
                 'textarea' => t('multi-line textfield'),
                 'checkbox' => t('checkbox'),
                 'selection' => t('list selection'),
                 'list' => t('freeform list'),
                 'url' => t('URL'),
                 'date' => t('date'));
  return isset($type) ? $types[$type] : $types;
}

function _profile_field_serialize($type = NULL) {
  return $type == 'date';
}

function _profile_get_fields($category, $register = FALSE) {
  $query = db_select('profile_field');
  if ($register) {
    $query->condition('register', 1);
  }
  else {
    // Use LOWER(:category) instead of PHP's strtolower() to avoid UTF-8 conversion issues.
    $query->where('LOWER(category) = LOWER(:category)', array(':category' => $category));
  }
  if (!user_access('administer users')) {
    $query->condition('visibility', PROFILE_HIDDEN, '<>');
  }
  return $query
    ->fields('profile_field')
    ->orderBy('category', 'ASC')
    ->orderBy('weight', 'ASC')
    ->execute();
}