- very early D6 version (Oct-01, 2007)
[project/gallery.git] / gallery_user_admin.inc
index c6cae2c..3e312d6 100644 (file)
@@ -8,19 +8,13 @@ require_once(drupal_get_path('module', 'gallery') .'/gallery_user.inc');
  * Gallery User Administration
  */
  
-define(GALLERY_BATCH_INTERVAL, 50);
+define('GALLERY_BATCH_INTERVAL', 10);
 
 /**
  * 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');
-  }
-  
+function _gallery_user_users() {
   // Generate user status overview
   $header = array(
     array('data' => t('ID'), 'field' => 'u.uid', 'sort' => 'asc'),
@@ -34,7 +28,7 @@ function _gallery_user_users($args) {
 
   $status = array(t('blocked'), t('active'));
   $destination = drupal_get_destination();
-  $filter = $_SESSION['gallery_user_filter'];
+  $filter = isset($_SESSION['gallery_user_filter']) ? $_SESSION['gallery_user_filter'] : FALSE;
 
   if (!_gallery_init(TRUE)) {
     return '';
@@ -44,7 +38,7 @@ function _gallery_user_users($args) {
     gallery_error(t('Error calling \'GalleryCoreApi::isUserInSiteAdminGroup\'.'), $ret);
   }
   
-  if (isset($filter)) {
+  if ($filter) {
     $result = db_query($query);
   }
   else {
@@ -52,6 +46,7 @@ function _gallery_user_users($args) {
     $result = pager_query($query, 50);
   }
   
+  $rows = array();
   while ($user = db_fetch_object($result)) {
     $g2_userinfo = gallery_user_map_info(user_load(array('uid' => $user->uid)), FALSE);
     
@@ -70,7 +65,7 @@ function _gallery_user_users($args) {
       $operations[] = l(t('sync'), 'admin/user/gallery/users/sync/'. $user->uid, array(), drupal_get_destination());
     }
     
-    if (isset($filter)) {
+    if ($filter) {
       if ($filter == GALLERY_USERINFO_ERROR) {
         if (!count($g2_userinfo['status'])) {
           continue;
@@ -105,7 +100,7 @@ function _gallery_user_users($args) {
  * Function _gallery_user_filter_form().
  * (filter form for user status)
  */
-function _gallery_user_filter_form($filter) {
+function _gallery_user_filter_form($form_state, $filter) {
   $form['filter'] = array(
     '#type' => 'fieldset',
     '#title' => t('Filter by status'),
@@ -120,24 +115,46 @@ function _gallery_user_filter_form($filter) {
     '#options' => $filter_options,
     '#default_value' => $filter,
   );
-  $form['filter']['buttons']['submit'] = array('#type' => 'submit', '#value' => t('Filter'));
+  $form['filter']['buttons']['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Filter'),
+    '#submit' => array('_gallery_user_filter_submit')
+  );
   if ($filter) {
-    $form['filter']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
+    $form['filter']['buttons']['reset'] = array(
+      '#type' => 'submit',
+      '#value' => t('Reset'),
+      '#submit' => array('_gallery_user_filter_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) {
+function _gallery_user_filter_submit($form, &$form_state) {
+  $_SESSION['gallery_user_filter'] = $form_state['values']['filter_status'];
+}
+
+/**
+ * Function _gallery_user_filter_reset().
+ */
+function _gallery_user_filter_reset($form, &$form_state) {
   unset($_SESSION['gallery_user_filter']);
-  if ($form_values['op'] == t('Filter')) {
-    $_SESSION['gallery_user_filter'] = $form_values['filter_status'];
+}
+
+/**
+ * Function _gallery_user_users_sync().
+ */
+function _gallery_user_users_sync($uid = NULL) {
+  // Sync the selected user
+  if (isset($uid) && is_numeric($uid)) {
+    _gallery_user_sync($uid);
   }
+
+  drupal_goto('admin/user/gallery/users');
 }
 
 /**
@@ -176,15 +193,16 @@ function _gallery_user_advanced() {
   );
   
   $form['buttons']['start'] = array('#type' => 'submit', '#value' => t('Start'));
-  $form['#base'] = '_gallery_user_advanced';
+  $form['#validate'] = array('_gallery_user_advanced_validate');
+  $form['#submit'] = array('_gallery_user_advanced_submit');
   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) {
+function _gallery_user_advanced_validate($form, &$form_state) {
+  if (($form_state['values']['gallery_user_advanced_import'] + $form_state['values']['gallery_user_advanced_sync']) < 1) {
     form_set_error('', t('No option selected.'));
   }
 }
@@ -192,36 +210,57 @@ function _gallery_user_advanced_validate($form_id, $form_values) {
 /**
  * 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_submit($form, &$form_state) {
+  if ($form_state['values']['gallery_user_advanced_offline']) {
+    variable_set('site_offline', 1);
+    $_SESSION['gallery_user_batch_offline'] = TRUE;
+  }
+
+  $operations = array();
+  if ($form_state['values']['gallery_user_advanced_import']) {
+    $operations[] = array('_gallery_user_advanced_import', array());
+  }
+  if ($form_state['values']['gallery_user_advanced_sync']) {
+    $operations[] = array('_gallery_user_advanced_sync', array());
   }
+  
+  $batch = array(
+    'title' => t('User Synchronization'),
+    'operations' => $operations,
+    'file' => drupal_get_path('module', 'gallery') .'/gallery_user_admin.inc',
+    'finished' => '_gallery_user_advanced_finished'
+  );
+  
+  batch_set($batch);
 }
 
 /**
  * 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;
+function _gallery_user_advanced_import(&$context) {
+  // Skip operation if an error occured
+  if (isset($context['results']['error']) && $context['results']['error']) {
+    $context['finished'] = $context['results']['error'] = 1;
+    return;
+  }
+  // Initialize G2
+  if (!_gallery_init(TRUE, NULL, FALSE)) {
+    gallery_error(t('Unable to initialize embedded Gallery.'));
+    $context['finished'] = $context['results']['error'] = 1;
+    return;
   }
   // First pass
-  if (!$position) {
+  if (empty($context['sandbox'])) {
+    // Initialize batch variables
+    $context['finished'] = 0;
+    $context['sandbox']['progress'] = 0;
+    // Total number of G2 users
+    list($ret, $context['sandbox']['max']) = GalleryCoreApi::fetchUserCount();
+    if ($ret || !$context['sandbox']['max']) {
+      gallery_error(t('Error getting number of G2 users'), $ret);
+      $context['finished'] = $context['results']['error'] = 1;
+      return;
+    }
     // Flush entity cache
     gallery_flush_entity_cache();
     // Import Gallery2 groups
@@ -230,156 +269,107 @@ function _gallery_user_advanced_import(&$position) {
     }
   }
   // Fetch a list of G2 users
-  list($ret, $g2_users) = GalleryCoreApi::fetchUsernames(GALLERY_BATCH_INTERVAL, $position);
+  list($ret, $g2_users) = GalleryCoreApi::fetchUsernames(GALLERY_BATCH_INTERVAL, $context['sandbox']['progress']);
   if ($ret) {
     gallery_error(t('Error fetching G2 usernames'), $ret);
-    return 0;
+    $context['finished'] = $context['results']['error'] = 1;
+    return;
   }
   else {
-    if (!_gallery_user_import($g2_users)) {
-      return 0;
+    if (!_gallery_user_import($g2_users, $context['results']['messages'])) {
+      $context['finished'] = $context['results']['error'] = 1;
+      return;
     }
   }
-  $position += GALLERY_BATCH_INTERVAL;
-  
-  return ( 100 * $position ) / $total;
+  $context['sandbox']['progress'] += GALLERY_BATCH_INTERVAL;
+  $context['finished'] = 1;
+  if ($context['sandbox']['progress'] < $context['sandbox']['max']) {
+    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
+  }
 }
 
 /**
  * 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;
+function _gallery_user_advanced_sync(&$context) {
+  // Skip operation if an error occured
+  if (isset($context['results']['error']) && $context['results']['error']) {
+    $context['finished'] = $context['results']['error'] = 1;
+    return;
+  }
+  // Initialize G2
+  if (!_gallery_init(TRUE, NULL, FALSE)) {
+    gallery_error(t('Unable to initialize embedded Gallery.'));
+    $context['finished'] = $context['results']['error'] = 1;
+    return;
   }
-  // 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;
+  // First pass
+  if (empty($context['sandbox'])) {
+    // Initialize batch variables
+    $context['finished'] = 0;
+    $context['sandbox']['progress'] = 0;
+    // Total number of users
+    $total = db_fetch_object(db_query("SELECT COUNT(*) AS users FROM {users} WHERE uid > 0"));
+    if (!$total->users) {
+      $context['finished'] = $context['results']['error'] = 1;
+      return;
+    }
+    $context['sandbox']['max'] = $total->users;
+    // Empty externalIdMap in first pass
+    if (variable_get('gallery_user_sync_remap', 0)) {
+      $ret = GalleryCoreApi::removeAllMapEntries('ExternalIdMap');
+      if ($ret) {
+        gallery_error(t('Error emptying \'ExternalIdMap\''), $ret);
+        $context['finished'] = $context['results']['error'] = 1;
+        return;
+      }
     }
   }
   // Sync users
-  $result = db_query_range("SELECT uid FROM {users} WHERE uid > 0", $position, GALLERY_BATCH_INTERVAL);
+  $result = db_query_range("SELECT uid FROM {users} WHERE uid > 0", $context['sandbox']['progress'], 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;
+      if (!gallery_user_modify($account, 'update', !$context['sandbox']['progress'])) {
+        $context['finished'] = $context['results']['error'] = 1;
+        return;
       }
     }
   }
-  $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');
+  $context['sandbox']['progress'] += GALLERY_BATCH_INTERVAL;
+  $context['finished'] = 1;
+  if ($context['sandbox']['progress'] < $context['sandbox']['max']) {
+    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
+  }
 }
 
 /**
- * Function _gallery_user_advanced_progress().
+ * Function _gallery_user_advanced_finished().
  */
-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;
+function _gallery_user_advanced_finished($success, $results, $operations) {
+  if (isset($_SESSION['gallery_user_batch_offline'])) {
+    variable_set('site_offline', 0);
+    unset($_SESSION['gallery_user_batch_offline']);
+  }
+  //
+  if ($success) {
+    if (isset($results['error']) && $results['error']) {
+      drupal_set_message(t('User synchronization (partially) failed.'), 'error');
     }
     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');
+      if (isset($results['messages']) && count($results['messages'])) {
+        drupal_set_message(theme('item_list', $results['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.'));
+        watchdog('gallery', theme('item_list', $results['messages'], t('The following messages occured:')), WATCHDOG_NOTICE);
       }
       else {
-        drupal_set_message(t('User synchronization (partially) failed.'), 'error');
-      }
-      if ($redirect) {
-        unset($_SESSION['gallery_user_progress_redirect']);
-        drupal_goto($redirect);
+        drupal_set_message(t('User synchronization successfully completed.'));
       }
-      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;
+  else {
+    $error_operation = reset($operations);
+    drupal_set_message(t('An error occurred while processing @operation', array('@operation' => $error_operation[0])), 'error');
+  }
 }
 
 /**
@@ -395,17 +385,11 @@ function _gallery_user_settings() {
     '#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(
+  // General (not sync related) settings
+  $form['user']['gallery_user_hide_profile'] = array(
     '#type' => 'checkbox',
     '#title' => t('Hide Gallery2 section in profiles'),
-    '#default_value' => variable_get('gallery_user_profile_hide', 0),
+    '#default_value' => variable_get('gallery_user_hide_profile', 0),
     '#description' => t('Hide the Gallery2 section (i.e. Gallery2-Drupal Sync Status) on the user profile pages.'),
   );
   
@@ -466,7 +450,7 @@ function _gallery_user_settings() {
                            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}');
@@ -546,20 +530,21 @@ function _gallery_user_settings() {
                          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);
+  $form = system_settings_form($form);
+  $form['#submit'] = array('_gallery_user_settings_submit', 'system_settings_form_submit');
+  return $form;
 }
 
 /**
  * Function _gallery_user_settings_submit().
  */
-function _gallery_user_settings_submit($form_id, $form_values) {
-  if ($form_values['op'] == t('Reset to defaults')) {
+function _gallery_user_settings_submit($form, &$form_state) {
+  if ($form_state['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));
+    $fullname_changed = (isset($form_state['values']['gallery_use_fullname'])
+      && ($form_state['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