df80a47035be0b522cbfd9cdf0809726bb8db4cb
[yaffs-website] / web / core / modules / taxonomy / src / Form / OverviewTerms.php
1 <?php
2
3 namespace Drupal\taxonomy\Form;
4
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Form\FormBase;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\Core\Form\FormStateInterface;
10 use Drupal\Core\Render\RendererInterface;
11 use Drupal\Core\Url;
12 use Drupal\taxonomy\VocabularyInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14
15 /**
16  * Provides terms overview form for a taxonomy vocabulary.
17  *
18  * @internal
19  */
20 class OverviewTerms extends FormBase {
21
22   /**
23    * The module handler service.
24    *
25    * @var \Drupal\Core\Extension\ModuleHandlerInterface
26    */
27   protected $moduleHandler;
28
29   /**
30    * The entity manager.
31    *
32    * @var \Drupal\Core\Entity\EntityManagerInterface
33    */
34   protected $entityManager;
35
36   /**
37    * The term storage handler.
38    *
39    * @var \Drupal\taxonomy\TermStorageInterface
40    */
41   protected $storageController;
42
43   /**
44    * The term list builder.
45    *
46    * @var \Drupal\Core\Entity\EntityListBuilderInterface
47    */
48   protected $termListBuilder;
49
50   /**
51    * The renderer service.
52    *
53    * @var \Drupal\Core\Render\RendererInterface
54    */
55   protected $renderer;
56
57   /**
58    * Constructs an OverviewTerms object.
59    *
60    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
61    *   The module handler service.
62    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
63    *   The entity manager service.
64    * @param \Drupal\Core\Render\RendererInterface $renderer
65    *   The renderer service.
66    */
67   public function __construct(ModuleHandlerInterface $module_handler, EntityManagerInterface $entity_manager, RendererInterface $renderer = NULL) {
68     $this->moduleHandler = $module_handler;
69     $this->entityManager = $entity_manager;
70     $this->storageController = $entity_manager->getStorage('taxonomy_term');
71     $this->termListBuilder = $entity_manager->getListBuilder('taxonomy_term');
72     $this->renderer = $renderer ?: \Drupal::service('renderer');
73   }
74
75   /**
76    * {@inheritdoc}
77    */
78   public static function create(ContainerInterface $container) {
79     return new static(
80       $container->get('module_handler'),
81       $container->get('entity.manager'),
82       $container->get('renderer')
83     );
84   }
85
86   /**
87    * {@inheritdoc}
88    */
89   public function getFormId() {
90     return 'taxonomy_overview_terms';
91   }
92
93   /**
94    * Form constructor.
95    *
96    * Display a tree of all the terms in a vocabulary, with options to edit
97    * each one. The form is made drag and drop by the theme function.
98    *
99    * @param array $form
100    *   An associative array containing the structure of the form.
101    * @param \Drupal\Core\Form\FormStateInterface $form_state
102    *   The current state of the form.
103    * @param \Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary
104    *   The vocabulary to display the overview form for.
105    *
106    * @return array
107    *   The form structure.
108    */
109   public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL) {
110     // @todo Remove global variables when https://www.drupal.org/node/2044435 is
111     //   in.
112     global $pager_page_array, $pager_total, $pager_total_items;
113
114     $form_state->set(['taxonomy', 'vocabulary'], $taxonomy_vocabulary);
115     $parent_fields = FALSE;
116
117     $page = $this->getRequest()->query->get('page') ?: 0;
118     // Number of terms per page.
119     $page_increment = $this->config('taxonomy.settings')->get('terms_per_page_admin');
120     // Elements shown on this page.
121     $page_entries = 0;
122     // Elements at the root level before this page.
123     $before_entries = 0;
124     // Elements at the root level after this page.
125     $after_entries = 0;
126     // Elements at the root level on this page.
127     $root_entries = 0;
128
129     // Terms from previous and next pages are shown if the term tree would have
130     // been cut in the middle. Keep track of how many extra terms we show on
131     // each page of terms.
132     $back_step = NULL;
133     $forward_step = 0;
134
135     // An array of the terms to be displayed on this page.
136     $current_page = [];
137
138     $delta = 0;
139     $term_deltas = [];
140     $tree = $this->storageController->loadTree($taxonomy_vocabulary->id(), 0, NULL, TRUE);
141     $tree_index = 0;
142     do {
143       // In case this tree is completely empty.
144       if (empty($tree[$tree_index])) {
145         break;
146       }
147       $delta++;
148       // Count entries before the current page.
149       if ($page && ($page * $page_increment) > $before_entries && !isset($back_step)) {
150         $before_entries++;
151         continue;
152       }
153       // Count entries after the current page.
154       elseif ($page_entries > $page_increment && isset($complete_tree)) {
155         $after_entries++;
156         continue;
157       }
158
159       // Do not let a term start the page that is not at the root.
160       $term = $tree[$tree_index];
161       if (isset($term->depth) && ($term->depth > 0) && !isset($back_step)) {
162         $back_step = 0;
163         while ($pterm = $tree[--$tree_index]) {
164           $before_entries--;
165           $back_step++;
166           if ($pterm->depth == 0) {
167             $tree_index--;
168             // Jump back to the start of the root level parent.
169             continue 2;
170           }
171         }
172       }
173       $back_step = isset($back_step) ? $back_step : 0;
174
175       // Continue rendering the tree until we reach the a new root item.
176       if ($page_entries >= $page_increment + $back_step + 1 && $term->depth == 0 && $root_entries > 1) {
177         $complete_tree = TRUE;
178         // This new item at the root level is the first item on the next page.
179         $after_entries++;
180         continue;
181       }
182       if ($page_entries >= $page_increment + $back_step) {
183         $forward_step++;
184       }
185
186       // Finally, if we've gotten down this far, we're rendering a term on this
187       // page.
188       $page_entries++;
189       $term_deltas[$term->id()] = isset($term_deltas[$term->id()]) ? $term_deltas[$term->id()] + 1 : 0;
190       $key = 'tid:' . $term->id() . ':' . $term_deltas[$term->id()];
191
192       // Keep track of the first term displayed on this page.
193       if ($page_entries == 1) {
194         $form['#first_tid'] = $term->id();
195       }
196       // Keep a variable to make sure at least 2 root elements are displayed.
197       if ($term->parents[0] == 0) {
198         $root_entries++;
199       }
200       $current_page[$key] = $term;
201     } while (isset($tree[++$tree_index]));
202
203     // Because we didn't use a pager query, set the necessary pager variables.
204     $total_entries = $before_entries + $page_entries + $after_entries;
205     $pager_total_items[0] = $total_entries;
206     $pager_page_array[0] = $page;
207     $pager_total[0] = ceil($total_entries / $page_increment);
208
209     // If this form was already submitted once, it's probably hit a validation
210     // error. Ensure the form is rebuilt in the same order as the user
211     // submitted.
212     $user_input = $form_state->getUserInput();
213     if (!empty($user_input)) {
214       // Get the POST order.
215       $order = array_flip(array_keys($user_input['terms']));
216       // Update our form with the new order.
217       $current_page = array_merge($order, $current_page);
218       foreach ($current_page as $key => $term) {
219         // Verify this is a term for the current page and set at the current
220         // depth.
221         if (is_array($user_input['terms'][$key]) && is_numeric($user_input['terms'][$key]['term']['tid'])) {
222           $current_page[$key]->depth = $user_input['terms'][$key]['term']['depth'];
223         }
224         else {
225           unset($current_page[$key]);
226         }
227       }
228     }
229
230     $errors = $form_state->getErrors();
231     $row_position = 0;
232     // Build the actual form.
233     $access_control_handler = $this->entityManager->getAccessControlHandler('taxonomy_term');
234     $create_access = $access_control_handler->createAccess($taxonomy_vocabulary->id(), NULL, [], TRUE);
235     if ($create_access->isAllowed()) {
236       $empty = $this->t('No terms available. <a href=":link">Add term</a>.', [':link' => Url::fromRoute('entity.taxonomy_term.add_form', ['taxonomy_vocabulary' => $taxonomy_vocabulary->id()])->toString()]);
237     }
238     else {
239       $empty = $this->t('No terms available.');
240     }
241     $form['terms'] = [
242       '#type' => 'table',
243       '#empty' => $empty,
244       '#attributes' => [
245         'id' => 'taxonomy',
246       ],
247     ];
248     $this->renderer->addCacheableDependency($form['terms'], $create_access);
249
250     // Only allow access to changing weights if the user has update access for
251     // all terms.
252     $change_weight_access = AccessResult::allowed();
253     foreach ($current_page as $key => $term) {
254       /** @var $term \Drupal\Core\Entity\EntityInterface */
255       $term = $this->entityManager->getTranslationFromContext($term);
256       $form['terms'][$key]['#term'] = $term;
257       $indentation = [];
258       if (isset($term->depth) && $term->depth > 0) {
259         $indentation = [
260           '#theme' => 'indentation',
261           '#size' => $term->depth,
262         ];
263       }
264       $form['terms'][$key]['term'] = [
265         '#prefix' => !empty($indentation) ? \Drupal::service('renderer')->render($indentation) : '',
266         '#type' => 'link',
267         '#title' => $term->getName(),
268         '#url' => $term->urlInfo(),
269       ];
270       if ($taxonomy_vocabulary->getHierarchy() != VocabularyInterface::HIERARCHY_MULTIPLE && count($tree) > 1) {
271         $parent_fields = TRUE;
272         $form['terms'][$key]['term']['tid'] = [
273           '#type' => 'hidden',
274           '#value' => $term->id(),
275           '#attributes' => [
276             'class' => ['term-id'],
277           ],
278         ];
279         $form['terms'][$key]['term']['parent'] = [
280           '#type' => 'hidden',
281           // Yes, default_value on a hidden. It needs to be changeable by the
282           // javascript.
283           '#default_value' => $term->parents[0],
284           '#attributes' => [
285             'class' => ['term-parent'],
286           ],
287         ];
288         $form['terms'][$key]['term']['depth'] = [
289           '#type' => 'hidden',
290           // Same as above, the depth is modified by javascript, so it's a
291           // default_value.
292           '#default_value' => $term->depth,
293           '#attributes' => [
294             'class' => ['term-depth'],
295           ],
296         ];
297       }
298       $update_access = $term->access('update', NULL, TRUE);
299       $change_weight_access = $change_weight_access->andIf($update_access);
300
301       if ($update_access->isAllowed()) {
302         $form['terms'][$key]['weight'] = [
303           '#type' => 'weight',
304           '#delta' => $delta,
305           '#title' => $this->t('Weight for added term'),
306           '#title_display' => 'invisible',
307           '#default_value' => $term->getWeight(),
308           '#attributes' => ['class' => ['term-weight']],
309         ];
310       }
311
312       if ($operations = $this->termListBuilder->getOperations($term)) {
313         $form['terms'][$key]['operations'] = [
314           '#type' => 'operations',
315           '#links' => $operations,
316         ];
317       }
318
319       $form['terms'][$key]['#attributes']['class'] = [];
320       if ($parent_fields) {
321         $form['terms'][$key]['#attributes']['class'][] = 'draggable';
322       }
323
324       // Add classes that mark which terms belong to previous and next pages.
325       if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) {
326         $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-preview';
327       }
328
329       if ($row_position !== 0 && $row_position !== count($tree) - 1) {
330         if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) {
331           $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-top';
332         }
333         elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
334           $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom';
335         }
336       }
337
338       // Add an error class if this row contains a form error.
339       foreach ($errors as $error_key => $error) {
340         if (strpos($error_key, $key) === 0) {
341           $form['terms'][$key]['#attributes']['class'][] = 'error';
342         }
343       }
344       $row_position++;
345     }
346
347     $form['terms']['#header'] = [$this->t('Name')];
348
349     $this->renderer->addCacheableDependency($form['terms'], $change_weight_access);
350     if ($change_weight_access->isAllowed()) {
351       $form['terms']['#header'][] = $this->t('Weight');
352       if ($parent_fields) {
353         $form['terms']['#tabledrag'][] = [
354           'action' => 'match',
355           'relationship' => 'parent',
356           'group' => 'term-parent',
357           'subgroup' => 'term-parent',
358           'source' => 'term-id',
359           'hidden' => FALSE,
360         ];
361         $form['terms']['#tabledrag'][] = [
362           'action' => 'depth',
363           'relationship' => 'group',
364           'group' => 'term-depth',
365           'hidden' => FALSE,
366         ];
367         $form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy';
368         $form['terms']['#attached']['drupalSettings']['taxonomy'] = [
369           'backStep' => $back_step,
370           'forwardStep' => $forward_step,
371         ];
372       }
373       $form['terms']['#tabledrag'][] = [
374         'action' => 'order',
375         'relationship' => 'sibling',
376         'group' => 'term-weight',
377       ];
378     }
379
380     $form['terms']['#header'][] = $this->t('Operations');
381
382     if (($taxonomy_vocabulary->getHierarchy() !== VocabularyInterface::HIERARCHY_MULTIPLE && count($tree) > 1) && $change_weight_access->isAllowed()) {
383       $form['actions'] = ['#type' => 'actions', '#tree' => FALSE];
384       $form['actions']['submit'] = [
385         '#type' => 'submit',
386         '#value' => $this->t('Save'),
387         '#button_type' => 'primary',
388       ];
389       $form['actions']['reset_alphabetical'] = [
390         '#type' => 'submit',
391         '#submit' => ['::submitReset'],
392         '#value' => $this->t('Reset to alphabetical'),
393       ];
394     }
395
396     $form['pager_pager'] = ['#type' => 'pager'];
397     return $form;
398   }
399
400   /**
401    * Form submission handler.
402    *
403    * Rather than using a textfield or weight field, this form depends entirely
404    * upon the order of form elements on the page to determine new weights.
405    *
406    * Because there might be hundreds or thousands of taxonomy terms that need to
407    * be ordered, terms are weighted from 0 to the number of terms in the
408    * vocabulary, rather than the standard -10 to 10 scale. Numbers are sorted
409    * lowest to highest, but are not necessarily sequential. Numbers may be
410    * skipped when a term has children so that reordering is minimal when a child
411    * is added or removed from a term.
412    *
413    * @param array $form
414    *   An associative array containing the structure of the form.
415    * @param \Drupal\Core\Form\FormStateInterface $form_state
416    *   The current state of the form.
417    */
418   public function submitForm(array &$form, FormStateInterface $form_state) {
419     // Sort term order based on weight.
420     uasort($form_state->getValue('terms'), ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
421
422     $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
423     // Update the current hierarchy type as we go.
424     $hierarchy = VocabularyInterface::HIERARCHY_DISABLED;
425
426     $changed_terms = [];
427     $tree = $this->storageController->loadTree($vocabulary->id(), 0, NULL, TRUE);
428
429     if (empty($tree)) {
430       return;
431     }
432
433     // Build a list of all terms that need to be updated on previous pages.
434     $weight = 0;
435     $term = $tree[0];
436     while ($term->id() != $form['#first_tid']) {
437       if ($term->parents[0] == 0 && $term->getWeight() != $weight) {
438         $term->setWeight($weight);
439         $changed_terms[$term->id()] = $term;
440       }
441       $weight++;
442       $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
443       $term = $tree[$weight];
444     }
445
446     // Renumber the current page weights and assign any new parents.
447     $level_weights = [];
448     foreach ($form_state->getValue('terms') as $tid => $values) {
449       if (isset($form['terms'][$tid]['#term'])) {
450         $term = $form['terms'][$tid]['#term'];
451         // Give terms at the root level a weight in sequence with terms on previous pages.
452         if ($values['term']['parent'] == 0 && $term->getWeight() != $weight) {
453           $term->setWeight($weight);
454           $changed_terms[$term->id()] = $term;
455         }
456         // Terms not at the root level can safely start from 0 because they're all on this page.
457         elseif ($values['term']['parent'] > 0) {
458           $level_weights[$values['term']['parent']] = isset($level_weights[$values['term']['parent']]) ? $level_weights[$values['term']['parent']] + 1 : 0;
459           if ($level_weights[$values['term']['parent']] != $term->getWeight()) {
460             $term->setWeight($level_weights[$values['term']['parent']]);
461             $changed_terms[$term->id()] = $term;
462           }
463         }
464         // Update any changed parents.
465         if ($values['term']['parent'] != $term->parents[0]) {
466           $term->parent->target_id = $values['term']['parent'];
467           $changed_terms[$term->id()] = $term;
468         }
469         $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
470         $weight++;
471       }
472     }
473
474     // Build a list of all terms that need to be updated on following pages.
475     for ($weight; $weight < count($tree); $weight++) {
476       $term = $tree[$weight];
477       if ($term->parents[0] == 0 && $term->getWeight() != $weight) {
478         $term->parent->target_id = $term->parents[0];
479         $term->setWeight($weight);
480         $changed_terms[$term->id()] = $term;
481       }
482       $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
483     }
484
485     // Save all updated terms.
486     foreach ($changed_terms as $term) {
487       $term->save();
488     }
489
490     // Update the vocabulary hierarchy to flat or single hierarchy.
491     if ($vocabulary->getHierarchy() != $hierarchy) {
492       $vocabulary->setHierarchy($hierarchy);
493       $vocabulary->save();
494     }
495     drupal_set_message($this->t('The configuration options have been saved.'));
496   }
497
498   /**
499    * Redirects to confirmation form for the reset action.
500    */
501   public function submitReset(array &$form, FormStateInterface $form_state) {
502     /** @var $vocabulary \Drupal\taxonomy\VocabularyInterface */
503     $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
504     $form_state->setRedirectUrl($vocabulary->urlInfo('reset-form'));
505   }
506
507 }