1<?php
2
3/**
4 * @file
5 * Support for configurable user profiles.
6 */
7
8/**
9 * Private field, content only available to privileged users.
10 */
11define('PROFILE_PRIVATE', 1);
12
13/**
14 * Public field, content shown on profile page but not used on member list pages.
15 */
16define('PROFILE_PUBLIC', 2);
17
18/**
19 * Public field, content shown on profile page and on member list pages.
20 */
21define('PROFILE_PUBLIC_LISTINGS', 3);
22
23/**
24 * Hidden profile field, only accessible by administrators, modules and themes.
25 */
26define('PROFILE_HIDDEN', 4);
27
28/**
29 * Implements hook_help().
30 */
31function profile_help($path, $arg) {
32  switch ($path) {
33    case 'admin/help#profile':
34      $output = '';
35      $output .= '<h3>' . t('About') . '</h3>';
36      $output .= '<p>' . t('The Profile module allows site administrators to define custom fields (such as country, full name, or age) for user profiles, which are then displayed in the <a href="@user">My Account</a> section. This permits users of a site to share more information about themselves, and can help community-based sites organize users around specific information. For more information, see the online handbook entry for <a href="@profile">Profile module</a>.', array('@user' => url('user'), '@profile' => 'http://drupal.org/documentation/modules/profile/')) . '</p>';
37      $output .= '<h3>' . t('Uses') . '</h3>';
38      $output .= '<dl>';
39      $output .= '<dt>' . t('Adding fields to the default profile') . '</dt>';
40      $output .= '<dd>' . t('To provide the ability for users to enter more information about themselves, the Profile module allows additional fields to be added to the default user profile. Examples of common additions would be <em>Location</em>, <em>Company</em>, <em>Age</em>, or <em>About me</em>.') . '</dd>';
41      $output .= '<dt>' . t('User information pages') . '</dt>';
42      $output .= '<dd>' . t('The Profile module enables links to see further information about site users. You can view both a main <a href="@profile">User list page</a>, and more specified pages by clicking on linked fields in any profile. For example, the <a href="@profile-country">People who live in Canada</a> listing on Drupal.org displays all users who have entered <em>Canada</em> in the <em>Country</em> field on their user profile.', array('@profile' => url('profile'), '@profile-country' => 'http://drupal.org/profile/country/Canada')) . '</dd>';
43      $output .= '<dt>' . t('Author information block') . '</dt>';
44      $output .= '<dd>' . t('The <em>Author information block</em> is a default block created by the Profile module that can be enabled on the <a href="@blocks">Blocks administration page</a>. It shows visitors of your website information about the author of the page they are reading.', array('@blocks' => url('admin/structure/block'))) . '</dd>';
45      $output .= '</dl>';
46      return $output;
47    case 'admin/config/people/profile':
48      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.") . '</p>';
49  }
50}
51
52/**
53 * Implements hook_theme().
54 */
55function profile_theme() {
56  return array(
57    'profile_block' => array(
58      'variables' => array('account' => NULL, 'fields' => array()),
59      'template' => 'profile-block',
60    ),
61    'profile_listing' => array(
62      'variables' => array('account' => NULL, 'fields' => array()),
63      'template' => 'profile-listing',
64    ),
65    'profile_wrapper' => array(
66      'variables' => array('content' => NULL),
67      'template' => 'profile-wrapper',
68    ),
69    'profile_admin_overview' => array(
70      'render element' => 'form',
71      'file' => 'profile.admin.inc',
72    )
73  );
74}
75
76/**
77 * Implements hook_menu().
78 */
79function profile_menu() {
80  $items['profile'] = array(
81    'title' => 'User list',
82    'page callback' => 'profile_browse',
83    'access arguments' => array('access user profiles'),
84    'file' => 'profile.pages.inc',
85    'type' => MENU_SUGGESTED_ITEM,
86  );
87  $items['admin/config/people/profile'] = array(
88    'title' => 'Profiles',
89    'description' => 'Create customizable fields for your users.',
90    'page callback' => 'drupal_get_form',
91    'page arguments' => array('profile_admin_overview'),
92    'access arguments' => array('administer users'),
93    'file' => 'profile.admin.inc',
94  );
95  $items['admin/config/people/profile/add'] = array(
96    'title' => 'Add field',
97    'page callback' => 'drupal_get_form',
98    'page arguments' => array('profile_field_form'),
99    'access arguments' => array('administer users'),
100    'type' => MENU_VISIBLE_IN_BREADCRUMB,
101    'file' => 'profile.admin.inc',
102  );
103  $items['admin/config/people/profile/autocomplete'] = array(
104    'title' => 'Profile category autocomplete',
105    'page callback' => 'profile_admin_settings_autocomplete',
106    'access arguments' => array('administer users'),
107    'file' => 'profile.admin.inc',
108    'type' => MENU_CALLBACK,
109  );
110  $items['admin/config/people/profile/edit'] = array(
111    'title' => 'Edit field',
112    'page callback' => 'drupal_get_form',
113    'page arguments' => array('profile_field_form'),
114    'access arguments' => array('administer users'),
115    'type' => MENU_VISIBLE_IN_BREADCRUMB,
116    'file' => 'profile.admin.inc',
117  );
118  $items['admin/config/people/profile/delete'] = array(
119    'title' => 'Delete field',
120    'page callback' => 'drupal_get_form',
121    'page arguments' => array('profile_field_delete'),
122    'access arguments' => array('administer users'),
123    'type' => MENU_VISIBLE_IN_BREADCRUMB,
124    'file' => 'profile.admin.inc',
125  );
126  $items['profile/autocomplete'] = array(
127    'title' => 'Profile autocomplete',
128    'page callback' => 'profile_autocomplete',
129    'access arguments' => array('access user profiles'),
130    'file' => 'profile.pages.inc',
131    'type' => MENU_CALLBACK,
132  );
133  return $items;
134}
135
136/**
137 * Implements hook_block_info().
138 */
139 function profile_block_info() {
140  $blocks['author-information']['info'] = t('Author information');
141  $blocks['author-information']['cache'] = DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE;
142  return $blocks;
143}
144
145/**
146 * Implements hook_block_configure().
147 */
148function profile_block_configure($delta = '') {
149  // Compile a list of fields to show
150  $fields = array();
151  $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)));
152  foreach ($result as $record) {
153    $fields[$record->name] = check_plain($record->title);
154  }
155  $fields['user_profile'] = t('Link to full user profile');
156  $form['profile_block_author_fields'] = array(
157    '#type' => 'checkboxes',
158    '#title' => t('Profile fields to display'),
159    '#default_value' => variable_get('profile_block_author_fields', array()),
160    '#options' => $fields,
161    '#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'))),
162  );
163  return $form;
164}
165
166/**
167 * Implements hook_block_save().
168 */
169function profile_block_save($delta = '', $edit = array()) {
170  variable_set('profile_block_author_fields', $edit['profile_block_author_fields']);
171}
172
173/**
174 * Implements hook_block_view().
175 */
176function profile_block_view($delta = '') {
177  if (user_access('access user profiles')) {
178    $output = '';
179    if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL) {
180      $node = node_load(arg(1));
181      $account = user_load($node->uid);
182
183      if ($use_fields = variable_get('profile_block_author_fields', array())) {
184        // Compile a list of fields to show.
185        $fields = array();
186        $result = db_query('SELECT * FROM {profile_field} WHERE visibility IN (:visibility) ORDER BY weight', array(':visibility' => array(PROFILE_PUBLIC, PROFILE_PUBLIC_LISTINGS)));
187        foreach ($result as $record) {
188          // Ensure that field is displayed only if it is among the defined block fields and, if it is private, the user has appropriate permissions.
189          if (isset($use_fields[$record->name]) && $use_fields[$record->name]) {
190            $fields[] = $record;
191          }
192        }
193      }
194
195      if (!empty($fields)) {
196        $profile = _profile_update_user_fields($fields, $account);
197        $output .= theme('profile_block', array('account' => $account, 'fields' => $profile));
198      }
199
200      if (isset($use_fields['user_profile']) && $use_fields['user_profile']) {
201        $output .= '<div>' . l(t('View full user profile'), 'user/' . $account->uid) . '</div>';
202      }
203    }
204
205    if ($output) {
206      $block['subject'] = t('About %name', array('%name' => format_username($account)));
207      $block['content'] = $output;
208      return $block;
209    }
210  }
211}
212
213/**
214 * Implements hook_user_presave().
215 */
216function profile_user_presave(&$edit, $account, $category) {
217  if (!empty($account->uid)) {
218    profile_save_profile($edit, $account, $category);
219  }
220}
221
222/**
223 * Implements hook_user_insert().
224 */
225function profile_user_insert(&$edit, $account, $category) {
226  profile_save_profile($edit, $account, $category, TRUE);
227}
228
229/**
230 * Implements hook_user_cancel().
231 */
232function profile_user_cancel($edit, $account, $method) {
233  switch ($method) {
234    case 'user_cancel_reassign':
235      db_delete('profile_value')
236        ->condition('uid', $account->uid)
237        ->execute();
238  }
239}
240
241/**
242 * Implements hook_user_delete().
243 */
244function profile_user_delete($account) {
245  db_delete('profile_value')
246    ->condition('uid', $account->uid)
247    ->execute();
248}
249
250/**
251 * Implements hook_user_load().
252 */
253function profile_user_load($users) {
254  $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)));
255  foreach ($result as $record) {
256    if (empty($users[$record->uid]->{$record->name})) {
257      $users[$record->uid]->{$record->name} = _profile_field_serialize($record->type) ? unserialize($record->value) : $record->value;
258    }
259  }
260}
261
262function profile_save_profile(&$edit, $account, $category, $register = FALSE) {
263  $result = _profile_get_fields($category, $register);
264  foreach ($result as $field) {
265    if (_profile_field_serialize($field->type)) {
266      $edit[$field->name] = serialize($edit[$field->name]);
267    }
268    db_merge('profile_value')
269      ->key(array(
270        'fid' => $field->fid,
271        'uid' => $account->uid,
272      ))
273      ->fields(array('value' => $edit[$field->name]))
274      ->execute();
275  }
276}
277
278function profile_view_field($account, $field) {
279  // Only allow browsing of private fields for admins, if browsing is enabled,
280  // and if a user has permission to view profiles. Note that this check is
281  // necessary because a user may always see their own profile.
282  $browse = user_access('access user profiles')
283        && (user_access('administer users') || $field->visibility != PROFILE_PRIVATE)
284        && !empty($field->page);
285
286  if (isset($account->{$field->name}) && $value = $account->{$field->name}) {
287    switch ($field->type) {
288      case 'textarea':
289        return check_markup($value, filter_default_format($account), '', TRUE);
290      case 'textfield':
291      case 'selection':
292        return $browse ? l($value, 'profile/' . $field->name . '/' . $value) : check_plain($value);
293      case 'checkbox':
294        return $browse ? l($field->title, 'profile/' . $field->name) : check_plain($field->title);
295      case 'url':
296        return '<a href="' . check_url($value) . '">' . check_plain($value) . '</a>';
297      case 'date':
298        $format = substr(variable_get('date_format_short', 'm/d/Y - H:i'), 0, 5);
299        // Note: Avoid PHP's date() because it does not handle dates before
300        // 1970 on Windows. This would make the date field useless for e.g.
301        // birthdays.
302        $replace = array(
303          'd' => sprintf('%02d', $value['day']),
304          'j' => $value['day'],
305          'm' => sprintf('%02d', $value['month']),
306          'M' => map_month($value['month']),
307          'Y' => $value['year'],
308          'H:i' => NULL,
309          'g:ia' => NULL,
310        );
311        return strtr($format, $replace);
312      case 'list':
313        $values = preg_split("/[,\n\r]/", $value);
314        $fields = array();
315        foreach ($values as $value) {
316          if ($value = trim($value)) {
317            $fields[] = $browse ? l($value, 'profile/' . $field->name . '/' . $value) : check_plain($value);
318          }
319        }
320        return implode(', ', $fields);
321    }
322  }
323}
324
325/**
326 * Implements hook_user_view().
327 */
328function profile_user_view($account) {
329  // Show private fields to administrators and people viewing their own account.
330  if (user_access('administer users') || $GLOBALS['user']->uid == $account->uid) {
331    $result = db_query('SELECT * FROM {profile_field} WHERE visibility <> :hidden ORDER BY category, weight', array(':hidden' => PROFILE_HIDDEN));
332  }
333  else {
334    $result = db_query('SELECT * FROM {profile_field} WHERE visibility <> :private AND visibility <> :hidden ORDER BY category, weight', array(':private' => PROFILE_PRIVATE, ':hidden' => PROFILE_HIDDEN));
335  }
336
337  $fields = array();
338  foreach ($result as $field) {
339    if ($value = profile_view_field($account, $field)) {
340      $title = ($field->type != 'checkbox') ? check_plain($field->title) : NULL;
341
342      // Create a single fieldset for each category.
343      if (!isset($account->content[$field->category])) {
344        $account->content[$field->category] = array(
345          '#type' => 'user_profile_category',
346          '#title' => $field->category,
347        );
348      }
349
350      $account->content[$field->category][$field->name] = array(
351        '#type' => 'user_profile_item',
352        '#title' => $title,
353        '#markup' => $value,
354        '#weight' => $field->weight,
355        '#attributes' => array('class' => array('profile-' . $field->name)),
356      );
357    }
358  }
359}
360
361function _profile_form_explanation($field) {
362  $output = filter_xss_admin($field->explanation);
363
364  if ($field->type == 'list') {
365    $output .= ' ' . t('Put each item on a separate line or separate them by commas. No HTML allowed.');
366  }
367
368  if ($field->visibility == PROFILE_PRIVATE) {
369    $output .= ' ' . t('The content of this field is kept private and will not be shown publicly.');
370  }
371
372  return $output;
373}
374
375/**
376 * Implements hook_form_alter().
377 */
378function profile_form_alter(&$form, &$form_state, $form_id) {
379  if (!($form_id == 'user_register_form' || $form_id == 'user_profile_form')) {
380    return;
381  }
382  $form['#validate'][] = 'profile_user_form_validate';
383  $account = $form['#user'];
384  $result = _profile_get_fields($form['#user_category'], $form['#user_category'] == 'register');
385  $weight = 1;
386  foreach ($result as $field) {
387    $category = $field->category;
388    if (!isset($form[$category])) {
389      $form[$category] = array('#type' => 'fieldset', '#title' => check_plain($category), '#weight' => $weight++);
390    }
391    switch ($field->type) {
392      case 'textfield':
393      case 'url':
394        $form[$category][$field->name] = array(
395          '#type' => 'textfield',
396          '#title' => check_plain($field->title),
397          '#default_value' => isset($account->{$field->name}) ? $account->{$field->name} : '',
398          '#maxlength' => 255,
399          '#description' => _profile_form_explanation($field),
400          '#required' => $field->required,
401        );
402        if ($field->autocomplete) {
403          $form[$category][$field->name]['#autocomplete_path'] = "profile/autocomplete/" . $field->fid;
404        }
405        break;
406
407      case 'textarea':
408        $form[$category][$field->name] = array(
409          '#type' => 'textarea',
410          '#title' => check_plain($field->title),
411          '#default_value' => isset($account->{$field->name}) ? $account->{$field->name} : '',
412          '#description' => _profile_form_explanation($field),
413          '#required' => $field->required,
414        );
415        break;
416
417      case 'list':
418        $form[$category][$field->name] = array(
419          '#type' => 'textarea',
420          '#title' => check_plain($field->title),
421          '#default_value' => isset($account->{$field->name}) ? $account->{$field->name} : '',
422          '#description' => _profile_form_explanation($field),
423          '#required' => $field->required,
424        );
425        break;
426
427      case 'checkbox':
428        $form[$category][$field->name] = array(
429          '#type' => 'checkbox',
430          '#title' => check_plain($field->title),
431          '#default_value' => isset($account->{$field->name}) ? $account->{$field->name} : '',
432          '#description' => _profile_form_explanation($field),
433          '#required' => $field->required,
434        );
435        break;
436
437      case 'selection':
438        $options = array();
439        $lines = preg_split("/[\n\r]/", $field->options);
440        foreach ($lines as $line) {
441          if ($line = trim($line)) {
442            $options[$line] = $line;
443          }
444        }
445        $form[$category][$field->name] = array(
446          '#type' => 'select',
447          '#title' => check_plain($field->title),
448          '#default_value' => isset($account->{$field->name}) ? $account->{$field->name} : '',
449          '#options' => $options,
450          '#description' => _profile_form_explanation($field),
451          '#required' => $field->required,
452          '#empty_value' => 0,
453        );
454        break;
455
456      case 'date':
457        $form[$category][$field->name] = array(
458          '#type' => 'date',
459          '#title' => check_plain($field->title),
460          '#default_value' => isset($account->{$field->name}) ? $account->{$field->name} : '',
461          '#description' => _profile_form_explanation($field),
462          '#required' => $field->required,
463        );
464        break;
465    }
466  }
467}
468
469/**
470 * Helper function: update an array of user fields by calling profile_view_field
471 */
472function _profile_update_user_fields($fields, $account) {
473  foreach ($fields as $key => $field) {
474    $fields[$key]->value = profile_view_field($account, $field);
475  }
476  return $fields;
477}
478
479/**
480 * Form validation handler for the user register/profile form.
481 *
482 * @see profile_form_alter()
483 */
484function profile_user_form_validate($form, &$form_state) {
485  $result = _profile_get_fields($form['#user_category'], $form['#user_category'] == 'register');
486  foreach ($result as $field) {
487    if (!empty($form_state['values'][$field->name])) {
488      if ($field->type == 'url' && !valid_url($form_state['values'][$field->name], TRUE)) {
489        form_set_error($field->name, t('The value provided for %field is not a valid URL.', array('%field' => $field->title)));
490      }
491    }
492    elseif ($field->required && !user_access('administer users')) {
493      form_set_error($field->name, t('The field %field is required.', array('%field' => $field->title)));
494    }
495  }
496}
497
498/**
499 * Implements hook_user_categories().
500 */
501function profile_user_categories() {
502  $result = db_query("SELECT DISTINCT(category) FROM {profile_field}");
503  $data = array();
504  foreach ($result as $category) {
505    $data[] = array(
506      'name' => $category->category,
507      'title' => $category->category,
508      'weight' => 3,
509      'access callback' => 'profile_category_access',
510      'access arguments' => array(1, $category->category)
511    );
512  }
513  return $data;
514}
515
516/**
517 * Menu item access callback - check if a user has access to a profile category.
518 */
519function profile_category_access($account, $category) {
520  if (user_access('administer users') && $account->uid > 0) {
521    return TRUE;
522  }
523  else {
524    $category_visible = (bool) db_query_range('SELECT 1 FROM {profile_field} WHERE category = :category AND visibility <> :visibility', 0, 1, array(
525      ':category' => $category,
526      ':visibility' => PROFILE_HIDDEN
527    ))->fetchField();
528    return user_edit_access($account) && $category_visible;
529  }
530}
531
532/**
533 * Process variables for profile-block.tpl.php.
534 *
535 * The $variables array contains the following arguments:
536 * - $account
537 * - $fields
538 *
539 * @see profile-block.tpl.php
540 */
541function template_preprocess_profile_block(&$variables) {
542
543  $variables['user_picture'] = theme('user_picture', array('account' => $variables['account']));
544  $variables['profile'] = array();
545  // Supply filtered version of $fields that have values.
546  foreach ($variables['fields'] as $field) {
547    if ($field->value) {
548      $variables['profile'][$field->name] = new stdClass();
549      $variables['profile'][$field->name]->title = check_plain($field->title);
550      $variables['profile'][$field->name]->value = $field->value;
551      $variables['profile'][$field->name]->type = $field->type;
552    }
553  }
554
555}
556
557/**
558 * Process variables for profile-listing.tpl.php.
559 *
560 * The $variables array contains the following arguments:
561 * - $account
562 * - $fields
563 *
564 * @see profile-listing.tpl.php
565 */
566function template_preprocess_profile_listing(&$variables) {
567
568  $variables['user_picture'] = theme('user_picture', array('account' => $variables['account']));
569  $variables['name'] = theme('username', array('account' => $variables['account']));
570  $variables['profile'] = array();
571  // Supply filtered version of $fields that have values.
572  foreach ($variables['fields'] as $field) {
573    if ($field->value) {
574      $variables['profile'][$field->name] = new stdClass();
575      $variables['profile'][$field->name]->title = $field->title;
576      $variables['profile'][$field->name]->value = $field->value;
577      $variables['profile'][$field->name]->type = $field->type;
578    }
579  }
580
581}
582
583/**
584 * Process variables for profile-wrapper.tpl.php.
585 *
586 * The $variables array contains the following arguments:
587 * - $content
588 *
589 * @see profile-wrapper.tpl.php
590 */
591function template_preprocess_profile_wrapper(&$variables) {
592  $variables['current_field'] = '';
593  if ($field = arg(1)) {
594    $variables['current_field'] = $field;
595    $variables['theme_hook_suggestions'][] = 'profile_wrapper__' . $field;
596  }
597}
598
599function _profile_field_types($type = NULL) {
600  $types = array('textfield' => t('single-line textfield'),
601                 'textarea' => t('multi-line textfield'),
602                 'checkbox' => t('checkbox'),
603                 'selection' => t('list selection'),
604                 'list' => t('freeform list'),
605                 'url' => t('URL'),
606                 'date' => t('date'));
607  return isset($type) ? $types[$type] : $types;
608}
609
610function _profile_field_serialize($type = NULL) {
611  return $type == 'date';
612}
613
614function _profile_get_fields($category, $register = FALSE) {
615  $query = db_select('profile_field');
616  if ($register) {
617    $query->condition('register', 1);
618  }
619  else {
620    $query->condition('category', db_like($category), 'LIKE');
621  }
622  if (!user_access('administer users')) {
623    $query->condition('visibility', PROFILE_HIDDEN, '<>');
624  }
625  return $query
626    ->fields('profile_field')
627    ->orderBy('category', 'ASC')
628    ->orderBy('weight', 'ASC')
629    ->execute();
630}
631