profile.module 32.3 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
Dries's avatar
Dries committed
2
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
   
Dries committed
4
5
6
7
8
/**
 * @file
 * Support for configurable user profiles.
 */

9
10
11
12
13
14
/**
 * Flags to define the visibility of a profile field.
 */
define('PROFILE_PRIVATE', 1);
define('PROFILE_PUBLIC', 2);
define('PROFILE_PUBLIC_LISTINGS', 3);
15
define('PROFILE_HIDDEN', 4);
16

Dries's avatar
   
Dries committed
17
18
19
/**
 * Implementation of hook_help().
 */
Dries's avatar
   
Dries committed
20
function profile_help($section) {
Dries's avatar
   
Dries committed
21
  switch ($section) {
22
    case 'admin/help#profile':
23
      $output = '<p>'. t('The profile module allows you to define custom fields (such as country, real name, age, ...) in the user profile. This permits users of a site to share more information about themselves, and can help community-based sites to organize users around profile fields.') .'</p>';
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
      $output .= t('<p>The following types of fields can be added to the user profile:</p>
<ul>
<li>single-line textfield</li>
<li>multi-line textfield</li>
<li>checkbox</li>
<li>list selection</li>
<li>freeform list</li>
<li>URL</li>
<li>date</li>
</ul>
');
      $output .= t('<p>You can</p>
<ul>
<li>view user <a href="%profile">profiles</a>.</li>
<li>administer profile settings: <a href="%admin-settings-profile">administer &gt;&gt; settings &gt;&gt; profiles</a>.</li>
</ul>
', array('%profile' => url('profile'), '%admin-settings-profile' => url('admin/settings/profile')));
41
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%profile">Profile page</a>.', array('%profile' => 'http://drupal.org/handbook/modules/profile/')) .'</p>';
42
      return $output;
Dries's avatar
   
Dries committed
43
    case 'admin/modules#description':
44
      return t('Supports configurable user profiles.');
45
    case 'admin/settings/profile':
46
      return t('<p>Here you can define custom fields that users can fill in in their user profile (such as <em>country</em>, <em>real name</em>, <em>age</em>, ...).</p>');
Dries's avatar
   
Dries committed
47
48
49
  }
}

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
 * Implementation of hook_menu().
 */
function profile_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array('path' => 'profile',
      'title' => t('user list'),
      'callback' => 'profile_browse',
      'access' => user_access('access user profiles'),
      'type' => MENU_SUGGESTED_ITEM);
    $items[] = array('path' => 'admin/settings/profile',
      'title' => t('profiles'),
      'callback' => 'profile_admin_overview');
    $items[] = array('path' => 'admin/settings/profile/add',
      'title' => t('add field'),
67
      'callback' => 'profile_field_form',
68
      'type' => MENU_CALLBACK);
69
70
71
72
73
    $items[] = array('path' => 'admin/settings/profile/autocomplete',
      'title' => t('profile category autocomplete'),
      'callback' => 'profile_admin_settings_autocomplete',
      'access' => user_access('administer users'),
      'type' => MENU_CALLBACK);
74
75
    $items[] = array('path' => 'admin/settings/profile/edit',
      'title' => t('edit field'),
76
      'callback' => 'profile_field_form',
77
78
79
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/settings/profile/delete',
      'title' => t('delete field'),
80
      'callback' => 'profile_field_delete',
81
82
83
84
85
86
      'type' => MENU_CALLBACK);
  }

  return $items;
}

87
88
89
90
91
92
93
94
95
96
97
98
99
/**
 * Implementation of hook_block().
 */
function profile_block($op = 'list', $delta = 0, $edit = array()) {

  if ($op == 'list') {
     $blocks[0]['info'] = t('Author information');

     return $blocks;
  }
  else if ($op == 'configure' && $delta == 0) {
    // Compile a list of fields to show
    $fields = array();
100
    $result = db_query('SELECT name, title, weight, visibility FROM {profile_fields} WHERE visibility IN (%d, %d) ORDER BY weight', PROFILE_PUBLIC, PROFILE_PUBLIC_LISTINGS);
101
102
103
104
    while ($record = db_fetch_object($result)) {
      $fields[$record->name] = $record->title;
    }
    $fields['user_profile'] = t('Link to full user profile');
105
106
107
108
109
110
    $form['profile_block_author_fields'] = array('#type' => 'checkboxes',
      '#title' => t('Profile fields to display'),
      '#default_value' => variable_get('profile_block_author_fields', NULL),
      '#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/settings/profile'))),
    );
111
    return $form;
112
113
114
115
116
117
118
  }
  else if ($op == 'save' && $delta == 0) {
    variable_set('profile_block_author_fields', $edit['profile_block_author_fields']);
  }
  else if ($op == 'view') {
    if (user_access('access user profiles')) {
      if ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == NULL)) {
119
        $node = node_load(arg(1));
120
121
122
        $account = user_load(array('uid' => $node->uid));

        if ($use_fields = variable_get('profile_block_author_fields', array())) {
123
          // Compile a list of fields to show.
124
          $fields = array();
125
126
127
          $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);
          while ($record = db_fetch_object($result)) {
            // Ensure that field is displayed only if it is among the defined block fields and, if it is private, the user has appropriate permissions.
128
            if (isset($use_fields[$record->name]) && $use_fields[$record->name]) {
129
130
131
132
133
134
              $fields[] = $record;
            }
          }
        }

        if ($fields) {
135
          $fields = _profile_update_user_fields($fields, $account);
136
137
138
          $output .= theme('profile_block', $account, $fields, true);
        }

139
        if (isset($use_fields['user_profile']) && $use_fields['user_profile']) {
140
141
142
143
144
145
146
147
148
149
150
151
152
          $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;
      }
    }
  }
}

Dries's avatar
   
Dries committed
153
/**
154
 * Implementation of hook_user().
Dries's avatar
   
Dries committed
155
 */
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
function profile_user($type, &$edit, &$user, $category = NULL) {
  switch ($type) {
    case 'load':
      return profile_load_profile($user);
    case 'register':
      return profile_form_profile($edit, $user, $category);
    case 'update':
    case 'insert':
      return profile_save_profile($edit, $user, $category);
    case 'view':
      return profile_view_profile($user);
    case 'form':
      return profile_form_profile($edit, $user, $category);
    case 'validate':
      return profile_validate_profile($edit, $category);
    case 'categories':
      return profile_categories();
173
174
    case 'delete':
      db_query('DELETE FROM {profile_values} WHERE uid = %d', $user->uid);
175
176
  }
}
Dries's avatar
   
Dries committed
177

178
/**
179
 * Menu callback: Generate a form to add/edit a user profile field.
180
 */
181
182
183
184
function profile_field_form($arg = NULL) {
  if (arg(3) == 'edit') {
    if (is_numeric($arg)) {
      $fid = $arg;
185

186
      $edit = db_fetch_array(db_query('SELECT * FROM {profile_fields} WHERE fid = %d', $fid));
187

188
189
190
191
192
193
194
195
      if (!$edit) {
        drupal_not_found();
        return;
      }
      drupal_set_title(t('edit %title', array('%title' => $edit['title'])));
      $form['fid'] = array('#type' => 'value',
        '#value' => $fid,
      );
196
      $type = $edit['type'];
197
    }
198
199
200
    else {
      drupal_not_found();
      return;
201
202
203
    }
  }
  else {
204
205
206
207
    $types = _profile_field_types();
    if (!isset($types[$arg])) {
      drupal_not_found();
      return;
208
    }
209
210
211
212
    $type = $arg;
    drupal_set_title(t('add new %type', array('%type' => $types[$type])));
    $edit = array('name' => 'profile_');
    $form['type'] = array('#type' => 'value', '#value' => $type);
213
214
215
216
217
218
219
  }
  $form['fields'] = array('#type' => 'fieldset',
    '#title' => t('Field settings'),
  );
  $form['fields']['category'] = array('#type' => 'textfield',
    '#title' => t('Category'),
    '#default_value' => $edit['category'],
220
    '#autocomplete_path' => 'admin/settings/profile/autocomplete',
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
    '#description' => t('The category the new field should be part of. Categories are used to group fields logically. An example category is "Personal information".'),
    '#required' => TRUE,
  );
  $form['fields']['title'] = array('#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $edit['title'],
    '#description' => t('The title of the new field. The title will be shown to the user. An example title is "Favorite color".'),
    '#required' => TRUE,
  );
  $form['fields']['name'] = array('#type' => 'textfield',
    '#title' => t('Form name'),
    '#default_value' => $edit['name'],
    '#description' => t('The name of the field. The form name is not shown to the user but used internally in the HTML code and URLs.
Unless you know what you are doing, it is highly recommended that you prefix the form name with <code>profile_</code> to avoid name clashes with other fields. Spaces or any other special characters except dash (-) and underscore (_) are not allowed. An example name is "profile_favorite_color" or perhaps just "profile_color".'),
    '#required' => TRUE,
  );
  $form['fields']['explanation'] = array('#type' => 'textarea',
    '#title' => t('Explanation'),
    '#default_value' => $edit['explanation'],
    '#description' => t('An optional explanation to go with the new field. The explanation will be shown to the user.'),
  );
  if ($type == 'selection') {
    $form['fields']['options'] = array('#type' => 'textarea',
      '#title' => t('Selection options'),
      '#default_value' => $edit['options'],
      '#description' => t('A list of all options. Put each option on a separate line. Example options are "red", "blue", "green", etc.'),
    );
  }
  $form['fields']['weight'] = array('#type' => 'weight',
    '#title' => t('Weight'),
    '#default_value' => $edit['weight'],
    '#delta' => 5,
    '#description' => t('The weights define the order in which the form fields are shown. Lighter fields "float up" towards the top of the category.'),
  );
  $form['fields']['visibility'] = array('#type' => 'radios',
    '#title' => t('Visibility'),
    '#default_value' => isset($edit['visibility']) ? $edit['visibility'] : PROFILE_PUBLIC,
    '#options' => array(PROFILE_HIDDEN => t('Hidden profile field, only accessible by administrators, modules and themes.'), PROFILE_PRIVATE => t('Private field, content only available to privileged users.'), PROFILE_PUBLIC => t('Public field, content shown on profile page but not used on member list pages.'), PROFILE_PUBLIC_LISTINGS => t('Public field, content shown on profile page and on member list pages.')),
  );
260
  if ($type == 'selection' || $type == 'list' || $type == 'textfield') {
261
262
263
    $form['fields']['page'] = array('#type' => 'textfield',
      '#title' => t('Page title'),
      '#default_value' => $edit['page'],
264
      '#description' => t('To enable browsing this field by value, enter a title for the resulting page. The word <code>%value</code> will be substituted with the corresponding value. An example page title is "People whose favorite color is %value". This is only applicable for a public field.'),
265
266
    );
  }
267
  else if ($type == 'checkbox') {
268
269
270
    $form['fields']['page'] = array('#type' => 'textfield',
      '#title' => t('Page title'),
      '#default_value' => $edit['page'],
271
      '#description' => t('To enable browsing this field by value, enter a title for the resulting page. An example page title is "People who are employed". This is only applicable for a public field.'),
272
273
274
275
276
277
278
279
280
281
282
283
284
    );
  }
  $form['fields']['required'] = array('#type' => 'checkbox',
    '#title' => t('The user must enter a value.'),
    '#default_value' => $edit['required'],
  );
  $form['fields']['register'] = array('#type' => 'checkbox',
    '#title' => t('Visible in user registration form.'),
    '#default_value' => $edit['register'],
  );
  $form['submit'] = array('#type' => 'submit',
    '#value' => t('Save field'),
  );
285
  return drupal_get_form('profile_field_form', $form);
286
287
}

288
289
290
291
292
293
/**
 * Validate profile_field_form submissions.
 */
function profile_field_form_validate($form_id, $form_values) {
  // Validate the 'field name':
  if (eregi('[^a-z0-9_-]', $form_values['name'])) {
294
295
296
    form_set_error('name', t('The specified form name contains one or more illegal characters. Spaces or any other special characters expect dash (-) and underscore (_) are not allowed.'));
  }

297
  if (in_array($form_values['name'], user_fields())) {
298
299
300
    form_set_error('name', t('The specified form name is reserved for use by Drupal.'));
  }
  // Validate the category:
301
  if (!$form_values['category']) {
302
303
    form_set_error('category', t('You must enter a category.'));
  }
304
  if ($form_values['category'] == 'account') {
305
306
    form_set_error('category', t('The specified category name is reserved for use by Drupal.'));
  }
307
308
309
  $args1 = array($form_values['title'], $form_values['category']);
  $args2 = array($form_values['name']);
  $query_suffix = '';
Dries's avatar
Dries committed
310

311
312
313
314
315
316
317
318
319
320
321
  if (isset($form_values['fid'])) {
    $args1[] = $args2[] = $form_values['fid'];
    $query_suffix = ' AND fid != %d';
  }

  if (db_result(db_query("SELECT fid FROM {profile_fields} WHERE title = '%s' AND category = '%s'". $query_suffix, $args1))) {
    form_set_error('title', t('The specified title is already in use.'));
  }
  if (db_result(db_query("SELECT fid FROM {profile_fields} WHERE name = '%s'". $query_suffix, $args2))) {
    form_set_error('name', t('The specified name is already in use.'));
  }
322
323
324
}

/**
325
 * Process profile_field_form submissions.
326
 */
327
328
329
function profile_field_form_submit($form_id, $form_values) {
  if (!isset($form_values['fid'])) {
    db_query("INSERT INTO {profile_fields} (title, name, explanation, category, type, weight, required, register, visibility, options, page) VALUES ('%s', '%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s', '%s')", $form_values['title'], $form_values['name'], $form_values['explanation'], $form_values['category'], $form_values['type'], $form_values['weight'], $form_values['required'], $form_values['register'], $form_values['visibility'], $form_values['options'], $form_values['page']);
Dries's avatar
Dries committed
330

331
332
    drupal_set_message(t('The field has been created.'));
    watchdog('profile', t('Profile field %field added under category %category.', array('%field' => theme('placeholder', $form_values['title']), '%category' => theme('placeholder', $form_values['category']))), WATCHDOG_NOTICE, l(t('view'), 'admin/settings/profile'));
333
334
  }
  else {
335
336
337
338
339
    db_query("UPDATE {profile_fields} SET title = '%s', name = '%s', explanation = '%s', category = '%s', weight = %d, required = %d, register = %d, visibility = %d, options = '%s', page = '%s' WHERE fid = %d", $form_values['title'], $form_values['name'], $form_values['explanation'], $form_values['category'], $form_values['weight'], $form_values['required'], $form_values['register'], $form_values['visibility'], $form_values['options'], $form_values['page'], $form_values['fid']);

    drupal_set_message(t('The field has been updated.'));
  }
  cache_clear_all();
Dries's avatar
Dries committed
340

341
342
343
344
345
346
347
348
349
350
351
  return 'admin/settings/profile';
}

/**
 * Menu callback; deletes a field from all user profiles.
 */
function profile_field_delete($fid) {
  $field = db_fetch_object(db_query("SELECT title FROM {profile_fields} WHERE fid = %d", $fid));
  if (!$field) {
    drupal_not_found();
    return;
352
  }
353
354
  $form['fid'] = array('#type' => 'value', '#value' => $fid);
  $form['title'] = array('#type' => 'value', '#value' => $field->title);
Dries's avatar
Dries committed
355

356
  return confirm_form('profile_field_delete', $form, t('Are you sure you want to delete the field %field?', array('%field' => theme('placeholder', $field->title))), 'admin/settings/profile', t('This action cannot be undone. If users have entered values into this field in their profile, these entries will also be deleted. If you want to keep the user-entered data, instead of deleting the field you may wish to <a href="%edit-field">edit this field</a> and change it to a %hidden-field so that it may only be accessed by administrators.', array('%edit-field' => url('admin/settings/profile/edit/' . $fid), '%hidden-field' => theme('placeholder', t('hidden profile field'))), t('Delete'), t('Cancel')));
357
358
359
360
361
362
363
364
}

/**
 * Process a field delete form submission.
 */
function profile_field_delete_submit($form_id, $form_values) {
  db_query('DELETE FROM {profile_fields} WHERE fid = %d', $form_values['fid']);
  db_query('DELETE FROM {profile_values} WHERE fid = %d', $form_values['fid']);
Dries's avatar
Dries committed
365

366
  cache_clear_all();
Dries's avatar
Dries committed
367

368
369
  drupal_set_message(t('The field %field has been deleted.', array('%field' => theme('placeholder', $form_values['title']))));
  watchdog('profile', t('Profile field %field deleted.', array('%field' => theme('placeholder', $form_values['title']))), WATCHDOG_NOTICE, l(t('view'), 'admin/settings/profile'));
Dries's avatar
Dries committed
370

371
  return 'admin/settings/profile';
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
}

/**
 * Menu callback; display a listing of all editable profile fields.
 */
function profile_admin_overview() {

  $result = db_query('SELECT * FROM {profile_fields} ORDER BY category, weight');
  $rows = array();
  while ($field = db_fetch_object($result)) {
    $rows[] = array(check_plain($field->title), $field->name, _profile_field_types($field->type), $field->category, l(t('edit'), "admin/settings/profile/edit/$field->fid"), l(t('delete'), "admin/settings/profile/delete/$field->fid"));
  }
  if (count($rows) == 0) {
    $rows[] = array(array('data' => t('No fields defined.'), 'colspan' => '6'));
  }

  $header = array(t('Title'), t('Name'), t('Type'), t('Category'), array('data' => t('Operations'), 'colspan' => '2'));

  $output  = theme('table', $header, $rows);
  $output .= '<h2>'. t('Add new field') .'</h2>';
  $output .= '<ul>';
  foreach (_profile_field_types() as $key => $value) {
    $output .= '<li>'. l($value, "admin/settings/profile/add/$key") .'</li>';
  }
  $output .= '</ul>';

  return $output;
Dries's avatar
   
Dries committed
399
}
Dries's avatar
 
Dries committed
400

Dries's avatar
   
Dries committed
401
402
403
/**
 * Menu callback; display a list of user information.
 */
Dries's avatar
   
Dries committed
404
function profile_browse() {
Dries's avatar
   
Dries committed
405

Steven Wittens's avatar
Steven Wittens committed
406
  $name = arg(1);
407
  list(,,$value) = explode('/', $_GET['q'], 3);
Dries's avatar
   
Dries committed
408

Steven Wittens's avatar
Steven Wittens committed
409
  $field = db_fetch_object(db_query("SELECT DISTINCT(fid), type, title, page, visibility FROM {profile_fields} WHERE name = '%s'", $name));
Dries's avatar
 
Dries committed
410

Dries's avatar
   
Dries committed
411
  if ($name && $field->fid) {
412
413
414
415
416
    // Only allow browsing of fields that have a page title set.
    if (empty($field->page)) {
      drupal_not_found();
      return;
    }
417
    // Do not allow browsing of private fields by non-admins.
Steven Wittens's avatar
Steven Wittens committed
418
419
420
421
422
    if (!user_access('administer users') && $field->visibility == PROFILE_PRIVATE) {
       drupal_access_denied();
       return;
    }

423
    // Compile a list of fields to show.
Dries's avatar
   
Dries committed
424
    $fields = array();
425
    $result = db_query('SELECT name, title, type, weight FROM {profile_fields} WHERE fid != %d AND visibility = %d ORDER BY weight', $field->fid, PROFILE_PUBLIC_LISTINGS);
Dries's avatar
   
Dries committed
426
427
428
    while ($record = db_fetch_object($result)) {
      $fields[] = $record;
    }
Dries's avatar
 
Dries committed
429

Dries's avatar
Dries committed
430
    // Determine what query to use:
431
    $arguments = array($field->fid);
Dries's avatar
Dries committed
432
433
434
435
    switch ($field->type) {
      case 'checkbox':
        $query = 'v.value = 1';
        break;
436
      case 'textfield':
Dries's avatar
Dries committed
437
      case 'selection':
438
439
        $query = "v.value = '%s'";
        $arguments[] = $value;
Dries's avatar
Dries committed
440
441
        break;
      case 'list':
442
443
        $query = "v.value LIKE '%%%s%%'";
        $arguments[] = $value;
Dries's avatar
Dries committed
444
        break;
Steven Wittens's avatar
Steven Wittens committed
445
446
447
      default:
        drupal_not_found();
        return;
Dries's avatar
Dries committed
448
449
    }

Dries's avatar
   
Dries committed
450
    // Extract the affected users:
451
    $result = pager_query("SELECT u.uid, u.access FROM {users} u INNER JOIN {profile_values} v ON u.uid = v.uid WHERE v.fid = %d AND $query ORDER BY u.access DESC", 20, 0, NULL, $arguments);
Dries's avatar
 
Dries committed
452

Dries's avatar
   
Dries committed
453
    $output = '<div id="profile">';
Dries's avatar
   
Dries committed
454
    while ($account = db_fetch_object($result)) {
455
      $account = user_load(array('uid' => $account->uid));
456
457
      $profile = _profile_update_user_fields($fields, $account);
      $output .= theme('profile_listing', $account, $profile);
Dries's avatar
   
Dries committed
458
459
460
    }
    $output .= theme('pager', NULL, 20);

461
    if ($field->type == 'selection' || $field->type == 'list' || $field->type == 'textfield') {
462
      $title = strtr($field->page, array('%value' => theme('placeholder', $value)));
Dries's avatar
   
Dries committed
463
464
    }
    else {
Dries's avatar
   
Dries committed
465
      $title = $field->page;
Dries's avatar
   
Dries committed
466
    }
Dries's avatar
   
Dries committed
467
    $output .= '</div>';
Dries's avatar
   
Dries committed
468

469
    drupal_set_title($title);
Dries's avatar
   
Dries committed
470
    return $output;
Dries's avatar
   
Dries committed
471
  }
472
  else if ($name && !$field->fid) {
Dries's avatar
   
Dries committed
473
    drupal_not_found();
Dries's avatar
 
Dries committed
474
  }
Dries's avatar
   
Dries committed
475
  else {
476
    // Compile a list of fields to show.
Dries's avatar
   
Dries committed
477
    $fields = array();
478
    $result = db_query('SELECT name, title, type, weight FROM {profile_fields} WHERE visibility = %d ORDER BY category, weight', PROFILE_PUBLIC_LISTINGS);
Dries's avatar
   
Dries committed
479
480
481
482
483
    while ($record = db_fetch_object($result)) {
      $fields[] = $record;
    }

    // Extract the affected users:
484
    $result = pager_query("SELECT uid, access FROM {users} WHERE uid > 0 AND status != 0 ORDER BY access DESC", 20, 0, NULL);
Dries's avatar
   
Dries committed
485
486
487

    $output = '<div id="profile">';
    while ($account = db_fetch_object($result)) {
488
      $account = user_load(array('uid' => $account->uid));
489
490
      $profile = _profile_update_user_fields($fields, $account);
      $output .= theme('profile_listing', $account, $profile);
Dries's avatar
   
Dries committed
491
492
493
494
    }
    $output .= '</div>';
    $output .= theme('pager', NULL, 20);

495
    drupal_set_title(t('user list'));
Dries's avatar
   
Dries committed
496
    return $output;
Dries's avatar
   
Dries committed
497
  }
Dries's avatar
   
Dries committed
498
}
Dries's avatar
 
Dries committed
499

Dries's avatar
   
Dries committed
500
function profile_load_profile(&$user) {
Steven Wittens's avatar
Steven Wittens committed
501
  $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);
Dries's avatar
   
Dries committed
502
503
  while ($field = db_fetch_object($result)) {
    if (empty($user->{$field->name})) {
Steven Wittens's avatar
Steven Wittens committed
504
      $user->{$field->name} = _profile_field_serialize($field->type) ? unserialize($field->value) : $field->value;
Dries's avatar
   
Dries committed
505
    }
Dries's avatar
   
Dries committed
506
  }
Dries's avatar
 
Dries committed
507
508
}

509
function profile_save_profile(&$edit, &$user, $category) {
510
  if ((arg(0) == 'user' && arg(1) == 'register') || (arg(0) == 'admin' && arg(1) == 'user' && arg(2) == 'create')) {
511
    $result = db_query('SELECT fid, name, type FROM {profile_fields} WHERE register = 1 AND visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);
Dries's avatar
   
Dries committed
512
513
  }
  else {
514
    $result = db_query("SELECT fid, name, type FROM {profile_fields} WHERE LOWER(category) = LOWER('%s') AND visibility != %d", $category, PROFILE_HIDDEN);
515
    // Use LOWER('%s') instead of PHP's strtolower() to avoid UTF-8 conversion issues.
Dries's avatar
   
Dries committed
516
  }
Dries's avatar
   
Dries committed
517
  while ($field = db_fetch_object($result)) {
Steven Wittens's avatar
Steven Wittens committed
518
519
520
    if (_profile_field_serialize($field->type)) {
       $edit[$field->name] = serialize($edit[$field->name]);
    }
521
522
    db_query("DELETE FROM {profile_values} WHERE fid = %d AND uid = %d", $field->fid, $user->uid);
    db_query("INSERT INTO {profile_values} (fid, uid, value) VALUES (%d, %d, '%s')", $field->fid, $user->uid, $edit[$field->name]);
523
    // Mark field as handled (prevents saving to user->data).
524
    $edit[$field->name] = NULL;
Dries's avatar
   
Dries committed
525
  }
Dries's avatar
 
Dries committed
526
527
}

528
function profile_view_field($user, $field) {
529
530
531
532
533
534
  // 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);
Steven Wittens's avatar
Steven Wittens committed
535

536
537
538
  if ($value = $user->{$field->name}) {
    switch ($field->type) {
      case 'textarea':
539
        return check_markup($value);
540
      case 'textfield':
541
      case 'selection':
542
        return $browse ? l($value, 'profile/'. $field->name .'/'. $value) : check_plain($value);
543
      case 'checkbox':
544
        return $browse ? l($field->title, 'profile/'. $field->name) : check_plain($field->title);
545
      case 'url':
546
        return '<a href="'. check_url($value) .'">'. check_plain($value) .'</a>';
Steven Wittens's avatar
Steven Wittens committed
547
      case 'date':
548
        $format = substr(variable_get('date_format_short', 'm/d/Y - H:i'), 0, 5);
549
        // Note: Avoid PHP's date() because it does not handle dates before
Steven Wittens's avatar
Steven Wittens committed
550
551
552
553
554
        // 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']),
555
                         'M' => map_month($value['month']),
556
557
558
                         'Y' => $value['year'],
                         'H:i' => null,
                         'g:ia' => null);
Steven Wittens's avatar
Steven Wittens committed
559
        return strtr($format, $replace);
560
      case 'list':
Dries's avatar
   
Dries committed
561
        $values = split("[,\n\r]", $value);
Dries's avatar
Dries committed
562
563
        $fields = array();
        foreach ($values as $value) {
Steven Wittens's avatar
Steven Wittens committed
564
          if ($value = trim($value)) {
565
            $fields[] = $browse ? l($value, 'profile/'. $field->name .'/'. $value) : check_plain($value);
Dries's avatar
Dries committed
566
567
568
          }
        }
        return implode(', ', $fields);
569
570
571
572
    }
  }
}

Dries's avatar
   
Dries committed
573
function profile_view_profile($user) {
Dries's avatar
 
Dries committed
574

575
  profile_load_profile($user);
Dries's avatar
 
Dries committed
576

Steven Wittens's avatar
Steven Wittens committed
577
578
  // Show private fields to administrators and people viewing their own account.
  if (user_access('administer users') || $GLOBALS['user']->uid == $user->uid) {
579
    $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);
Steven Wittens's avatar
Steven Wittens committed
580
581
  }
  else {
582
    $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND visibility != %d ORDER BY category, weight', PROFILE_PRIVATE, PROFILE_HIDDEN);
Steven Wittens's avatar
Steven Wittens committed
583
584
  }

Dries's avatar
   
Dries committed
585
  while ($field = db_fetch_object($result)) {
586
    if ($value = profile_view_field($user, $field)) {
Steven Wittens's avatar
Steven Wittens committed
587
      $description = ($field->visibility == PROFILE_PRIVATE) ? t('The content of this field is private and only visible to yourself.') : '';
588
      $title = ($field->type != 'checkbox') ? check_plain($field->title) : NULL;
589
590
591
592
593
      $item = array('title' => $title,
        'value' => $value,
        'class' => $field->name,
      );
      $fields[$field->category][] = $item;
Dries's avatar
 
Dries committed
594
595
    }
  }
Dries's avatar
Dries committed
596
  return $fields;
Dries's avatar
   
Dries committed
597
}
Dries's avatar
 
Dries committed
598

599
600
function _profile_form_explanation($field) {
  $output = $field->explanation;
Dries's avatar
   
Dries committed
601

602
  if ($field->type == 'list') {
603
    $output .= ' '. t('Put each item on a separate line or separate them by commas. No HTML allowed.');
604
605
606
607
608
609
610
611
612
613
  }

  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, $user, $category) {
614
  if (arg(0) == 'user' && arg(1) == 'register') {
615
    $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND register = 1 ORDER BY category, weight', PROFILE_HIDDEN);
Dries's avatar
   
Dries committed
616
  }
617
  elseif (arg(0) == 'admin' && arg(1) == 'user' && arg(2) == 'create') {
618
619
    $result = db_query('SELECT * FROM {profile_fields} WHERE register = 1 ORDER BY category, weight');
  }
620
  elseif (user_access('administer users')) {
621
    $result = db_query("SELECT * FROM {profile_fields} WHERE LOWER(category) = LOWER('%s') ORDER BY weight", $category);
Dries's avatar
   
Dries committed
622
  }
623
624
  else {
    $result = db_query("SELECT * FROM {profile_fields} WHERE visibility != %d AND LOWER(category) = LOWER('%s') ORDER BY weight", PROFILE_HIDDEN, $category);
625
626
    // Use LOWER('%s') instead of PHP's strtolower() to avoid UTF-8 conversion issues.
  }
627

Dries's avatar
   
Dries committed
628
  while ($field = db_fetch_object($result)) {
Dries's avatar
   
Dries committed
629
    $category = $field->category;
630
631
632
    if (!isset($fields[$category])) {
      $fields[$category] = array('#type' => 'fieldset', '#title' => $category, '#weight' => $w++);
    }
Dries's avatar
   
Dries committed
633
634
    switch ($field->type) {
      case 'textfield':
635
      case 'url':
636
        $fields[$category][$field->name] = array('#type' => 'textfield',
637
638
639
640
          '#title' => check_plain($field->title),
          '#default_value' => $edit[$field->name],
          '#maxlength' => 255,
          '#description' => _profile_form_explanation($field),
641
          '#required' => $field->required,
642
        );
Dries's avatar
   
Dries committed
643
        break;
644
      case 'textarea':
645
        $fields[$category][$field->name] = array('#type' => 'textarea',
646
647
648
          '#title' => check_plain($field->title),
          '#default_value' => $edit[$field->name],
          '#description' => _profile_form_explanation($field),
649
          '#required' => $field->required,
650
        );
Dries's avatar
Dries committed
651
652
        break;
      case 'list':
653
        $fields[$category][$field->name] = array('#type' => 'textarea',
654
655
656
          '#title' => check_plain($field->title),
          '#default_value' => $edit[$field->name],
          '#description' => _profile_form_explanation($field),
657
          '#required' => $field->required,
658
        );
Dries's avatar
   
Dries committed
659
        break;
660
      case 'checkbox':
661
        $fields[$category][$field->name] = array('#type' => 'checkbox',
662
663
664
          '#title' => check_plain($field->title),
          '#default_value' => $edit[$field->name],
          '#description' => _profile_form_explanation($field),
665
          '#required' => $field->required,
666
        );
Dries's avatar
   
Dries committed
667
668
        break;
      case 'selection':
669
        $options = $field->required ? array() : array('--');
Dries's avatar
   
Dries committed
670
        $lines = split("[,\n\r]", $field->options);
Dries's avatar
   
Dries committed
671
672
673
674
675
        foreach ($lines as $line) {
          if ($line = trim($line)) {
            $options[$line] = $line;
          }
        }
676
        $fields[$category][$field->name] = array('#type' => 'select',
677
678
679
680
          '#title' => check_plain($field->title),
          '#default_value' => $edit[$field->name],
          '#options' => $options,
          '#description' => _profile_form_explanation($field),
681
          '#required' => $field->required,
682
        );
Dries's avatar
   
Dries committed
683
        break;
Steven Wittens's avatar
Steven Wittens committed
684
      case 'date':
685
        $fields[$category][$field->name] = array('#type' => 'date',
686
687
688
          '#title' => check_plain($field->title),
          '#default_value' => $edit[$field->name],
          '#description' => _profile_form_explanation($field),
689
          '#required' => $field->required,
690
        );
Steven Wittens's avatar
Steven Wittens committed
691
        break;
Dries's avatar
 
Dries committed
692
693
    }
  }
694
  return $fields;
Dries's avatar
 
Dries committed
695
696
}

697
698
699
/**
 * Helper function: update an array of user fields by calling profile_view_field
 */
700
function _profile_update_user_fields($fields, $account) {
701
  foreach ($fields as $key => $field) {
702
    $fields[$key]->value = profile_view_field($account, $field);
703
  }
704
  return $fields;
705
706
}

707
function profile_validate_profile($edit, $category) {
708
  if (arg(0) == 'user' && arg(1) == 'register') {
709
    $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND register = 1 ORDER BY category, weight', PROFILE_HIDDEN);
Dries's avatar
   
Dries committed
710
  }
711
  elseif (arg(0) == 'admin' && arg(1) == 'user' && arg(2) == 'create') {
712
713
    $result = db_query('SELECT * FROM {profile_fields} WHERE register = 1 ORDER BY category, weight');
  }
714
  elseif (user_access('administer users')) {
715
    $result = db_query("SELECT * FROM {profile_fields} WHERE LOWER(category) = LOWER('%s') ORDER BY weight", $category);
Dries's avatar
   
Dries committed
716
  }
717
718
  else {
    $result = db_query("SELECT * FROM {profile_fields} WHERE visibility != %d AND LOWER(category) = LOWER('%s') ORDER BY weight", PROFILE_HIDDEN, $category);
719
720
    // Use LOWER('%s') instead of PHP's strtolower() to avoid UTF-8 conversion issues.
  }
721
722

  while ($field = db_fetch_object($result)) {
723
    if ($edit[$field->name]) {
Dries's avatar
   
Dries committed
724
725
      if ($field->type == 'url') {
        if (!valid_url($edit[$field->name], true)) {
726
727
          form_set_error($field->name, t('The value provided for %field is not a valid URL.', array('%field' => theme('placeholder', $field->title))));
        }
728
729
      }
    }
730
    else if ($field->required && !user_access('administer users')) {
731
      form_set_error($field->name, t('The field %field is required.', array('%field' => theme('placeholder', $field->title))));
Dries's avatar
   
Dries committed
732
    }
733
734
735
736
737
  }

  return $edit;
}

738
739
740
function profile_categories() {
  $result = db_query("SELECT DISTINCT(category) FROM {profile_fields}");
  while ($category = db_fetch_object($result)) {
741
    $data[] = array('name' => check_plain($category->category), 'title' => $category->category, 'weight' => 3);
742
743
744
745
  }
  return $data;
}

746
function theme_profile_block($account, $fields = array()) {
747

748
  $output .= theme('user_picture', $account);
749
750

  foreach ($fields as $field) {
751
    if ($field->value) {
752
753
754
755
756
757
      if ($field->type == 'checkbox') {
        $output .= "<p>$field->value</p>\n";
      }
      else {
        $output .= "<p><strong>$field->title</strong><br />$field->value</p>\n";
      }
758
759
760
761
762
763
    }
  }

  return $output;
}

764
function theme_profile_listing($account, $fields = array()) {
Dries's avatar
   
Dries committed
765
766

  $output  = "<div class=\"profile\">\n";
767
768
  $output .= theme('user_picture', $account);
  $output .= ' <div class="name">'. theme('username', $account) ."</div>\n";
Dries's avatar
   
Dries committed
769
770

  foreach ($fields as $field) {
771
    if ($field->value) {
772
      $output .= " <div class=\"field\">$field->value</div>\n";
Dries's avatar
 
Dries committed
773
774
    }
  }
Dries's avatar
   
Dries committed
775
776
777
778
779
780
781

  $output .= "</div>\n";

  return $output;
}

function _profile_field_types($type = NULL) {
Steven Wittens's avatar
Steven Wittens committed
782
783
784
785
786
787
788
  $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'));
Dries's avatar
   
Dries committed
789
  return isset($type) ? $types[$type] : $types;
Dries's avatar
 
Dries committed
790
791
}

Steven Wittens's avatar
Steven Wittens committed
792
793
794
function _profile_field_serialize($type = NULL) {
  return $type == 'date';
}
795
796
797
798
799
800
801
802
803
804
805
806
807

/**
 * Retrieve a pipe delimited string of autocomplete suggestions for profile categories
 */
function profile_admin_settings_autocomplete($string) {
  $matches = array();
  $result = db_query_range("SELECT category FROM {profile_fields} WHERE LOWER(category) LIKE LOWER('%s%%')", $string, 0, 10);
  while ($data = db_fetch_object($result)) {
    $matches[$data->category] = check_plain($data->category);
  }
  print drupal_to_js($matches);
  exit();
}