View source
<?php
namespace Drupal\contact_storage_export\Form;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\contact_storage_export\ContactStorageExport;
use Drupal\contact\Entity\Message;
class ContactStorageExportForm extends FormBase {
public function getFormId() {
return 'contact_storage_export';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$contact_form = $this
->getRequest()
->get('contact_form');
if ($contact_form) {
return $this
->exportForm($contact_form, $form, $form_state);
}
else {
return $this
->contactFormSelection($form, $form_state);
}
}
protected function exportForm($contact_form, array $form, FormStateInterface $form_state) {
$contact_message = $this
->getSingleMessage($contact_form);
if (!$contact_message) {
$message = $this
->t('There are no messages to be exported for this form.');
$messenger = \Drupal::messenger();
$messenger
->addWarning($message);
}
else {
$form['contact_form'] = [
'#type' => 'hidden',
'#value' => $contact_form,
];
$form['since_last_export'] = [
'#type' => 'checkbox',
'#title' => t('Only export new messages since the last export'),
];
$last_id = ContactStorageExport::getLastExportId($contact_form);
if (!$this
->getSingleMessage($contact_form, $last_id)) {
$form['since_last_export']['#disabled'] = TRUE;
$form['since_last_export']['#description'] = $this
->t('This checkbox has been disabled as there are not new messages since your last export.');
}
$form['advanced'] = [
'#type' => 'details',
'#title' => $this
->t('Advanced Settings'),
'#open' => FALSE,
];
$labels = \Drupal::service('contact_storage_export.exporter')
->getLabels($contact_message);
unset($labels['uuid']);
$form['advanced']['columns'] = [
'#type' => 'checkboxes',
'#title' => t('Columns to be exported'),
'#required' => TRUE,
'#options' => $labels,
'#default_value' => array_keys($labels),
];
$filename = str_replace('_', '-', $contact_form);
$filename .= '-' . date('Y-m-d--h-i-s');
$filename .= '.csv';
$form['advanced']['filename'] = [
'#type' => 'textfield',
'#title' => t('File name'),
'#required' => TRUE,
'#default_value' => $filename,
'#maxlength' => 240,
];
$form['advanced']['date_format'] = [
'#type' => 'select',
'#title' => $this
->t('Created date format'),
'#options' => $this
->getDateFormats(),
'#default_value' => 'medium',
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Export'),
'#button_type' => 'primary',
];
if (!isset($form['#attributes'])) {
$form['#attributes'] = [];
}
}
return $form;
}
protected function contactFormSelection(array $form, FormStateInterface $form_state) {
if ($bundles = \Drupal::service('entity_type.bundle.info')
->getBundleInfo('contact_message')) {
$options = [];
foreach ($bundles as $key => $bundle) {
$options[$key] = $bundle['label'];
}
$form['contact_form'] = [
'#type' => 'select',
'#title' => t('Contact form'),
'#options' => $options,
'#required' => TRUE,
];
$form['#attributes']['method'] = 'get';
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Select form'),
'#button_type' => 'primary',
];
}
else {
$message = $this
->t('You must create a contact form first before you can export.');
$messenger = \Drupal::messenger();
$messenger
->addWarning($message);
}
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$settings = $form_state
->getValues();
if ($settings['since_last_export']) {
$last_id = ContactStorageExport::getLastExportId($settings['contact_form']);
if (!$this
->getSingleMessage($settings['contact_form'], $last_id)) {
$message = $this
->t('There have been no new messages since the last export.');
$form_state
->setErrorByName('since_last_export', $message);
}
}
$filaname_parts = explode('.', $settings['filename']);
$extension = end($filaname_parts);
if (strtolower($extension) != 'csv') {
$message = $this
->t('The filename must end in ".csv"');
$form_state
->setErrorByName('filename', $message);
}
$punctuation = '-_. ';
$map = [
'!\\s+!' => ' ',
'!\\.+!' => '.',
"![^0-9A-Za-z{$punctuation}]!" => '',
];
$sanitised = preg_replace(array_keys($map), array_values($map), $settings['filename']);
$sanitised = trim($sanitised, $punctuation);
if ($sanitised != $settings['filename']) {
$message = $this
->t('The filename should not have multiple whitespaces in a row, should not have multiple dots in a row, and should use only alphanumeric charcters.');
$form_state
->setErrorByName('filename', $message);
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$path = drupal_get_path('module', 'contact_storage_export');
$path .= '/src/ContactStorageExportBatches.php';
$settings = $form_state
->getValues();
$settings['columns'] = array_filter($settings['columns']);
$batch = [
'title' => t('Exporting'),
'operations' => [
[
'_contact_storage_export_process_batch',
[
$settings,
],
],
],
'finished' => '_contact_storage_export_finish_batch',
'file' => $path,
];
batch_set($batch);
}
protected function getSingleMessage($contact_form, $since_last_id = 0) {
$query = \Drupal::entityQuery('contact_message');
$query
->condition('contact_form', $contact_form);
$query
->condition('id', $since_last_id, '>');
$query
->range(0, 1);
if ($mids = $query
->execute()) {
$mid = reset($mids);
if ($message = Message::load($mid)) {
return $message;
}
}
return FALSE;
}
protected function getDateFormats() {
$date_formats = DateFormat::loadMultiple();
$formats = [];
$request_time = \Drupal::time()
->getRequestTime();
foreach ($date_formats as $id => $date_format) {
$formats[$id] = \Drupal::service('date.formatter')
->format($request_time, $id);
}
return $formats;
}
}