summaryrefslogtreecommitdiffstats
path: root/gallery_user_admin.inc
blob: 843f7cb3521750706ac7c3df213b8902754cfb2f (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
<?php

require_once(drupal_get_path('module', 'gallery') .'/gallery_user.inc');

/**
 * gallery.module : gallery_user_admin.inc
 * Gallery User Administration
 */
 
define('GALLERY_BATCH_INTERVAL', 50);

/**
 * Function _gallery_user_users().
 * (gallery users page - view list of users)
 */
function _gallery_user_users($args) {
  // Sync the selected user
  if ($args && is_numeric($args)) {
    _gallery_user_sync($args);
    drupal_goto('admin/user/gallery/users');
  }
  
  // Generate user status overview
  $header = array(
    array('data' => t('ID'), 'field' => 'u.uid', 'sort' => 'asc'),
    array('data' => t('G2ID')),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    array('data' => t('Sync Status')),
    t('Operations')
  );
  $query = 'SELECT u.uid, u.name, u.status FROM {users} u WHERE uid != 0';

  $status = array(t('blocked'), t('active'));
  $destination = drupal_get_destination();
  $filter = $_SESSION['gallery_user_filter'];

  if (!_gallery_init(TRUE)) {
    return '';
  }
  list($ret, $g2_admin) = GalleryCoreApi::isUserInSiteAdminGroup();
  if ($ret) {
    gallery_error(t('Error calling \'GalleryCoreApi::isUserInSiteAdminGroup\'.'), $ret);
  }
  
  if (isset($filter)) {
    $result = db_query($query);
  }
  else {
    $query .= tablesort_sql($header);
    $result = pager_query($query, 50);
  }
  
  while ($user = db_fetch_object($result)) {
    $g2_userinfo = gallery_user_map_info(user_load(array('uid' => $user->uid)), FALSE);
    
    $g2_id = ($g2_userinfo['g2_id'] >= 0) ? $g2_userinfo['g2_id'] : t('N/A');

    $operations = array(l(t('edit'), "user/$user->uid/edit", array(), $destination));

    if ($g2_admin && ($g2_userinfo['g2_id'] > 0)) {
      $link_url = gallery_generate_url(array('view' => 'core.SiteAdmin',
                                               'subView' => 'core.AdminEditUser',
                                               'userId' => $g2_userinfo['g2_id']), FALSE);
      $operations[] = l(t('edit G2'), $link_url);
    }

    if (count($g2_userinfo['status'])) {
      $operations[] = l(t('sync'), 'admin/user/gallery/users/sync/'. $user->uid, array(), drupal_get_destination());
    }
    
    if (isset($filter)) {
      if ($filter == GALLERY_USERINFO_ERROR) {
        if (!count($g2_userinfo['status'])) {
          continue;
        }
      }
      elseif (!in_array($filter, $g2_userinfo['status'])) {
        continue;
      }    
    }

    $rows[] = array($user->uid,
                    $g2_id,
                    theme_username($user),
                    $status[$user->status],
                    implode(',<br />', gallery_user_map_info_status($g2_userinfo['status'])),
                    implode(' | ', $operations));
  }
  
  if ($filter && !count($rows)) {
    $rows[] = array(array('data' => t('There are no users with the selected status.'), 'colspan' => '6', 'align' => 'center', 'class' => 'message'));
  }
  
  $output  = drupal_get_form('_gallery_user_filter_form', $filter);
  $output .= theme('table', $header, $rows);
  $output .= theme('pager', array(), 50);

  GalleryEmbed::done();
  return $output;
}

/**
 * Function _gallery_user_filter_form().
 * (filter form for user status)
 */
function _gallery_user_filter_form($filter) {
  $form['filter'] = array(
    '#type' => 'fieldset',
    '#title' => t('Filter by status'),
    '#collapsible' => TRUE,
    '#collapsed' => !$filter,
  );
  $filter_options = gallery_user_map_info_status(array(), FALSE);
  unset($filter_options[GALLERY_USERINFO_NOERROR]);
  $form['filter']['filter_status'] = array(
    '#type' => 'select',
    '#title' => t('Show only users with status'),
    '#options' => $filter_options,
    '#default_value' => $filter,
  );
  $form['filter']['buttons']['submit'] = array('#type' => 'submit', '#value' => t('Filter'));
  if ($filter) {
    $form['filter']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
  }
  $form['#submit']['_gallery_user_filter_submit'] = array();
  
  return $form;
}

/**
 * Function _gallery_user_filter_submit().
 * (submit handler of the filter form)
 */
function _gallery_user_filter_submit($form_id, $form_values) {
  unset($_SESSION['gallery_user_filter']);
  if ($form_values['op'] == t('Filter')) {
    $_SESSION['gallery_user_filter'] = $form_values['filter_status'];
  }
}

/**
 * Function _gallery_user_advanced().
 * (advanced user administration)
 */
function _gallery_user_advanced() {
  $form['advanced'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced Sync (Batch operations)'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['advanced']['gallery_user_advanced_import'] = array(
    '#type' => 'checkbox',
    '#title' => t('Import users from Gallery2'),
    '#return_value' => 1,
    '#default_value' => FALSE,
    '#description' => t('Use this option to import users from an existing Gallery2 install into Drupal.'),
  );
  $form['advanced']['gallery_user_advanced_sync'] = array(
    '#type' => 'checkbox',
    '#title' => t('Synchronize (export) all existing users'),
    '#return_value' => 1,
    '#default_value' => FALSE,
    '#description' => t('Use this option to sync all users between Drupal and Gallery2.'),
  );
  
  $form['advanced']['gallery_user_advanced_offline'] = array(
    '#type' => 'checkbox',
    '#title' => t('Switch Drupal to \'offline mode\' for operation'),
    '#return_value' => 1,
    '#default_value' => FALSE,
    '#disabled' => (user_access('administer site configuration') && !variable_get('site_offline', 0)) ? FALSE : TRUE,
    '#prefix' => '<br />',
  );
  
  $form['buttons']['start'] = array('#type' => 'submit', '#value' => t('Start'));
  $form['#base'] = '_gallery_user_advanced';
  return $form;
}

/**
 * Function _gallery_user_advanced_validate().
 */
function _gallery_user_advanced_validate($form_id, $form_values) {
  if (($form_values['gallery_user_advanced_import'] + $form_values['gallery_user_advanced_sync']) < 1) {
    form_set_error('', t('No option selected.'));
  }
}

/**
 * Function _gallery_user_advanced_submit().
 */
function _gallery_user_advanced_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Start')) {
    if ($form_values['gallery_user_progress_offline']) {
      variable_set('site_offline', 1);
      $_SESSION['gallery_user_progress_offline'] = TRUE;
    }
    
    $tasks = array();
    if ($form_values['gallery_user_advanced_import']) {
      $tasks[] = 'import';
    }
    if ($form_values['gallery_user_advanced_sync']) {
      $tasks[] = 'sync';
    }
    _gallery_user_advanced_start($tasks);
  }
}

/**
 * Function _gallery_user_advanced_import().
 */
function _gallery_user_advanced_import(&$position) {
  // Get number of G2 users
  list($ret, $total) = GalleryCoreApi::fetchUserCount();
  if ($ret || !$total) {
    gallery_error(t('Error getting number of G2 users'), $ret);
    return 100;
  }
  // First pass
  if (!$position) {
    // Flush entity cache
    gallery_flush_entity_cache();
    // Import Gallery2 groups
    if (variable_get('gallery_user_import_groups', 1)) {
      _gallery_groups_import();
    }
  }
  // Fetch a list of G2 users
  list($ret, $g2_users) = GalleryCoreApi::fetchUsernames(GALLERY_BATCH_INTERVAL, $position);
  if ($ret) {
    gallery_error(t('Error fetching G2 usernames'), $ret);
    return 0;
  }
  else {
    if (!_gallery_user_import($g2_users)) {
      return 0;
    }
  }
  $position += GALLERY_BATCH_INTERVAL;
  
  return ( 100 * $position ) / $total;
}

/**
 * Function _gallery_user_advanced_sync().
 */
function _gallery_user_advanced_sync(&$position) {
  $total = db_fetch_object(db_query("SELECT COUNT(*) AS users FROM {users} WHERE uid > 0"));
  if (!$total->users) {
    return 100;
  }
  // Empty externalIdMap in first pass
  if (!$position && variable_get('gallery_user_sync_remap', 0)) {
    $ret = GalleryCoreApi::removeAllMapEntries('ExternalIdMap');
    if ($ret) {
      gallery_error(t('Error emptying \'ExternalIdMap\''), $ret);
      return 0;
    }
  }
  // Sync users
  $result = db_query_range("SELECT uid FROM {users} WHERE uid > 0", $position, GALLERY_BATCH_INTERVAL);
  while ($user = db_fetch_object($result)) {
    if ($account = user_load(array('uid' => $user->uid))) {
      if (!gallery_user_modify($account, 'update', !$position)) {
        return 0;
      }
    }
  }
  $position += GALLERY_BATCH_INTERVAL;

  return ( 100 * $position ) / $total->users;
}

/**
 * Function _gallery_user_advanced_start().
 */
function _gallery_user_advanced_start($mode, $redirect = NULL) {
  $_SESSION['gallery_user_progress_mode'] = $mode;
  $_SESSION['gallery_user_progress_position'] = 0;
  $_SESSION['gallery_user_progress_messages'] = array();
  $_SESSION['gallery_user_progress_redirect'] = $redirect;
  drupal_goto('admin/user/gallery/advanced_progress');
}

/**
 * Function _gallery_user_advanced_progress().
 */
function _gallery_user_advanced_progress() {
  $mode = $_SESSION['gallery_user_progress_mode'];
  $position = $_SESSION['gallery_user_progress_position'];
  $messages = $_SESSION['gallery_user_progress_messages'];
  $redirect = $_SESSION['gallery_user_progress_redirect'];
  if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (!_gallery_init(TRUE, NULL, FALSE)) {
      $percent = 0;
    }
    else {
      switch (reset($mode)) {
        case 'import':
          $status = t('Importing Gallery2 users into Drupal ...');
          $percent = _gallery_user_advanced_import($position);
          break;
        case 'sync':
          $status = t('Synchronizing Drupal and Gallery2 users ...');
          $percent = _gallery_user_advanced_sync($position);
          break;
        default:
          $status = t('Performing batch operation ...');
          $percent = $position++;
      }
      GalleryEmbed::done();
    }
    // Operation finished or error occured
    if ($percent >= 100 || !$percent) {
      array_shift($mode);
      if (count($mode) && $percent) {
        _gallery_user_advanced_start($mode, $redirect);
      }
      if ($_SESSION['gallery_user_progress_offline']) {
        variable_set('site_offline', 0);
        unset($_SESSION['gallery_user_progress_offline']);
      }
      if (count($_SESSION['gallery_user_progress_messages'])) {
        drupal_set_message(theme('item_list', $_SESSION['gallery_user_progress_messages'], t('The following messages occured:')), 'notice');
        drupal_set_message('<strong>'. t('Invalid user items were skipped.') .'</strong>', 'notice');
        watchdog('gallery', theme('item_list', $_SESSION['gallery_user_progress_messages'], t('The following messages occured:')), WATCHDOG_NOTICE);
      }
      unset($_SESSION['gallery_user_progress_mode']);
      unset($_SESSION['gallery_user_progress_position']);
      unset($_SESSION['gallery_user_progress_messages']);
      if ($percent) {
        drupal_set_message(t('User synchronization successfully completed.'));
      }
      else {
        drupal_set_message(t('User synchronization (partially) failed.'), 'error');
      }
      if ($redirect) {
        unset($_SESSION['gallery_user_progress_redirect']);
        drupal_goto($redirect);
      }
      drupal_goto('admin/user/gallery/advanced');
    }
    $_SESSION['gallery_user_progress_position'] = $position;
  }

  drupal_set_title('Drupal <> Gallery2');
  drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL='. base_path() .'index.php?q=admin/user/gallery/advanced_progress">');
  print theme('gallery_user_progress_page', theme('progress_bar', round($percent, 1), $status), FALSE);
  exit();
}

/**
 * Theme function : theme_gallery_user_progress_page().
 */
function theme_gallery_user_progress_page($content, $messages = TRUE, $partial = FALSE) {
  drupal_set_header('Content-Type: text/html; charset=utf-8');
  drupal_set_html_head('<link rel="shortcut icon" href="'. base_path() .'misc/favicon.ico" type="image/x-icon" />');

  $css = array('all' => array('module' => array('misc/maintenance.css' => FALSE, 'modules/system/system.css' => FALSE)));

  $output = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
  $output .= '<html xmlns="http://www.w3.org/1999/xhtml">';
  $output .= '<head>';
  $output .= ' <title>'. strip_tags(drupal_get_title()) .'</title>';
  $output .= drupal_get_html_head();
  $output .= drupal_get_css($css);
  $output .= drupal_get_js();
  $output .= '</head>';
  $output .= '<body>';
  $output .= '<h2>'. drupal_get_title() .'</h2>';

  $output .= "\n<!-- begin content -->\n";
  $output .= $content;
  $output .= "\n<!-- end content -->\n";

  $output .= '</body></html>';

  return $output;
}

/**
 * Function _gallery_user_settings().
 */
function _gallery_user_settings() {
  require_once(drupal_get_path('module', 'gallery') .'/gallery_settings.inc');
  
  $form['user'] = array(
    '#type' => 'fieldset',
    '#title' => t('Settings'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE
  );
  
  // Profile settings
  $form['user']['profile'] = array(
    '#type' => 'fieldset',
    '#title' => t('User Profile'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );
  $form['user']['profile']['gallery_user_profile_hide'] = array(
    '#type' => 'checkbox',
    '#title' => t('Hide Gallery2 section in profiles'),
    '#default_value' => variable_get('gallery_user_profile_hide', 0),
    '#description' => t('Hide the Gallery2 section (i.e. Gallery2-Drupal Sync Status) on the user profile pages.'),
  );
  
  // Sync settings
  $form['user']['sync'] = array(
    '#type' => 'fieldset',
    '#title' => t('User Synchronization'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE
  );
  
  $roles  = array(0 => t('none'));
  $roles += user_roles(TRUE);
  unset($roles[DRUPAL_AUTHENTICATED_RID]);
  $form['user']['sync']['gallery_user_admin_role'] = array(
    '#type' => 'select',
    '#title' => t('Drupal \'admin\' role'),
    '#default_value' => variable_get('gallery_user_admin_role', 0),
    '#options' => $roles,
    '#description' => t('Select the Drupal role equivalent to Gallery2\'s \'Site Admin\' group (or \'none\' to disable this
                         feature). The roles \'anonymous\' and \'authenticated\' are not available for selection.'),
  );
  
  $form['user']['sync']['gallery_user_locked'] = array(
    '#type' => 'checkbox',
    '#title' => t('Lock G2 accounts'),
    '#default_value' => variable_get('gallery_user_locked', 0),
    '#description' => t('Locking G2 account prevents users from changing their details (password, email, ...) in G2.'),
  );
  
  // Fullname settings
  $profile_status = module_exists('profile');
  $profile_status_str = theme('gallery_module_status_message', $profile_status);
  $desc = t('Full names in Gallery2 can be supported by using the profile module
            (!profile_status) with a \'Full Name\' profile field as defined below.', 
            array('!profile_status' => $profile_status_str)
  );
  if (!$profile_status) {
    $desc .= t(' However the profile module is disabled, so this functionality is
      not available and the options are disabled.');
  }
  $form['user']['sync']['fullname'] = array(
    '#type' => 'fieldset',
    '#title' => t('Full Name settings'),
    '#collapsible' => TRUE,
    '#collapsed' => !$profile_status,
    '#description' => $desc,
  );
  if ($profile_status) {
    $usefullname = variable_get('gallery_use_fullname', 0);
    $form['user']['sync']['fullname']['gallery_use_fullname'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable Full Name support'),
      '#return_value' => 1,
      '#default_value' => $usefullname,
      '#disabled' => !$profile_status,
      '#description' => t('Use full name from profile module in Gallery2 user data. Note that
                           enabling/disabling this only updates Gallery2 user data when the
                           Drupal user is updated or if a user sync is performed.'),
    );

    if ($usefullname) {
      $categories = array();
      $result = db_query('SELECT DISTINCT(category) FROM {profile_fields}');
      while ($category = db_fetch_object($result)) {
        $categories[$category->category] = $category->category;
      }
      $default_category = variable_get('gallery_profile_fullname_category', 'Personal Information');
      $form['user']['sync']['fullname']['gallery_profile_fullname_category'] = array(
        '#type' => 'select',
        '#title' => t('Full name profile category'),
        '#default_value' => $default_category,
        '#options' => $categories,
        '#description' => t('Name of the category containing the \'Full Name\' field in profile module.'),
      );
      $fields = array();
      $result = _profile_get_fields($default_category);
      while ($field = db_fetch_object($result)) {
        $fields[$field->name] = $field->title;
      }
      $form['user']['sync']['fullname']['gallery_profile_fullname_field'] = array(
        '#type' => 'select',
        '#title' => t('Full name profile field'),
        '#default_value' => variable_get('gallery_profile_fullname_field', 'profile_fullname'),
        '#options' => $fields,
        '#description' => t('Name of \'Full Name\' field in profile module.'),
      );
    }
  }
  
  // Import behaviour
  $form['user']['sync']['import'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced Sync - Import'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  
  $form['user']['sync']['import']['gallery_user_import_groups'] = array(
    '#type' => 'checkbox',
    '#title' => t('Import Gallery2 groups'),
    '#default_value' => variable_get('gallery_user_import_groups', 1),
    '#description' => t('Import Gallery2 groups into Drupal roles (in addition to users).'),
  );
  
  $form['user']['sync']['import']['gallery_user_import_override'] = array(
    '#type' => 'checkbox',
    '#title' => t('Override existing Drupal users'),
    '#default_value' => variable_get('gallery_user_import_override', 0),
    '#description' => t('Replaces user details (password, email, groups, ...) of existing Drupal users with Gallery2 imported values.'),
  );
  
  $form['user']['sync']['import']['gallery_user_import_conflict'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Auto-resolve email address conflicts'),
    '#default_value' => variable_get('gallery_user_import_conflict', array()),
    '#options' => array(
      GALLERY_IMPORT_CONFLICT_DUPLICATE   => t('Duplicate e-mail addresses'),
      GALLERY_IMPORT_CONFLICT_INVALID     => t('Invalide e-mail addresses')
    ),
    '#description' => t('Renames duplicate/invalid e-mail addresses to username@drupaldomain.
                         If this option is disabled you get a list of users to handle conflicts yourself.')
  );
  
  // Export behaviour
  $form['user']['sync']['export'] = array(
    '#type' => 'fieldset',
    '#title' => t('Advanced Sync - Export (Synchronize)'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  
  $form['user']['sync']['export']['gallery_user_sync_remap'] = array(
    '#type' => 'checkbox',
    '#title' => t('Remap all users'),
    '#default_value' => variable_get('gallery_user_sync_remap', 0),
    '#description' => t('Remaps all users instead of missing or mismatching ones only.
                         This will completely flush Gallery2\'s \'externalIdMap\'.'),
  );
  
  $form['#submit']['_gallery_user_settings_submit'] = array();
  $form['#submit']['system_settings_form_submit'] = array();
  return system_settings_form($form);
}

/**
 * Function _gallery_user_settings_submit().
 */
function _gallery_user_settings_submit($form_id, $form_values) {
  if ($form_values['op'] == t('Reset to defaults')) {
    $fullname_changed = variable_get('gallery_use_fullname', 0);
  } 
  else {
    $fullname_changed = ($form_values['gallery_use_fullname'] != variable_get('gallery_use_fullname', 0));
  }
  if ($fullname_changed) {
      drupal_set_message(t('Full Name settings have changed. You should now synchronize
                            your users on the <a href="@user-admin">Gallery users</a> page.',
                            array('@user-admin' => url('admin/user/gallery'))));
  }
}