-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtaxonomy.module
1253 lines (1163 loc) · 44.1 KB
/
taxonomy.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Enables the organization of content into categories.
*/
use Drupal\taxonomy\VocabularyInterface;
use Drupal\node\Plugin\Core\Entity\Node;
use Drupal\taxonomy\Plugin\Core\Entity\Term;
use Drupal\taxonomy\Plugin\Core\Entity\Vocabulary;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Field\FieldDefinitionInterface;
/**
* Denotes that no term in the vocabulary has a parent.
*/
const TAXONOMY_HIERARCHY_DISABLED = 0;
/**
* Denotes that one or more terms in the vocabulary has a single parent.
*/
const TAXONOMY_HIERARCHY_SINGLE = 1;
/**
* Denotes that one or more terms in the vocabulary have multiple parents.
*/
const TAXONOMY_HIERARCHY_MULTIPLE = 2;
/**
* Users can create new terms in a free-tagging vocabulary when
* submitting a taxonomy_autocomplete_widget. We store a term object
* whose tid is 'autocreate' as a field data item during widget
* validation and then actually create the term if/when that field
* data item makes it to taxonomy_field_insert/update().
*/
/**
* Implements hook_help().
*/
function taxonomy_help($path, $arg) {
switch ($path) {
case 'admin/help#taxonomy':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Taxonomy module allows you to classify the content of your website. To classify content, you define <em>vocabularies</em> that contain related <em>terms</em>, and then assign the vocabularies to content types. For more information, see the online handbook entry for the <a href="@taxonomy">Taxonomy module</a>.', array('@taxonomy' => 'http://drupal.org/documentation/modules/taxonomy')) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating vocabularies') . '</dt>';
$output .= '<dd>' . t('Users with sufficient <a href="@perm">permissions</a> can create <em>vocabularies</em> and <em>terms</em> through the <a href="@taxo">Taxonomy page</a>. The page listing the terms provides a drag-and-drop interface for controlling the order of the terms and sub-terms within a vocabulary, in a hierarchical fashion. A <em>controlled vocabulary</em> classifying music by genre with terms and sub-terms could look as follows:', array('@taxo' => url('admin/structure/taxonomy'), '@perm' => url('admin/people/permissions', array('fragment'=>'module-taxonomy'))));
$output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
$output .= '<ul><li>' . t('<em>term</em>: Jazz') . '</li>';
$output .= '<ul><li>' . t('<em>sub-term</em>: Swing') . '</li>';
$output .= '<li>' . t('<em>sub-term</em>: Fusion') . '</li></ul></ul>';
$output .= '<ul><li>' . t('<em>term</em>: Rock') . '</li>';
$output .= '<ul><li>' . t('<em>sub-term</em>: Country rock') . '</li>';
$output .= '<li>' . t('<em>sub-term</em>: Hard rock') . '</li></ul></ul></ul>';
$output .= t('You can assign a sub-term to multiple parent terms. For example, <em>fusion</em> can be assigned to both <em>rock</em> and <em>jazz</em>.') . '</dd>';
$output .= '<dd>' . t('Terms in a <em>free-tagging vocabulary</em> can be built gradually as you create or edit content. This is often done used for blogs or photo management applications.') . '</dd>';
$output .= '<dt>' . t('Assigning vocabularies to content types') . '</dt>';
$output .= '<dd>' . t('Before you can use a new vocabulary to classify your content, a new Taxonomy term field must be added to a <a href="@ctedit">content type</a> on its <em>manage fields</em> page. When adding a taxonomy field, you choose a <em>widget</em> to use to enter the taxonomy information on the content editing page: a select list, checkboxes, radio buttons, or an auto-complete field (to build a free-tagging vocabulary). After choosing the field type and widget, on the subsequent <em>field settings</em> page you can choose the desired vocabulary, whether one or multiple terms can be chosen from the vocabulary, and other settings. The same vocabulary can be added to multiple content types, by using the "Re-use existing field" section on the manage fields page.', array('@ctedit' => url('admin/structure/types'))) . '</dd>';
$output .= '<dt>' . t('Classifying content') . '</dt>';
$output .= '<dd>' . t('After the vocabulary is assigned to the content type, you can start classifying content. The field with terms will appear on the content editing screen when you edit or <a href="@addnode">add new content</a>.', array('@addnode' => url('node/add'))) . '</dd>';
$output .= '<dt>' . t('Viewing listings and RSS feeds by term') . '</dt>';
$output .= '<dd>' . t("Each taxonomy term automatically provides a page listing content that has its classification, and a corresponding RSS feed. For example, if the taxonomy term <em>country rock</em> has the ID 123 (you can see this by looking at the URL when hovering on the linked term, which you can click to navigate to the listing page), then you will find this list at the path <em>taxonomy/term/123</em>. The RSS feed will use the path <em>taxonomy/term/123/feed</em> (the RSS icon for this term's listing will automatically display in your browser's address bar when viewing the listing page).") . '</dd>';
$output .= '<dt>' . t('Extending Taxonomy module') . '</dt>';
$output .= '<dd>' . t('There are <a href="@taxcontrib">many contributed modules</a> that extend the behavior of the Taxonomy module for both display and organization of terms.', array('@taxcontrib' => 'http://drupal.org/project/modules?filters=tid:71&solrsort=sis_project_release_usage%20desc'));
$output .= '</dl>';
return $output;
case 'admin/structure/taxonomy':
$output = '<p>' . t('Taxonomy is for categorizing content. Terms are grouped into vocabularies. For example, a vocabulary called "Fruit" would contain the terms "Apple" and "Banana".') . '</p>';
return $output;
case 'admin/structure/taxonomy/manage/%':
$vocabulary = entity_load('taxonomy_vocabulary', $arg[4]);
switch ($vocabulary->hierarchy) {
case TAXONOMY_HIERARCHY_DISABLED:
return '<p>' . t('You can reorganize the terms in %capital_name using their drag-and-drop handles, and group terms under a parent term by sliding them under and to the right of the parent.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
case TAXONOMY_HIERARCHY_SINGLE:
return '<p>' . t('%capital_name contains terms grouped under parent terms. You can reorganize the terms in %capital_name using their drag-and-drop handles.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
case TAXONOMY_HIERARCHY_MULTIPLE:
return '<p>' . t('%capital_name contains terms with multiple parents. Drag and drop of terms with multiple parents is not supported, but you can re-enable drag-and-drop support by editing each term to include only a single parent.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) . '</p>';
}
}
}
/**
* Implements hook_permission().
*/
function taxonomy_permission() {
$permissions = array(
'administer taxonomy' => array(
'title' => t('Administer vocabularies and terms'),
),
);
foreach (entity_load_multiple('taxonomy_vocabulary') as $vocabulary) {
$permissions += array(
'edit terms in ' . $vocabulary->id() => array(
'title' => t('Edit terms in %vocabulary', array('%vocabulary' => $vocabulary->name)),
),
);
$permissions += array(
'delete terms in ' . $vocabulary->id() => array(
'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
),
);
}
return $permissions;
}
/**
* Implements hook_entity_bundle_info().
*/
function taxonomy_entity_bundle_info() {
$bundles = array();
foreach (taxonomy_vocabulary_get_names() as $id) {
$config = config('taxonomy.vocabulary.' . $id);
$bundles['taxonomy_term'][$id]['label'] = $config->get('name');
}
return $bundles;
}
/**
* Entity URI callback.
*/
function taxonomy_term_uri($term) {
return array(
'path' => 'taxonomy/term/' . $term->id(),
);
}
/**
* Implements hook_field_extra_fields().
*/
function taxonomy_field_extra_fields() {
$return = array();
foreach (entity_get_bundles('taxonomy_term') as $bundle => $bundle_info) {
$return['taxonomy_term'][$bundle] = array(
'form' => array(
'name' => array(
'label' => t('Name'),
'description' => t('Term name textfield'),
'weight' => -5,
),
'description' => array(
'label' => t('Description'),
'description' => t('Term description textarea'),
'weight' => 0,
),
),
'display' => array(
'description' => array(
'label' => t('Description'),
'description' => t('Term description'),
'weight' => 0,
),
),
);
}
return $return;
}
/**
* Return nodes attached to a term across all field instances.
*
* This function requires taxonomy module to be maintaining its own tables,
* and will return an empty array if it is not. If using other field storage
* methods alternatives methods for listing terms will need to be used.
*
* @param $tid
* The term ID.
* @param $pager
* Boolean to indicate whether a pager should be used.
* @param $limit
* Integer. The maximum number of nodes to find.
* Set to FALSE for no limit.
* @param $order
* An array of fields and directions.
*
* @return
* An array of nids matching the query.
*/
function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
if (!config('taxonomy.settings')->get('maintain_index_table')) {
return array();
}
$query = db_select('taxonomy_index', 't');
$query->addTag('node_access');
$query->addMetaData('base_table', 'taxonomy_index');
$query->condition('tid', $tid);
if ($pager) {
$count_query = clone $query;
$count_query->addExpression('COUNT(t.nid)');
$query = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender');
if ($limit !== FALSE) {
$query = $query->limit($limit);
}
$query->setCountQuery($count_query);
}
else {
if ($limit !== FALSE) {
$query->range(0, $limit);
}
}
$query->addField('t', 'nid');
$query->addField('t', 'tid');
foreach ($order as $field => $direction) {
$query->orderBy($field, $direction);
// ORDER BY fields need to be loaded too, assume they are in the form
// table_alias.name
list($table_alias, $name) = explode('.', $field);
$query->addField($table_alias, $name);
}
return $query->execute()->fetchCol();
}
/**
* Implements hook_theme().
*/
function taxonomy_theme() {
return array(
'taxonomy_term' => array(
'render element' => 'elements',
'template' => 'taxonomy-term',
),
);
}
/**
* Implements hook_menu().
*/
function taxonomy_menu() {
$items['admin/structure/taxonomy'] = array(
'title' => 'Taxonomy',
'description' => 'Manage tagging, categorization, and classification of your content.',
'route_name' => 'taxonomy_vocabulary_list',
);
$items['admin/structure/taxonomy/list'] = array(
'title' => 'List',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['admin/structure/taxonomy/add'] = array(
'title' => 'Add vocabulary',
'page callback' => 'taxonomy_vocabulary_add',
'access callback' => 'entity_page_create_access',
'access arguments' => array('taxonomy_vocabulary'),
'type' => MENU_LOCAL_ACTION,
'file' => 'taxonomy.admin.inc',
);
$items['taxonomy/term/%taxonomy_term'] = array(
'title' => 'Taxonomy term',
'title callback' => 'taxonomy_term_title',
'title arguments' => array(2),
'page callback' => 'taxonomy_term_page',
'page arguments' => array(2),
'access callback' => 'entity_page_access',
'access arguments' => array(2, 'view'),
'file' => 'taxonomy.pages.inc',
);
$items['taxonomy/term/%taxonomy_term/view'] = array(
'title' => 'View',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['taxonomy/term/%taxonomy_term/edit'] = array(
'title' => 'Edit',
'page callback' => 'entity_get_form',
'page arguments' => array(2, 'default', array()),
'access callback' => 'entity_page_access',
'access arguments' => array(2, 'update'),
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
'weight' => 10,
'file' => 'taxonomy.admin.inc',
);
$items['taxonomy/term/%taxonomy_term/delete'] = array(
'title' => 'Delete',
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
'weight' => 20,
'route_name' => 'taxonomy_term_delete',
);
$items['taxonomy/term/%taxonomy_term/feed'] = array(
'title' => 'Taxonomy term',
'title callback' => 'taxonomy_term_title',
'title arguments' => array(2),
'page callback' => 'taxonomy_term_feed',
'page arguments' => array(2),
'access callback' => 'entity_page_access',
'access arguments' => array(2, 'view'),
'type' => MENU_CALLBACK,
'file' => 'taxonomy.pages.inc',
);
$items['taxonomy/autocomplete/%'] = array(
'title' => 'Autocomplete taxonomy',
'page callback' => 'taxonomy_autocomplete',
'page arguments' => array(2),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
'file' => 'taxonomy.pages.inc',
);
$items['admin/structure/taxonomy/manage/%taxonomy_vocabulary'] = array(
'title callback' => 'entity_page_label',
'title arguments' => array(4),
'page callback' => 'drupal_get_form',
'page arguments' => array('taxonomy_overview_terms', 4),
'access callback' => 'entity_page_access',
'access arguments' => array(4, 'view'),
'file' => 'taxonomy.admin.inc',
);
$items['admin/structure/taxonomy/manage/%taxonomy_vocabulary/list'] = array(
'title' => 'List',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['admin/structure/taxonomy/manage/%taxonomy_vocabulary/edit'] = array(
'title' => 'Edit',
'page callback' => 'entity_get_form',
'page arguments' => array(4),
'access callback' => 'entity_page_access',
'access arguments' => array(4, 'update'),
'type' => MENU_LOCAL_TASK,
'file' => 'taxonomy.admin.inc',
);
$items['admin/structure/taxonomy/%taxonomy_vocabulary/delete'] = array(
'title' => 'Delete',
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
'weight' => 20,
'route_name' => 'taxonomy_vocabulary_delete',
);
$items['admin/structure/taxonomy/manage/%taxonomy_vocabulary/add'] = array(
'title' => 'Add term',
'route_name' => 'taxonomy_term_add',
'type' => MENU_LOCAL_ACTION,
);
return $items;
}
/**
* Implements hook_admin_paths().
*/
function taxonomy_admin_paths() {
$paths = array(
'taxonomy/term/*/edit' => TRUE,
'taxonomy/term/*/delete' => TRUE,
'taxonomy/term/*/translations' => TRUE,
'taxonomy/term/*/translations/*' => TRUE,
);
return $paths;
}
/**
* Checks and updates the hierarchy flag of a vocabulary.
*
* Checks the current parents of all terms in a vocabulary and updates the
* vocabulary's hierarchy setting to the lowest possible level. If no term
* has parent terms then the vocabulary will be given a hierarchy of
* TAXONOMY_HIERARCHY_DISABLED. If any term has a single parent then the
* vocabulary will be given a hierarchy of TAXONOMY_HIERARCHY_SINGLE. If any
* term has multiple parents then the vocabulary will be given a hierarchy of
* TAXONOMY_HIERARCHY_MULTIPLE.
*
* @param \Drupal\taxonomy\VocabularyInterface $vocabulary
* A taxonomy vocabulary entity.
* @param $changed_term
* An array of the term structure that was updated.
*
* @return
* An integer that represents the level of the vocabulary's hierarchy.
*/
function taxonomy_check_vocabulary_hierarchy(VocabularyInterface $vocabulary, $changed_term) {
$tree = taxonomy_get_tree($vocabulary->id());
$hierarchy = TAXONOMY_HIERARCHY_DISABLED;
foreach ($tree as $term) {
// Update the changed term with the new parent value before comparison.
if ($term->tid == $changed_term['tid']) {
$term = (object) $changed_term;
$term->parents = $term->parent;
}
// Check this term's parent count.
if (count($term->parents) > 1) {
$hierarchy = TAXONOMY_HIERARCHY_MULTIPLE;
break;
}
elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
$hierarchy = TAXONOMY_HIERARCHY_SINGLE;
}
}
if ($hierarchy != $vocabulary->hierarchy) {
$vocabulary->hierarchy = $hierarchy;
$vocabulary->save();
}
return $hierarchy;
}
/**
* Generates an array which displays a term detail page.
*
* @param Drupal\taxonomy\Plugin\Core\Entity\Term $term
* A taxonomy term object.
* @param string $view_mode
* View mode, e.g. 'full', 'teaser'...
* @param string $langcode
* (optional) A language code to use for rendering. Defaults to the global
* content language of the current request.
*
* @return array
* A $page element suitable for use by drupal_page_render().
*/
function taxonomy_term_view(Term $term, $view_mode = 'full', $langcode = NULL) {
return entity_view($term, $view_mode, $langcode);
}
/**
* Constructs a drupal_render() style array from an array of loaded terms.
*
* @param array $terms
* An array of taxonomy terms as returned by entity_load_multiple('taxonomy_term').
* @param string $view_mode
* View mode, e.g. 'full', 'teaser'...
* @param string $langcode
* (optional) A language code to use for rendering. Defaults to the global
* content language of the current request.
*
* @return array
* An array in the format expected by drupal_render().
*/
function taxonomy_term_view_multiple(array $terms, $view_mode = 'full', $langcode = NULL) {
return entity_view_multiple($terms, $view_mode, $langcode);
}
/**
* Prepares variables for taxonomy term templates.
*
* Default template: taxonomy-term.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the taxonomy term and any
* fields attached to the term. Properties used:
* - #term: The term object.
* - #view_mode: The current view mode for this taxonomy term, e.g.
* 'full' or 'teaser'.
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_taxonomy_term(&$variables) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
$variables['term'] = $variables['elements']['#term'];
$term = $variables['term'];
$uri = $term->uri();
$variables['url'] = url($uri['path'], $uri['options']);
// We use name here because that is what appears in the UI.
$variables['name'] = check_plain($term->label());
$variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
// Helpful $content variable for templates.
$variables['content'] = array();
foreach (element_children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
// field_attach_preprocess() overwrites the $[field_name] variables with the
// values of the field in the language that was selected for display, instead
// of the raw values in $term->[field_name], which contain all values in all
// languages.
field_attach_preprocess($term, $variables['content'], $variables);
// Gather classes, and clean up name so there are no underscores.
$variables['attributes']['class'][] = 'taxonomy-term';
$vocabulary_name_css = str_replace('_', '-', $term->bundle());
$variables['attributes']['class'][] = 'vocabulary-' . $vocabulary_name_css;
$variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->bundle();
$variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->id();
}
/**
* Returns whether the current page is the page of the passed-in term.
*
* @param Drupal\taxonomy\Plugin\Core\Entity\Term $term
* A taxonomy term entity.
*/
function taxonomy_term_is_page(Term $term) {
$page_term = menu_get_object('taxonomy_term', 2);
return (!empty($page_term) ? $page_term->id() == $term->id() : FALSE);
}
/**
* Clear all static cache variables for terms.
*/
function taxonomy_terms_static_reset() {
Drupal::entityManager()->getStorageController('taxonomy_term')->resetCache();
}
/**
* Clear all static cache variables for vocabularies.
*
* @param $ids
* An array of ids to reset in entity controller cache.
*/
function taxonomy_vocabulary_static_reset(array $ids = NULL) {
Drupal::entityManager()->getStorageController('taxonomy_vocabulary')->resetCache($ids);
}
/**
* Get names for all taxonomy vocabularies.
*
* @return array
* A list of existing vocabulary IDs.
*/
function taxonomy_vocabulary_get_names() {
$names = &drupal_static(__FUNCTION__);
if (!isset($names)) {
$names = array();
$config_names = config_get_storage_names_with_prefix('taxonomy.vocabulary.');
foreach ($config_names as $config_name) {
$id = substr($config_name, strlen('taxonomy.vocabulary.'));
$names[$id] = $id;
}
}
return $names;
}
/**
* Finds all parents of a given term ID.
*
* @param $tid
* A taxonomy term ID.
*
* @return
* An array of term objects which are the parents of the term $tid, or an
* empty array if parents are not found.
*/
function taxonomy_term_load_parents($tid) {
$parents = &drupal_static(__FUNCTION__, array());
if ($tid && !isset($parents[$tid])) {
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
$query->addField('t', 'tid');
$query->condition('h.tid', $tid);
$query->addTag('term_access');
$query->orderBy('t.weight');
$query->orderBy('t.name');
$tids = $query->execute()->fetchCol();
$parents[$tid] = entity_load_multiple('taxonomy_term', $tids);
}
return isset($parents[$tid]) ? $parents[$tid] : array();
}
/**
* Find all ancestors of a given term ID.
*/
function taxonomy_term_load_parents_all($tid) {
$cache = &drupal_static(__FUNCTION__, array());
if (isset($cache[$tid])) {
return $cache[$tid];
}
$parents = array();
if ($term = entity_load('taxonomy_term', $tid)) {
$parents[] = $term;
$n = 0;
while ($parent = taxonomy_term_load_parents($parents[$n]->id())) {
$parents = array_merge($parents, $parent);
$n++;
}
}
$cache[$tid] = $parents;
return $parents;
}
/**
* Finds all children of a term ID.
*
* @param $tid
* A taxonomy term ID.
* @param $vid
* An optional vocabulary ID to restrict the child search.
*
* @return
* An array of term objects that are the children of the term $tid, or an
* empty array when no children exist.
*/
function taxonomy_term_load_children($tid, $vid = NULL) {
$children = &drupal_static(__FUNCTION__, array());
if ($tid && !isset($children[$tid])) {
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query->addField('t', 'tid');
$query->condition('h.parent', $tid);
if ($vid) {
$query->condition('t.vid', $vid);
}
$query->addTag('term_access');
$query->orderBy('t.weight');
$query->orderBy('t.name');
$tids = $query->execute()->fetchCol();
$children[$tid] = entity_load_multiple('taxonomy_term', $tids);
}
return isset($children[$tid]) ? $children[$tid] : array();
}
/**
* Create a hierarchical representation of a vocabulary.
*
* @param $vid
* The vocabulary ID to generate the tree for.
* @param $parent
* The term ID under which to generate the tree. If 0, generate the tree
* for the entire vocabulary.
* @param $max_depth
* The number of levels of the tree to return. Leave NULL to return all levels.
* @param $load_entities
* If TRUE, a full entity load will occur on the term objects. Otherwise they
* are partial objects queried directly from the {taxonomy_term_data} table to
* save execution time and memory consumption when listing large numbers of
* terms. Defaults to FALSE.
*
* @return
* An array of all term objects in the tree. Each term object is extended
* to have "depth" and "parents" attributes in addition to its normal ones.
* Results are statically cached. Term objects will be partial or complete
* depending on the $load_entities parameter.
*/
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
$children = &drupal_static(__FUNCTION__, array());
$parents = &drupal_static(__FUNCTION__ . ':parents', array());
$terms = &drupal_static(__FUNCTION__ . ':terms', array());
// We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
// term and its children, too.
if (!isset($children[$vid])) {
$children[$vid] = array();
$parents[$vid] = array();
$terms[$vid] = array();
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$result = $query
->addTag('term_access')
->fields('t')
->fields('h', array('parent'))
->condition('t.vid', $vid)
->orderBy('t.weight')
->orderBy('t.name')
->execute();
foreach ($result as $term) {
$children[$vid][$term->parent][] = $term->tid;
$parents[$vid][$term->tid][] = $term->parent;
$terms[$vid][$term->tid] = $term;
}
}
// Load full entities, if necessary. The entity controller statically
// caches the results.
if ($load_entities) {
$term_entities = entity_load_multiple('taxonomy_term', array_keys($terms[$vid]));
}
$max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
$tree = array();
// Keeps track of the parents we have to process, the last entry is used
// for the next processing step.
$process_parents = array();
$process_parents[] = $parent;
// Loops over the parent terms and adds its children to the tree array.
// Uses a loop instead of a recursion, because it's more efficient.
while (count($process_parents)) {
$parent = array_pop($process_parents);
// The number of parents determines the current depth.
$depth = count($process_parents);
if ($max_depth > $depth && !empty($children[$vid][$parent])) {
$has_children = FALSE;
$child = current($children[$vid][$parent]);
do {
if (empty($child)) {
break;
}
$term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
if (isset($parents[$vid][$load_entities ? $term->id() : $term->tid])) {
// Clone the term so that the depth attribute remains correct
// in the event of multiple parents.
$term = clone $term;
}
$term->depth = $depth;
unset($term->parent);
$tid = $load_entities ? $term->id() : $term->tid;
$term->parents = $parents[$vid][$tid];
$tree[] = $term;
if (!empty($children[$vid][$tid])) {
$has_children = TRUE;
// We have to continue with this parent later.
$process_parents[] = $parent;
// Use the current term as parent for the next iteration.
$process_parents[] = $tid;
// Reset pointers for child lists because we step in there more often
// with multi parents.
reset($children[$vid][$tid]);
// Move pointer so that we get the correct term the next time.
next($children[$vid][$parent]);
break;
}
} while ($child = next($children[$vid][$parent]));
if (!$has_children) {
// We processed all terms in this hierarchy-level, reset pointer
// so that this function works the next time it gets called.
reset($children[$vid][$parent]);
}
}
}
return $tree;
}
/**
* Try to map a string to an existing term, as for glossary use.
*
* Provides a case-insensitive and trimmed mapping, to maximize the
* likelihood of a successful match.
*
* @param $name
* Name of the term to search for.
* @param $vocabulary
* (optional) Vocabulary machine name to limit the search. Defaults to NULL.
*
* @return
* An array of matching term objects.
*/
function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
$values = array('name' => trim($name));
if (isset($vocabulary)) {
$vocabularies = taxonomy_vocabulary_get_names();
if (isset($vocabularies[$vocabulary])){
$values['vid'] = $vocabulary;
}
else {
// Return an empty array when filtering by a non-existing vocabulary.
return array();
}
}
return entity_load_multiple_by_properties('taxonomy_term', $values);
}
/**
* Load multiple taxonomy terms based on certain conditions.
*
* This function should be used whenever you need to load more than one term
* from the database. Terms are loaded into memory and will not require
* database access if loaded again during the same page request.
*
* @see entity_load_multiple()
* @see Drupal\Core\Entity\Query\EntityQueryInterface
*
* @deprecated use entity_load_multiple('taxonomy_term', $tids) instead.
*
* @param array $tids
* (optional) An array of entity IDs. If omitted, all entities are loaded.
*
* @return array
* An array of taxonomy term entities, indexed by tid. When no results are
* found, an empty array is returned.
*/
function taxonomy_term_load_multiple(array $tids = NULL) {
return entity_load_multiple('taxonomy_term', $tids);
}
/**
* Loads multiple taxonomy vocabularies based on certain conditions.
*
* This function should be used whenever you need to load more than one
* vocabulary from the database. Terms are loaded into memory and will not
* require database access if loaded again during the same page request.
*
* @see entity_load_multiple()
*
* @deprecated use entity_load_multiple('taxonomy_vocabulary', $vids) instead.
*
* @param array $vids
* (optional) An array of entity IDs. If omitted, all entities are loaded.
*
* @return array
* An array of vocabulary objects, indexed by vid.
*/
function taxonomy_vocabulary_load_multiple(array $vids = NULL) {
return entity_load_multiple('taxonomy_vocabulary', $vids);
}
/**
* Sorts vocabularies by its weight and label.
*
* @param array $vocabularies
* An array of \Drupal\taxonomy\Plugin\Core\Entity\Vocabulary objects.
*/
function taxonomy_vocabulary_sort(array &$vocabularies = array()) {
// @todo Remove error suppressing when http://drupal.org/node/1799600 is
// fixed.
@uasort($vocabularies, 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');
}
/**
* Return the taxonomy vocabulary entity matching a vocabulary ID.
*
* @deprecated use entity_load('taxonomy_vocabulary', $vid) instead.
*
* @param int $vid
* The vocabulary's ID.
*
* @return \Drupal\taxonomy\Plugin\Core\Entity\Vocabulary|null
* The taxonomy vocabulary entity, if exists, NULL otherwise. Results are
* statically cached.
*/
function taxonomy_vocabulary_load($vid) {
return entity_load('taxonomy_vocabulary', $vid);
}
/**
* Return the taxonomy term entity matching a term ID.
*
* @deprecated use entity_load('taxonomy_term', $tid) instead.
*
* @param $tid
* A term's ID
*
* @return \Drupal\taxonomy\Plugin\Core\Entity\Term|null
* A taxonomy term entity, or NULL if the term was not found. Results are
* statically cached.
*/
function taxonomy_term_load($tid) {
if (!is_numeric($tid)) {
return NULL;
}
return entity_load('taxonomy_term', $tid);
}
/**
* Implodes a list of tags of a certain vocabulary into a string.
*
* @see drupal_explode_tags()
*/
function taxonomy_implode_tags($tags, $vid = NULL) {
$typed_tags = array();
foreach ($tags as $tag) {
// Extract terms belonging to the vocabulary in question.
if (!isset($vid) || $tag->bundle() == $vid) {
// Make sure we have a completed loaded taxonomy term.
if ($tag instanceof EntityInterface && $label = $tag->label()) {
// Commas and quotes in tag names are special cases, so encode 'em.
if (strpos($label, ',') !== FALSE || strpos($label, '"') !== FALSE) {
$typed_tags[] = '"' . str_replace('"', '""', $label) . '"';
}
else {
$typed_tags[] = $label;
}
}
}
}
return implode(', ', $typed_tags);
}
/**
* Implements hook_field_info().
*
* Field settings:
* - allowed_values: a list array of one or more vocabulary trees:
* - vocabulary: a vocabulary machine name.
* - parent: a term ID of a term whose children are allowed. This should be
* '0' if all terms in a vocabulary are allowed. The allowed values do not
* include the parent term.
*
*/
function taxonomy_field_info() {
return array(
'taxonomy_term_reference' => array(
'label' => t('Term reference'),
'description' => t('This field stores a reference to a taxonomy term.'),
'default_widget' => 'options_select',
'default_formatter' => 'taxonomy_term_reference_link',
'class' => 'Drupal\taxonomy\Type\TaxonomyTermReferenceItem',
'settings' => array(
'options_list_callback' => NULL,
'allowed_values' => array(
array(
'vocabulary' => '',
'parent' => '0',
),
),
),
),
);
}
/**
* Implements hook_field_widget_info_alter().
*/
function taxonomy_field_widget_info_alter(&$info) {
$info['options_select']['field_types'][] = 'taxonomy_term_reference';
$info['options_buttons']['field_types'][] = 'taxonomy_term_reference';
}
/**
* Implements hook_options_list().
*/
function taxonomy_options_list(FieldDefinitionInterface $field_definition, EntityInterface $entity) {
$function = $field_definition->getFieldSetting('options_list_callback') ?: 'taxonomy_allowed_values';
return $function($field_definition, $entity);
}
/**
* Implements hook_field_validate().
*
* Taxonomy field settings allow for either a single vocabulary ID, multiple
* vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed
* values, although only the first of these is supported via the field UI.
* Confirm that terms entered as values meet at least one of these conditions.
*
* Possible error codes:
* - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
*/
function taxonomy_field_validate(EntityInterface $entity = NULL, $field, $instance, $langcode, $items, &$errors) {
// Build an array of existing term IDs so they can be loaded with
// entity_load_multiple('taxonomy_term');
foreach ($items as $delta => $item) {
if (!empty($item['target_id']) && $item['target_id'] != 'autocreate') {
$tids[] = $item['target_id'];
}
}
if (!empty($tids)) {
$terms = entity_load_multiple('taxonomy_term', $tids);
// Check each existing item to ensure it can be found in the
// allowed values for this field.
foreach ($items as $delta => $item) {
$validate = TRUE;
if (!empty($item['target_id']) && $item['target_id'] != 'autocreate') {
$validate = FALSE;
foreach ($field['settings']['allowed_values'] as $settings) {
// If no parent is specified, check if the term is in the vocabulary.
if (isset($settings['vocabulary']) && empty($settings['parent'])) {
if ($settings['vocabulary'] == $terms[$item['target_id']]->bundle()) {
$validate = TRUE;
break;
}
}
// If a parent is specified, then to validate it must appear in the
// array returned by taxonomy_term_load_parents_all().
elseif (!empty($settings['parent'])) {
$ancestors = taxonomy_term_load_parents_all($item['target_id']);
foreach ($ancestors as $ancestor) {
if ($ancestor->id() == $settings['parent']) {
$validate = TRUE;
break 2;
}
}
}
}
}
if (!$validate) {
$errors[$field['field_name']][$langcode][$delta][] = array(
'error' => 'taxonomy_term_reference_illegal_value',
'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
);
}
}
}
}
/**
* Implements hook_field_is_empty().
*/
function taxonomy_field_is_empty($item, $field_type) {
return !is_array($item) || (empty($item['target_id']) && empty($item['entity']));
}
/**
* Returns the set of valid terms for a taxonomy field.
*
* @param \Drupal\Core\Entity\Field\FieldDefinitionInterface $field_definition
* The field definition.
* @param \Drupal\Core\Entity\EntityInterface $entity