Example #1
1
 /**
  * Starts the batch process depending on where it was requested from.
  */
 public function start()
 {
     switch ($this->batchInfo['from']) {
         case 'form':
             batch_set($this->batch);
             break;
         case 'drush':
             batch_set($this->batch);
             $this->batch =& batch_get();
             $this->batch['progressive'] = FALSE;
             drush_log(t(self::BATCH_INIT_MESSAGE), 'status');
             drush_backend_batch_process();
             break;
         case 'backend':
             batch_set($this->batch);
             $this->batch =& batch_get();
             $this->batch['progressive'] = FALSE;
             batch_process();
             //todo: Does not take advantage of batch API and eventually runs out of memory on very large sites.
             break;
         case 'nobatch':
             $context = [];
             foreach ($this->batch['operations'] as $i => $operation) {
                 $operation[1][] =& $context;
                 call_user_func_array($operation[0], $operation[1]);
             }
             self::finishGeneration(TRUE, $context['results'], []);
             break;
     }
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     batch_test_stack(NULL, TRUE);
     $function = '_batch_test_' . $form_state->getValue('batch');
     batch_set($function());
     $form_state->setRedirect('batch_test.redirect');
 }
 public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state)
 {
     // Check to make sure that the file was uploaded to the server properly
     $userInputValues = $form_state->getUserInput();
     $uri = db_select('file_managed', 'f')->condition('f.fid', $userInputValues['import']['fids'], '=')->fields('f', array('uri'))->execute()->fetchField();
     if (!empty($uri)) {
         if (file_exists(\Drupal::service("file_system")->realpath($uri))) {
             // Open the csv
             $handle = fopen(\Drupal::service("file_system")->realpath($uri), "r");
             // Go through each row in the csv and run a function on it. In this case we are parsing by '|' (pipe) characters.
             // If you want commas are any other character, replace the pipe with it.
             while (($data = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
                 $operations[] = ['csvimport_import_batch_processing', [$data]];
             }
             // Once everything is gathered and ready to be processed... well... process it!
             $batch = ['title' => t('Importing CSV...'), 'operations' => $operations, 'finished' => $this->csvimport_import_finished(), 'error_message' => t('The installation has encountered an error.'), 'progress_message' => t('Imported @current of @total products.')];
             batch_set($batch);
             fclose($handle);
         } else {
             drupal_set_message(t('Not able to find file path.'), 'error');
         }
     } else {
         drupal_set_message(t('There was an error uploading your file. Please contact a System administator.'), 'error');
     }
 }
Example #4
0
 /**
  * {@inheritodc}
  */
 public function startBatchClear(FeedInterface $feed)
 {
     $feed->lock();
     $feed->clearStates();
     $batch = ['title' => $this->t('Deleting items from: %title', ['%title' => $feed->label()]), 'init_message' => $this->t('Deleting items from: %title', ['%title' => $feed->label()]), 'operations' => [[[$this, 'clear'], [$feed]]], 'progress_message' => $this->t('Deleting items from: %title', ['%title' => $feed->label()]), 'error_message' => $this->t('An error occored while clearing %title.', ['%title' => $feed->label()])];
     batch_set($batch);
 }
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Pass the file to the parser.
     $fid = $form_state->getValue('mtg_import_json_file');
     $fid = reset($fid);
     if ($fid == 0) {
         return FALSE;
     }
     $file = File::load($fid);
     if (!$file) {
         drupal_set_message('Unable to load file.');
         \Drupal::logger('mtg_import')->error(t('Unable to load the file.'));
         return FALSE;
     }
     $uri = $file->uri->value;
     $file_contents_raw = file_get_contents($uri);
     $file_contents = json_decode($file_contents_raw);
     if (!empty($file_contents->cards)) {
         $operations = [['mtg_import_parse_set_data', [$file_contents]]];
         $chunks = array_chunk($file_contents->cards, 20);
         foreach ($chunks as $chunk) {
             $operations[] = ['mtg_import_parse_card_data', [$chunk]];
         }
         $batch = ['title' => t('Importing'), 'operations' => $operations, 'finished' => 'mtg_import_completed', 'progress_message' => t('Completed part @current of @total.')];
         batch_set($batch);
     } else {
         drupal_set_message(t('There are no cards in the file, so no import will take place.'), 'warning');
     }
 }
Example #6
0
 /**
  * Manually checks the update status without the use of cron.
  */
 public function updateStatusManually()
 {
     $this->updateManager->refreshUpdateData();
     $batch = array('operations' => array(array(array($this->updateManager, 'fetchDataBatch'), array())), 'finished' => 'update_fetch_data_finished', 'title' => t('Checking available update data'), 'progress_message' => t('Trying to check available update data ...'), 'error_message' => t('Error checking available update data.'));
     batch_set($batch);
     return batch_process('admin/reports/updates');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     batch_test_stack(NULL, TRUE);
     $function = '_batch_test_' . $form_state['values']['batch'];
     batch_set($function());
     $form_state['redirect_route'] = new Url('batch_test.redirect');
 }
 /**
  * Form submission handler #4 for batch_test_chained_form
  */
 public static function batchTestChainedFormSubmit4($form, FormStateInterface $form_state)
 {
     batch_test_stack('submit handler 4');
     batch_test_stack('value = ' . $form_state['values']['value']);
     $form_state['values']['value']++;
     batch_set(_batch_test_batch_3());
     $form_state->setRedirect('batch_test.redirect');
 }
 /**
  * Form submission handler #4 for batch_test_chained_form
  */
 public static function batchTestChainedFormSubmit4($form, &$form_state)
 {
     batch_test_stack('submit handler 4');
     batch_test_stack('value = ' . $form_state['values']['value']);
     $form_state['values']['value']++;
     batch_set(_batch_test_batch_3());
     $form_state['redirect_route'] = new Url('batch_test.redirect');
 }
 public function get_movies()
 {
     $batch = array('title' => t('Importing Douban Movies'), 'operations' => array(array('doubanmovie_get_movies', array())), 'finished' => 'my_finished_callback', 'file' => drupal_get_path('module', 'doubanmovie') . '/doubanmovie.batch.inc');
     batch_set($batch);
     // Only needed if not inside a form _submit handler.
     // Setting redirect in batch_process.
     return batch_process('node/1');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $batch = array('title' => $this->t('Bulk updating URL aliases'), 'operations' => array(array('Drupal\\pathauto\\Form\\PathautoBulkUpdateForm::batchStart', array())), 'finished' => 'Drupal\\pathauto\\Form\\PathautoBulkUpdateForm::batchFinished');
     foreach ($form_state->getValue('update') as $id) {
         if (!empty($id)) {
             $batch['operations'][] = array('Drupal\\pathauto\\Form\\PathautoBulkUpdateForm::batchProcess', array($id));
         }
     }
     batch_set($batch);
 }
Example #12
0
 /**
  * {@inheritdoc}.
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $batch = ['title' => $this->t('Importing feed sources'), 'operations' => [], 'progress_message' => $this->t('Processed @current feed source from @total.'), 'error_message' => $this->t('An error occurred during processing'), 'finished' => '_d8batch_batch_finished'];
     // Get the feed sources from the CSV file and add them to the batch
     // operations for later processing.
     if ($res = fopen(drupal_get_path('module', 'd8batch') . '/' . self::CSVFILE_NAME, 'r')) {
         while ($line = fgetcsv($res)) {
             $batch['operations'][] = ['_d8batch_batch_operation', [array_shift($line)]];
         }
         fclose($res);
     }
     batch_set($batch);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     batch_test_stack(NULL, TRUE);
     switch ($form_state['storage']['step']) {
         case 1:
             batch_set(_batch_test_batch_1());
             break;
         case 2:
             batch_set(_batch_test_batch_2());
             break;
     }
     if ($form_state['storage']['step'] < 2) {
         $form_state['storage']['step']++;
         $form_state['rebuild'] = TRUE;
     }
     $form_state->setRedirect('batch_test.redirect');
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     batch_test_stack(NULL, TRUE);
     $step = $form_state->get('step');
     switch ($step) {
         case 1:
             batch_set(_batch_test_batch_1());
             break;
         case 2:
             batch_set(_batch_test_batch_2());
             break;
     }
     if ($step < 2) {
         $form_state->set('step', ++$step);
         $form_state->setRebuild();
     }
     $form_state->setRedirect('batch_test.redirect');
 }
Example #15
0
 /**
  * {@inheritodc}
  */
 public function startBatchExpire(FeedInterface $feed)
 {
     try {
         $feed->lock();
     } catch (LockException $e) {
         drupal_set_message(t('The feed became locked before the expiring could begin.'), 'warning');
         return;
     }
     $feed->clearStates();
     $ids = $feed->getType()->getProcessor()->getExpiredIds($feed);
     if (!$ids) {
         $feed->unlock();
         return;
     }
     $batch = ['title' => $this->t('Expiring: %title', ['%title' => $feed->label()]), 'init_message' => $this->t('Expiring: %title', ['%title' => $feed->label()]), 'progress_message' => $this->t('Expiring: %title', ['%title' => $feed->label()]), 'error_message' => $this->t('An error occored while expiring %title.', ['%title' => $feed->label()])];
     foreach ($ids as $id) {
         $batch['operations'][] = [[$this, 'expireItem'], [$feed, $id]];
     }
     $batch['operations'][] = [[$this, 'postExpire'], [$feed]];
     batch_set($batch);
 }
Example #16
0
 /**
  * Callback for updating a theme.
  *
  * @param array $form
  *   Nested array of form elements that comprise the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public static function updateTheme(array $form, FormStateInterface $form_state)
 {
     if ($theme = SystemThemeSettings::getTheme($form, $form_state)) {
         // Due to the fact that the batch API stores it's arguments in DB storage,
         // theme based objects cannot be passed as an operation argument here.
         // During _batch_page(), the DB item will attempt to restore the arguments
         // using unserialize() and the autoload fix include added below may not
         // yet have been invoked to register the theme namespaces. So instead,
         // we capture the relevant information needed to reconstruct these objects
         // in the batch processing callback.
         $theme_name = $theme->getName();
         // Create an operation for each update.
         $operations = [];
         foreach ($theme->getPendingUpdates() as $update) {
             $operations[] = [[__CLASS__, 'batchProcessUpdate'], [$theme_name, $update->getProvider() . ':' . $update->getSchema()]];
         }
         if ($operations) {
             $variables = ['@theme_title' => $theme->getTitle()];
             batch_set(['operations' => $operations, 'finished' => [__CLASS__, 'batchFinished'], 'title' => t('Updating @theme_title', $variables), 'init_message' => \Drupal::translation()->formatPlural(count($operations), 'Initializing 1 theme update for @theme_title...', 'Initializing @count theme updates for @theme_title...', $variables), 'progress_message' => t('Processing update @current of @total...', $variables), 'error_message' => t('An error was encountered while attempting to update the @theme_title theme.', $variables), 'file' => Bootstrap::autoloadFixInclude()]);
         }
     }
 }
Example #17
0
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $batch = [
      'title' => $this->t('Clearing Flag data'),
      'operations' => [
        [
          [__CLASS__, 'resetFlags'], [],
        ],
        [
          [__CLASS__, 'clearTables'], [],
        ],
      ],
      'progress_message' => $this->t('Clearing Flag data...'),
    ];
    batch_set($batch);

    drupal_set_message($this->t(
      'Flag data has been cleared. <a href="@uninstall-url">Proceed with uninstallation.</a>',
      [
        '@uninstall-url' => Url::fromRoute('system.modules_uninstall')->toString(),
      ]
    ));
  }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $values = $form_state->getValues();
     $types = array_filter($values['types']);
     if (count($types) > 0) {
         try {
             foreach ($types as $bundle) {
                 $result = db_select('node');
                 $query = $result->fields('node', array('nid'));
                 $query = $result->condition('type', $bundle);
                 $query = $result->execute()->fetchAll();
                 $last_row = count($query);
                 $operations = array();
                 if (!empty($last_row)) {
                     $message = t('All nodes of type @content mark for deletion', array('@content' => $bundle));
                     \Drupal::logger('bulkdelete')->notice($message);
                     // Create batch of 20 nodes.
                     $count = 1;
                     foreach ($query as $row) {
                         $nids[] = $row->nid;
                         if ($count % 20 === 0 || $count === $last_row) {
                             $operations[] = array(array(get_class($this), 'processBatch'), array($nids));
                             $nids = array();
                         }
                         ++$count;
                     }
                     // Set up the Batch API
                     $batch = array('operations' => $operations, 'finished' => array(get_class($this), 'bulkdelete_finishedBatch'), 'title' => t('Node bulk delete'), 'init_message' => t('Starting nodes deletion.'), 'progress_message' => t('Completed @current step of @total.'), 'error_message' => t('Bulk node deletion has encountered an error.'));
                     batch_set($batch);
                 }
             }
         } catch (Exception $e) {
             foreach ($e->getErrors() as $error_message) {
                 drupal_set_message($error_message, 'error');
             }
         }
     }
 }
 /**
  * Method responsible for creating content when
  * the number of elements is greater than 50.
  */
 private function generateBatchContent($values)
 {
     // Setup the batch operations and save the variables.
     $operations[] = array('devel_generate_operation', array($this, 'batchContentPreNode', $values));
     // add the kill operation
     if ($values['kill']) {
         $operations[] = array('devel_generate_operation', array($this, 'batchContentKill', $values));
     }
     // add the operations to create the nodes
     for ($num = 0; $num < $values['num']; $num++) {
         $operations[] = array('devel_generate_operation', array($this, 'batchContentAddNode', $values));
     }
     // start the batch
     $batch = array('title' => $this->t('Generating Content'), 'operations' => $operations, 'finished' => 'devel_generate_batch_finished', 'file' => drupal_get_path('module', 'devel_generate') . '/devel_generate.batch.inc');
     batch_set($batch);
 }
Example #20
0
 /**
  * Credential form submission handler.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public function submitConfirmForm(array &$form, FormStateInterface $form_state)
 {
     $batch = ['title' => $this->t('Running upgrade'), 'progress_message' => '', 'operations' => [[['Drupal\\migrate_upgrade\\MigrateUpgradeRunBatch', 'run'], [$form_state->get('migration_ids')]]], 'finished' => ['Drupal\\migrate_upgrade\\MigrateUpgradeRunBatch', 'finished']];
     batch_set($batch);
     $form_state->setRedirect('<front>');
     \Drupal::state()->set('migrate_upgrade.performed', REQUEST_TIME);
 }
Example #21
0
 /**
  * Runs batch process of user accounts synchronization on submit form above
  * 
  * @param array &$form      Form descriptions
  * @param array &$formState Form state
  *  
  * @return void
  */
 public function processUserSyncFormSubmit(array &$form, array &$formState)
 {
     if (t(self::LC_OP_NAME_USERSYNC) == $formState['values']['op']) {
         if ($this->isUserSynchronizationRequired()) {
             variable_set('lc_user_sync_notify', $formState['values']['notify_users']);
             // Calculate number of steps and list ot operations
             $maxSteps = $this->totalNonSynchronizedAccounts;
             // $this->userAccountsPerStepCounter) + 1;
             $operations = array();
             for ($i = 0; $i < $maxSteps; $i++) {
                 $operations[] = array('lcConnectorUserSync', array());
             }
             // Initialize batch (to set title).
             $batch = array('title' => t('Synchronize user accounts'), 'init_message' => t('Starting user accounts synchronization...'), 'operations' => $operations, 'finished' => 'lcConnectorUserSyncFinishedCallback');
             batch_set($batch);
             // Run batch process
             batch_process();
         } else {
             drupal_set_message(t('User accounts synchronization is not required.'));
         }
     }
 }
Example #22
0
function update_batch()
{
    global $base_url;
    // During the update, bring the site offline so that schema changes do not
    // affect visiting users.
    $_SESSION['site_offline'] = variable_get('site_offline', FALSE);
    if ($_SESSION['site_offline'] == FALSE) {
        variable_set('site_offline', TRUE);
    }
    $operations = array();
    // Set the installed version so updates start at the correct place.
    foreach ($_POST['start'] as $module => $version) {
        drupal_set_installed_schema_version($module, $version - 1);
        $updates = drupal_get_schema_versions($module);
        $max_version = max($updates);
        if ($version <= $max_version) {
            foreach ($updates as $update) {
                if ($update >= $version) {
                    $operations[] = array('update_do_one', array($module, $update));
                }
            }
        }
    }
    $batch = array('operations' => $operations, 'title' => 'Updating', 'init_message' => 'Starting updates', 'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.', 'finished' => 'update_finished');
    batch_set($batch);
    batch_process($base_url . '/update.php?op=results', $base_url . '/update.php');
}
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $entity_type_id = $form_state->getValue('entity_type_id');
     $entity_type_plural = $this->entityTypeManager->getDefinition($entity_type_id)->getPluralLabel();
     $batch = ['title' => t('Deleting @entity_type_plural', ['@entity_type_plural' => $entity_type_plural]), 'operations' => [[[__CLASS__, 'deleteContentEntities'], [$entity_type_id]]], 'finished' => [__CLASS__, 'moduleBatchFinished'], 'progress_message' => ''];
     batch_set($batch);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $config_importer = new ConfigImporter($form_state->get('storage_comparer'), $this->eventDispatcher, $this->configManager, $this->lock, $this->typedConfigManager, $this->moduleHandler, $this->themeHandler, $this->getStringTranslation());
     if ($config_importer->alreadyImporting()) {
         drupal_set_message($this->t('Another request may be synchronizing configuration already.'));
     } else {
         try {
             $sync_steps = $config_importer->initialize();
             $batch = array('operations' => array(), 'finished' => array(get_class($this), 'finishBatch'), 'title' => t('Synchronizing configuration'), 'init_message' => t('Starting configuration synchronization.'), 'progress_message' => t('Completed @current step of @total.'), 'error_message' => t('Configuration synchronization has encountered an error.'), 'file' => drupal_get_path('module', 'config') . '/config.admin.inc');
             foreach ($sync_steps as $sync_step) {
                 $batch['operations'][] = array(array(get_class($this), 'processBatch'), array($config_importer, $sync_step));
             }
             batch_set($batch);
         } catch (ConfigImporterException $e) {
             // There are validation errors.
             drupal_set_message($this->t('The configuration synchronization failed validation.'));
             foreach ($config_importer->getErrors() as $message) {
                 drupal_set_message($message, 'error');
             }
         }
     }
 }
Example #25
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     // Add language, if not yet supported.
     $language = $this->languageManager->getLanguage($form_state->getValue('langcode'));
     if (empty($language)) {
         $language = ConfigurableLanguage::createFromLangcode($form_state->getValue('langcode'));
         $language->save();
         drupal_set_message($this->t('The language %language has been created.', array('%language' => $this->t($language->label()))));
     }
     $options = array('langcode' => $form_state->getValue('langcode'), 'overwrite_options' => $form_state->getValue('overwrite_options'), 'customized' => $form_state->getValue('customized') ? LOCALE_CUSTOMIZED : LOCALE_NOT_CUSTOMIZED);
     $this->moduleHandler->loadInclude('locale', 'bulk.inc');
     $file = locale_translate_file_attach_properties($this->file, $options);
     $batch = locale_translate_batch_build(array($file->uri => $file), $options);
     batch_set($batch);
     $form_state->setRedirect('locale.translate_page');
 }
Example #26
0
 /**
  * Starts the database update batch process.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  */
 protected function triggerBatch(Request $request)
 {
     $maintenance_mode = $this->state->get('system.maintenance_mode', FALSE);
     // Store the current maintenance mode status in the session so that it can
     // be restored at the end of the batch.
     $_SESSION['maintenance_mode'] = $maintenance_mode;
     // During the update, always put the site into maintenance mode so that
     // in-progress schema changes do not affect visiting users.
     if (empty($maintenance_mode)) {
         $this->state->set('system.maintenance_mode', TRUE);
     }
     $operations = array();
     // Resolve any update dependencies to determine the actual updates that will
     // be run and the order they will be run in.
     $start = $this->getModuleUpdates();
     $updates = update_resolve_dependencies($start);
     // Store the dependencies for each update function in an array which the
     // batch API can pass in to the batch operation each time it is called. (We
     // do not store the entire update dependency array here because it is
     // potentially very large.)
     $dependency_map = array();
     foreach ($updates as $function => $update) {
         $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
     }
     // Determine updates to be performed.
     foreach ($updates as $function => $update) {
         if ($update['allowed']) {
             // Set the installed version of each module so updates will start at the
             // correct place. (The updates are already sorted, so we can simply base
             // this on the first one we come across in the above foreach loop.)
             if (isset($start[$update['module']])) {
                 drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
                 unset($start[$update['module']]);
             }
             $operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
         }
     }
     $post_updates = $this->postUpdateRegistry->getPendingUpdateFunctions();
     if ($post_updates) {
         // Now we rebuild all caches and after that execute the hook_post_update()
         // functions.
         $operations[] = ['drupal_flush_all_caches', []];
         foreach ($post_updates as $function) {
             $operations[] = ['update_invoke_post_update', [$function]];
         }
     }
     $batch['operations'] = $operations;
     $batch += array('title' => $this->t('Updating'), 'init_message' => $this->t('Starting updates'), 'error_message' => $this->t('An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.'), 'finished' => array('\\Drupal\\system\\Controller\\DbUpdateController', 'batchFinished'));
     batch_set($batch);
     // @todo Revisit once https://www.drupal.org/node/2548095 is in.
     return batch_process(Url::fromUri('base://results'), Url::fromUri('base://start'));
 }
Example #27
0
/**
 * Run an individual installation task.
 *
 * @param $task
 *   An array of information about the task to be run.
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   passed in by reference so that it can be modified by the task.
 * @return
 *   The output of the task function, if there is any.
 */
function install_run_task($task, &$install_state)
{
    $function = $task['function'];
    if ($task['type'] == 'form') {
        require_once DRUPAL_ROOT . '/includes/form.inc';
        if ($install_state['interactive']) {
            // For interactive forms, build the form and ensure that it will not
            // redirect, since the installer handles its own redirection only after
            // marking the form submission task complete.
            $form_state = array('args' => array(&$install_state), 'no_redirect' => TRUE);
            $form = drupal_build_form($function, $form_state);
            // If a successful form submission did not occur, the form needs to be
            // rendered, which means the task is not complete yet.
            if (empty($form_state['executed'])) {
                $install_state['task_not_complete'] = TRUE;
                return drupal_render($form);
            }
            // Otherwise, return nothing so the next task will run in the same
            // request.
            return;
        } else {
            // For non-interactive forms, submit the form programmatically with the
            // values taken from the installation state. Throw an exception if any
            // errors were encountered.
            $form_state = array('values' => !empty($install_state['forms'][$function]) ? $install_state['forms'][$function] : array());
            drupal_form_submit($function, $form_state, $install_state);
            $errors = form_get_errors();
            if (!empty($errors)) {
                throw new Exception(implode("\n", $errors));
            }
        }
    } elseif ($task['type'] == 'batch') {
        // Start a new batch based on the task function, if one is not running
        // already.
        $current_batch = variable_get('install_current_batch');
        if (!$install_state['interactive'] || !$current_batch) {
            $batch = $function($install_state);
            if (empty($batch)) {
                // If the task did some processing and decided no batch was necessary,
                // there is nothing more to do here.
                return;
            }
            batch_set($batch);
            // For interactive batches, we need to store the fact that this batch
            // task is currently running. Otherwise, we need to make sure the batch
            // will complete in one page request.
            if ($install_state['interactive']) {
                variable_set('install_current_batch', $function);
            } else {
                $batch =& batch_get();
                $batch['progressive'] = FALSE;
            }
            // Process the batch. For progressive batches, this will redirect.
            // Otherwise, the batch will complete.
            batch_process(install_redirect_url($install_state), install_full_redirect_url($install_state));
        } elseif ($current_batch == $function) {
            include_once DRUPAL_ROOT . '/includes/batch.inc';
            $output = _batch_page();
            // The task is complete when we try to access the batch page and receive
            // FALSE in return, since this means we are at a URL where we are no
            // longer requesting a batch ID.
            if ($output === FALSE) {
                // Return nothing so the next task will run in the same request.
                variable_del('install_current_batch');
                return;
            } else {
                // We need to force the page request to end if the task is not
                // complete, since the batch API sometimes prints JSON output
                // rather than returning a themed page.
                $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE;
                return $output;
            }
        }
    } else {
        // For normal tasks, just return the function result, whatever it is.
        return $function($install_state);
    }
}
Example #28
0
 /**
  * Runs a batch for testing the title shown on the progress page.
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
  *   A redirect response if the batch is progressive. No return value otherwise.
  */
 public function testTitleBatch()
 {
     batch_test_stack(NULL, TRUE);
     $batch = ['title' => 'Batch Test', 'operations' => [['_batch_test_title_callback', []]]];
     batch_set($batch);
     return batch_process('batch-test/redirect');
 }
Example #29
0
/**
 * Tasks performed after the database is initialized.
 */
function install_tasks($profile, $task)
{
    global $base_url, $install_locale;
    // Bootstrap newly installed Drupal, while preserving existing messages.
    $messages = isset($_SESSION['messages']) ? $_SESSION['messages'] : '';
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    $_SESSION['messages'] = $messages;
    // URL used to direct page requests.
    $url = $base_url . '/install.php?locale=' . $install_locale . '&profile=' . $profile;
    // Build a page for final tasks.
    if (empty($task)) {
        variable_set('install_task', 'profile-install');
        $task = 'profile-install';
    }
    // We are using a list of if constructs here to allow for
    // passing from one task to the other in the same request.
    // Install profile modules.
    if ($task == 'profile-install') {
        $modules = variable_get('install_profile_modules', array());
        $files = module_rebuild_cache();
        variable_del('install_profile_modules');
        $operations = array();
        foreach ($modules as $module) {
            $operations[] = array('_install_module_batch', array($module, $files[$module]->info['name']));
        }
        $batch = array('operations' => $operations, 'finished' => '_install_profile_batch_finished', 'title' => st('Installing @drupal', array('@drupal' => drupal_install_profile_name())), 'error_message' => st('The installation has encountered an error.'));
        // Start a batch, switch to 'profile-install-batch' task. We need to
        // set the variable here, because batch_process() redirects.
        variable_set('install_task', 'profile-install-batch');
        batch_set($batch);
        batch_process($url, $url);
    }
    // We are running a batch install of the profile's modules.
    // This might run in multiple HTTP requests, constantly redirecting
    // to the same address, until the batch finished callback is invoked
    // and the task advances to 'locale-initial-import'.
    if ($task == 'profile-install-batch') {
        include_once 'includes/batch.inc';
        $output = _batch_page();
    }
    // Import interface translations for the enabled modules.
    if ($task == 'locale-initial-import') {
        if (!empty($install_locale) && $install_locale != 'en') {
            include_once 'includes/locale.inc';
            // Enable installation language as default site language.
            locale_add_language($install_locale, NULL, NULL, NULL, NULL, NULL, 1, TRUE);
            // Collect files to import for this language.
            $batch = locale_batch_by_language($install_locale, '_install_locale_initial_batch_finished');
            if (!empty($batch)) {
                // Remember components we cover in this batch set.
                variable_set('install_locale_batch_components', $batch['#components']);
                // Start a batch, switch to 'locale-batch' task. We need to
                // set the variable here, because batch_process() redirects.
                variable_set('install_task', 'locale-initial-batch');
                batch_set($batch);
                batch_process($url, $url);
            }
        }
        // Found nothing to import or not foreign language, go to next task.
        $task = 'configure';
    }
    if ($task == 'locale-initial-batch') {
        include_once 'includes/batch.inc';
        include_once 'includes/locale.inc';
        $output = _batch_page();
    }
    if ($task == 'configure') {
        if (variable_get('site_name', FALSE) || variable_get('site_mail', FALSE)) {
            // Site already configured: This should never happen, means re-running
            // the installer, possibly by an attacker after the 'install_task' variable
            // got accidentally blown somewhere. Stop it now.
            install_already_done_error();
        }
        $form = drupal_get_form('install_configure_form', $url);
        if (!variable_get('site_name', FALSE) && !variable_get('site_mail', FALSE)) {
            // Not submitted yet: Prepare to display the form.
            $output = $form;
            drupal_set_title(st('Configure site'));
            // Warn about settings.php permissions risk
            $settings_dir = './' . conf_path();
            $settings_file = $settings_dir . '/settings.php';
            if (!drupal_verify_install_file($settings_file, FILE_EXIST | FILE_READABLE | FILE_NOT_WRITABLE) || !drupal_verify_install_file($settings_dir, FILE_NOT_WRITABLE, 'dir')) {
                drupal_set_message(st('All necessary changes to %dir and %file have been made, so you should remove write permissions to them now in order to avoid security risks. If you are unsure how to do so, please consult the <a href="@handbook_url">on-line handbook</a>.', array('%dir' => $settings_dir, '%file' => $settings_file, '@handbook_url' => 'http://drupal.org/getting-started')), 'error');
            } else {
                drupal_set_message(st('All necessary changes to %dir and %file have been made. They have been set to read-only for security.', array('%dir' => $settings_dir, '%file' => $settings_file)));
            }
            // Add JavaScript validation.
            _user_password_dynamic_validation();
            drupal_add_js(drupal_get_path('module', 'system') . '/system.js', 'module');
            // We add these strings as settings because JavaScript translation does not
            // work on install time.
            drupal_add_js(array('copyFieldValue' => array('edit-site-mail' => array('edit-account-mail')), 'cleanURL' => array('success' => st('Your server has been successfully tested to support this feature.'), 'failure' => st('Your system configuration does not currently support this feature. The <a href="http://drupal.org/node/15365">handbook page on Clean URLs</a> has additional troubleshooting information.'), 'testing' => st('Testing clean URLs...'))), 'setting');
            drupal_add_js('
// Global Killswitch
if (Drupal.jsEnabled) {
  $(document).ready(function() {
    Drupal.cleanURLsInstallCheck();
    Drupal.setDefaultTimezone();
  });
}', 'inline');
            // Build menu to allow clean URL check.
            menu_rebuild();
        } else {
            $task = 'profile';
        }
    }
    // If found an unknown task or the 'profile' task, which is
    // reserved for profiles, hand over the control to the profile,
    // so it can run any number of custom tasks it defines.
    if (!in_array($task, install_reserved_tasks())) {
        $function = $profile . '_profile_tasks';
        if (function_exists($function)) {
            // The profile needs to run more code, maybe even more tasks.
            // $task is sent through as a reference and may be changed!
            $output = $function($task, $url);
        }
        // If the profile doesn't move on to a new task we assume
        // that it is done.
        if ($task == 'profile') {
            $task = 'profile-finished';
        }
    }
    // Profile custom tasks are done, so let the installer regain
    // control and proceed with importing the remaining translations.
    if ($task == 'profile-finished') {
        if (!empty($install_locale) && $install_locale != 'en') {
            include_once 'includes/locale.inc';
            // Collect files to import for this language. Skip components
            // already covered in the initial batch set.
            $batch = locale_batch_by_language($install_locale, '_install_locale_remaining_batch_finished', variable_get('install_locale_batch_components', array()));
            // Remove temporary variable.
            variable_del('install_locale_batch_components');
            if (!empty($batch)) {
                // Start a batch, switch to 'locale-remaining-batch' task. We need to
                // set the variable here, because batch_process() redirects.
                variable_set('install_task', 'locale-remaining-batch');
                batch_set($batch);
                batch_process($url, $url);
            }
        }
        // Found nothing to import or not foreign language, go to next task.
        $task = 'finished';
    }
    if ($task == 'locale-remaining-batch') {
        include_once 'includes/batch.inc';
        include_once 'includes/locale.inc';
        $output = _batch_page();
    }
    // Display a 'finished' page to user.
    if ($task == 'finished') {
        drupal_set_title(st('@drupal installation complete', array('@drupal' => drupal_install_profile_name())));
        $messages = drupal_set_message();
        $output = '<p>' . st('Congratulations, @drupal has been successfully installed.', array('@drupal' => drupal_install_profile_name())) . '</p>';
        $output .= '<p>' . (isset($messages['error']) ? st('Please review the messages above before continuing on to <a href="@url">your new site</a>.', array('@url' => url(''))) : st('You may now visit <a href="@url">your new site</a>.', array('@url' => url('')))) . '</p>';
        $task = 'done';
    }
    // The end of the install process. Remember profile used.
    if ($task == 'done') {
        // Rebuild menu to get content type links registered by the profile,
        // and possibly any other menu items created through the tasks.
        menu_rebuild();
        // Register actions declared by any modules.
        actions_synchronize();
        // Randomize query-strings on css/js files, to hide the fact that
        // this is a new install, not upgraded yet.
        _drupal_flush_css_js();
        variable_set('install_profile', $profile);
    }
    // Set task for user, and remember the task in the database.
    install_task_list($task);
    variable_set('install_task', $task);
    // Output page, if some output was required. Otherwise it is possible
    // that we are printing a JSON page and theme output should not be there.
    if (isset($output)) {
        print theme('maintenance_page', $output);
    }
}
Example #30
0
 /**
  * Submission handler for the confirmation form.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public function submitConfirmForm(array &$form, FormStateInterface $form_state)
 {
     $storage = $form_state->getStorage();
     $migrations = $storage['migrations'];
     $config['source_base_path'] = $storage['source_base_path'];
     $batch = ['title' => $this->t('Running upgrade'), 'progress_message' => '', 'operations' => [[[MigrateUpgradeRunBatch::class, 'run'], [array_keys($migrations), 'import', $config]]], 'finished' => [MigrateUpgradeRunBatch::class, 'finished']];
     batch_set($batch);
     $form_state->setRedirect('<front>');
     $this->state->set('migrate_drupal_ui.performed', REQUEST_TIME);
 }