cforge-2.0.x-dev/src/Setup.php

src/Setup.php
<?php

namespace Drupal\cforge;

use Drupal\mcapi\Entity\Currency;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Locale\CountryManagerInterface;
use Drupal\Core\Extension\ModuleInstallerInterface;
use Drupal\Core\Extension\ExtensionDiscovery;
use Drupal\Core\Extension\ExtensionList;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;


ini_set('max_execution_time', 150);

/**
 * Configuration options for each flavour.
 *
 */
class Setup extends FormBase {

  /**
   * The site's default country
   * @var string
   */
  private $country;

  /**
   * @var CountryManagerInterface
   */
  private $countryManager;

  /**
   * @var ModuleInstallerInterface
   */
  private $installer;

  /**
   * @var LinkGeneratorInterface
   */
  protected $linkGenerator;

  /**
   * @var EntityTypeManagerInterface
   */
  private $entityTypeManager;
  /**
   * @var \Drupal\Core\Extension\ExtensionList
   */
  private $extensionList;
  /**
   * @var
   */
  private $formBuilder;
  /**
   * @var
   */
  private $defaultLanguage;
  /**
   * @var
   */
  private $moduleHandler;

  /**
   * @var ExtensionDiscovery
   */
  private $extensionDiscovery;

  /**
   * @param ModuleInstallerInterface $module_installer
   * @param LinkGeneratorInterface $link_generator
   * @param EntityTypeManagerInterface $entity_type_manager
   * @param ExtensionList $extension_list
   * @param type $form_builder
   * @param type $language_manager
   * @param ModuleHandler $module_handler
   * @param CountryManagerInterface $country_manager
   */
  public function __construct(ModuleInstallerInterface $module_installer, LinkGeneratorInterface $link_generator, EntityTypeManagerInterface $entity_type_manager, ExtensionList $extension_list, $form_builder, $language_manager, ModuleHandler $module_handler,  CountryManagerInterface $country_manager) {
    $this->installer = $module_installer;
    $this->linkGenerator = $link_generator;
    $this->entityTypeManager = $entity_type_manager;
    $this->extensionList = $extension_list;
    $this->formBuilder = $form_builder;
    $this->defaultLanguage = $language_manager->getDefaultLanguage();
    $this->moduleHandler = $module_handler;
    $this->extensionDiscovery = new ExtensionDiscovery(\Drupal::service('app.root'));
    $this->countryManager = $country_manager;
    $this->country = $this->config('system.date')->get('country.default');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('module_installer'),
      $container->get('link_generator'),
      $container->get('entity_type.manager'),
      $container->get('extension.list.module'),
      $container->get('form_builder'),
      $container->get('language_manager'),
      $container->get('module_handler'),
      $container->get('country_manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'cforge_setup_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // @todo move this to cf_hosted module and put dependencies in composer.json
    $form['migrate'] = [
      '#type' => 'submit',
      '#value' => 'Skip setup and migrate from Drupal 7',
      '#weight' => 0,
      '#submit' => ['::migration']
    ];

    $form['features'] = [
      // Hope that yields the current language.
      '#title' => (string) t('Hamlets features'),
      '#type' => 'checkboxes',
      '#options' => [],
      // Everything enabled by default.
      '#default_value' => [],
      '#weight' => 1,
    ];

    foreach ($this->extensionList->getList() as $module_name => $extension) {
      $info = $extension->info;
      if (@$info['project'] == 'cforge' and $module_name != 'cforge_import') {
        if (!$this->moduleHandler->moduleExists($module_name)) {
          $form['features']['#options'][$module_name] = $this->t($info['name']);
          $form['features']['#default_value'][] = $module_name;// all Checked by default
          $form['features'][$module_name]['#description'] = $this->t($info['description']);
          //$form['features'][$module_name]['#default_value'] = 1;
        }
      }
    }

    $form['data_content'] = [
      '#title' => $this->t('Prepare the site with'),
      '#type' => 'radios',
      '#options' => [
        'none' => t('No content'),
        'import' => $this->t('CSV Import Tools'),
      ],
      '#default_value'  => 'none',
      '#weight' => 3,
      '#required' => TRUE,
    ];

    $alt_login_form = $this->formBuilder->getForm('Drupal\alt_login\Settings');
    $form['aliases'] = [
      '#title' => $alt_login_form['aliases']['#title'],
      '#type' => 'select',
      '#options' => $alt_login_form['aliases']['#options'],
      '#default_value' => 'address_name',
      '#weight' => 5
    ];

    $form['default_categories'] = array(
      '#title' => $this->t('Preload ad categories'),
      '#description' => $this->t('Can be modified later'),
      '#type' => 'radios',
      '#options' => [
        0 => $this->t('- None -'),
        'en' => 'English LETS',
        'fr' => 'French',
        'be' => 'SEL Belgique, (2 Tier]'
      ],
      '#default_value' => $this->defaultLanguage->getId(),
      '#weight' => 6,
      '#states' => [
        'visible' => [
          ':input[name=data_content]' => ['value' => 'none'],
        ],
      ],
    );

    $form['site_default_country'] = [
      '#type' => 'select',
      '#title' => $this->t('Country'),
      '#empty_value' => '',
      '#default_value' => $this->country,
      '#options' => $this->countryManager->getList(),
      '#weight' => 7,
      '#required' => TRUE,
      '#access' => empty($this->country)
    ];

    $form['currency_type'] = [
      '#title' => $this->t('Main currency type'),
      '#type' => 'radios',
      '#options' => [
        'hours' => $this->t('Hours'),
        'other' => $this->t('Other'),
      ],
      '#default_value' => 'hours',
      '#required' => TRUE,
      '#weight' => 8,
    ];
    $form['currency_name'] = [
      '#title' => $this->t('Currency name'),
      '#description' => $this->t('Use the plural'),
      '#type' => 'textfield',
      '#placeholder' => $this->t('Units'),
      '#weight' => 9,
      '#states' => [
        'visible' => [
          ':input[name="currency_type"]' => ['value' => 'other'],
        ],
      ],
    ];

    $form['direction'] = [
      '#title' => $this->t('Default transaction direction'),
      '#type' => 'radios',
      '#options' => [
        'credit' => $this->t('Credit (push payment)'),
        'bill' => $this->t('Bill (pull payment)'),
        'both' => $this->t('Both (may be confusing for some users)')
      ],
      '#default_value' => 'credit',
      '#weight' => 10,
    ];

    $form['devel'] = [
      '#title' => t('Devel modules'),
      '#type' => 'checkbox',
      '#weight'=> 15
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Initiate Hamlets',
      '#weight' => 20,
    ];

    return $form;
  }


  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->moduleHandler->loadInclude('cforge', 'install');
    $available_modules = array_keys($this->extensionDiscovery->scan('module'));
    foreach($available_modules as $module) {
      if (substr($module, 0, 7) == 'cforge_') {
        module_set_weight($module, 101); //This doesn't seem to work anyway
      }
    }

    if ($form_state->getValue('direction') == 'credit') {
      if ($display = EntityFormDisplay::load('mcapi_transaction.mcapi_transaction.bill')) {
        $display->setThirdPartySetting('mcapi_forms', 'permission', 'manage mcapi')->save();
      }
    }
    elseif ($form_state->getValue('direction') == 'bill') {
      if ($display = EntityFormDisplay::load('mcapi_transaction.mcapi_transaction.credit')) {
        $display->setThirdPartySetting('mcapi_forms', 'permission', 'manage mcapi')->save();
      }
    }

    if ($form_state->getValue('default_categories')) {
      $terms = $this->entityTypeManager
        ->getStorage('taxonomy_term')
        ->loadByProperties(['vid' => SMALLAD_CATEGORIES_VID]);
      // Delete any existing terms in the vocab (one is installed by default)
      foreach ($terms as $term) {
        $term->delete();
      }
      $vocab = Vocabulary::load(SMALLAD_CATEGORIES_VID);
      // Now import the terms into the vocab.
      $get_terms = 'vocab_'.$form_state->getValue('default_categories');
      $last_term = $this->vocabImportRecursive($vocab, $this->$get_terms());
      $vocab->save();
      FieldConfig::load('mcapi_transaction.mcapi_transaction.category')
        ->set('default_value', [['target_uuid' => $last_term->uuid()]])
        ->save();
    }

    $country_code = $form_state->getValue('site_default_country') ?? $this->config('system.date')->get('country.default');
    self::setDefaultCountry($country_code);

    // Set up the currency by deleting the others.
    if ($c = Currency::load('veur')) {
      $c->delete();
    }
    if ($form_state->getValue('currency_type') == 'hours') {
      if ($c = Currency::load('cc')) {
        $c->delete();
      }
    }
    if ($form_state->getValue('currency_type') == 'cc') {
      if ($c = Currency::load('hhrs')) {
        $c->delete();
      }
    }

    if ($form_state->getvalue('aliases') == 'uid') {
      $alt_login_conf = $this->configfactory()->getEditable('alt_login.settings')
        ->set('display', '[user:address:given_name] [user:address:family_name] ([user:uid])')
        ->save();
    }
    $modules = array_filter($form_state->getValue('features'));
    if ($form_state->getValue('data_content') == 'import') {
      $modules[] = 'cforge_import';
    }

    if ($form_state->getValue('devel')) {
      $modules = array_merge($modules, [
        'dblog',
        'field_ui',
        'views_ui',
        'contextual',
        'admin_toolbar_tools',
        'config'
      ]);
    }
    $this->installer->install($modules);

    \Drupal::moduleHandler()->loadInclude('cforge', 'install');
    cforge_import_content('cforge', 'new');
    cforge_import_content('cforge', 'all');
    // Set the publiconly on all the page nodes.
    $nids = \Drupal::entityQuery('node')
      ->condition('type', 'page')
      ->condition('nid', 1, '<>') // Exclude privacy policy
      ->execute();
    foreach ($nids as $nid) {
      cforge_node_set_publiconly($nid, TRUE);
    }

    $form_state->setRedirectUrl(
      Url::fromUserInput($this->config('cforge.settings')->get('member_frontpage'))
    );
  }

  /**
   * Submit callback
   */
  public function migration(array &$form, FormStateInterface $form_state) {
    $modules = [
      'migrate_drupal_ui',
      'migrate_tools',
      'options'
    ];
    $this->installer->install($modules);
    $form_state->setRedirectUrl(Url::fromUserInput('/upgrade'));
  }

  /**
   * Import the terms in a vocabulary or a level of a vocab.
   */
  private function vocabImportRecursive(Vocabulary $vocab, array $termArray, $parent = 0) : \Drupal\taxonomy\Entity\Term{
    $w = $hierarchy = 0;
    foreach ($termArray as $term_name => $term_children) {
      $props = [
        'name' => $term_name,
        'weight' => $w++,
        'vid' => $vocab->id(),
        'parent' => $parent,
        'format' => 'plain_text',
      ];
      $term = Term::Create($props);
      $term->save();
      if (!empty($term_children)) {
        $this->vocabImportRecursive($vocab, $term_children, $term->tid);
      }
    }
    return $term;
  }

  /**
   * {@inheritdoc}
   */
  private function vocab_en() {
    return [
      'Arts & Culture' => [],
      'Business Services & Clerical' => [],
      'Clothing' => [],
      'Computing & Electronics' => [],
      'Education & Language' => [],
      'Food' => [],
      'Health & Wellness' => [],
      'House & Garden' => [],
      'LETS administration' => [],
      'Sports & Leisure' => [],
      'Skills & DIY' => [],
      'Transport' => [],
      'Miscellaneous' => []
    ];
  }

  /**
   * {@inheritdoc}
   */
  private function vocab_fr() {
    return [
      'SEL Administration' => [],
      'Alimentation' => [],
      'Artisanat & Bricolage' => [],
      'Arts & Culture' => [],
      'Cours & Langues' => [],
      'Informatique & Eléctro' => [],
      'Maison & Jardin' => [],
      'Mobilité' => [],
      'Santé & Soins' => [],
      'Sports & Evasion' => [],
      'Vêtements plus' => [],
      'Divers' => [],
    ];
  }
  private function vocab_be() {
    return [
      'A Ménage / Entretien maison' => [
        "Nettoyage/ produits d'entretien" => [],
        'Lessive, repassage' => [],
        'Couture, tricot' => [],
        'Rangement' => [],
        'Ménage - Divers' => [],
      ],
      'B Travaux maisons' => [
        'Travaux lourds' => [],
        'Petits travaux divers' => [],
        'Peinture, tapissage, décoration' => [],
        'Electricité' => [],
        'Plomberie, chauffage' => [],
        'Carrelage, plafonnage, maçonnerie' => [],
        'Menuiserie, planchers, meubles' => [],
        "Isolation, économies d'énergie" => [],
        "Travaux - Divers" => [],
      ],
      'C Enfants / Ados' => [
        'Grossesse et bébé' => [],
        'Baby sitting' => [],
        'Stages, animations créatives' => [],
        'Aide scolaire' => [],
        'Jeux et jouets' => [],
        'Enfants - Divers' => [],
      ],
      'D Alimentation / Gastronomie' => [
        'Nettoyage fruits et légumes' => [],
        'Boissons, soupes, sauces' => [],
        'Plats' => [],
        'Desserts' => [],
        "Tables d'hôtes" => [],
        'Cours, conseils, recettes' => [],
        'Alimentation - Divers' => [],
      ],
      'E Santé / Bien-être / Accompagnement' => [
        'Coiffure, esthétique visage et corps' => [],
        'Massage, thérapies, produits naturels' => [],
        'Personnes âgées, malades, immobilisées' => [],
        "Accompagnement, coaching et conseils 'psy'" => [],
        'Santé - Divers' => [],
      ],
      'F Administration / Gestion' => [
        'Classement de papiers, de dossiers' => [],
        'Dactylographie, mise en page' => [],
        'Courriers, démarches administratives' => [],
        'Assurances, questions juridiques' => [],
        'Fiscalité, pension, chômage' => [],
        'Administration du SEL' => [],
        'Administration - Divers' => [],
      ],
      'G Cours / Formations / Conseils' => [
        'Langues, conversation, traduction' => [],
        'Ecriture, rédaction, orthographe' => [],
        "Recherche d'emploi" => [],
        'Gestion et animation de groupes' => [],
        'Cours - Divers' => [],
      ],
      'H Jardin / Animaux / Nature' => [
        'Jardin : conception, entretien, conseils' => [],
        'Culture potagère, vergers' => [],
        'Récolte de fruits, légumes, plantes' => [],
        "Taille d'arbres et arbustes" => [],
        'Animaux (domestiques -élevage]' => [],
        'Biodiversité, nichoirs, découverte nature' => [],
        'Engrais, semences, plants, produits divers' => [],
        'Jardin et animaux - Divers' => [],
      ],
      'I Arts / Culture / Sports & loisirs' => [
        'Artisanat, peinture, dessin, sculpture' => [],
        'Musique, chant, danse' => [],
        'Photo, vidéo, cinema' => [],
        'Animations, spectacles' => [],
        'Fêtes : conseils, organisation, aide' => [],
        'Promenades, excursions' => [],
        "Jeux (de société, d'extérieur]" => [],
        'Sports' => [],
        'Culture et sport - Divers' => [],
      ],
      'J Transports / Voyages /Hébergement' => [
        'Courses' => [],
        'Covoiturage et transport' => [],
        'Déménagement' => [],
        'Auto-moto-vélo' => [],
        'Voyages, randonnées' => [],
        'Hébergement, échange maisons' => [],
        'Gardiennage maison' => [],
        'Transport - Divers' => [],
      ],
      'K Informatique /Électroménager' => [
        'Dépannage informatique' => [],
        'Réparation électroménager' => [],
        'Formations Internet / email' => [],
        'Formations logiciels' => [],
        'Informatique, électroménager - Divers' => [],
      ],
      'Z Divers (non classées]' => []
    ];
  }

  /**
   * Set the default country on the address field and all existing users to that country.
   */
  static function setDefaultCountry($country_code) {
    $field = FieldConfig::load('user.user.address');
    $settings = $field->get('settings');
    $settings['available_countries'][$country_code] = $country_code;
    $field->set('settings', $settings)
      ->save();
    \Drupal::configFactory()->getEditable('system.date')->set('country.default', $country_code)->save();
    foreach (\Drupal::entityTypeManager()->getStorage('user')->loadMultiple() as $user) {
      if ($user->isAnonymous()) continue;
      $user->address->country_code = $country_code;
      $user->save();
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc