-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmetatag.module
2308 lines (2070 loc) · 78.9 KB
/
metatag.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
* Primary hook implementations for Metatag.
*/
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Language\Language;
/**
* Implements hook_help().
*/
function metatag_help($path, $arg) {
if ($path == 'admin/config/search/metatags') {
return '<p>' . t('To view a summary of the default meta tags and the inheritance, click on a meta tag type.') . '</p>';
}
elseif ($path == 'admin/help#metatag') {
return '<p>' . t('The Metatag module provides a options to let each page have customized meta data added to the "meta" tags in the HEAD section of the document.') . '</p>';
}
elseif ($path == 'admin/config/search/metatags/bulk-revert') {
// return '<p>' . t('This form <strong>will wipe out</strong> all custom meta tags for the selected entities, reverting them to the default configuration assigned at the <a href="@url">Defaults tab</a>. For example, if the meta tags are changed for an article they will be removed if the "Node: Article" checkbox is selected.', array('@url' => url('admin/config/search/metatags'))) . '</p>';
}
}
/**
* Implements hook_theme().
*/
function metatag_theme() {
$info['metatag'] = array(
'render element' => 'element',
'file' => 'metatag.theme.inc',
);
$info['metatag_http_equiv'] = array(
'render element' => 'element',
'file' => 'metatag.theme.inc',
);
$info['metatag_link_rel'] = array(
'render element' => 'element',
'file' => 'metatag.theme.inc',
);
$info['metatag_link_rev'] = array(
'render element' => 'element',
'file' => 'metatag.theme.inc',
);
$info['metatag_property'] = array(
'render element' => 'element',
'file' => 'metatag.theme.inc',
);
return $info;
}
/**
* Implements hook_ctools_plugin_api().
*/
function metatag_ctools_plugin_api($owner, $api) {
if ($owner == 'metatag' && $api == 'metatag') {
return array('version' => 1);
}
}
/**
* Implements hook_hook_info().
*/
function metatag_hook_info() {
$hooks = array(
'metatag_config_default',
'metatag_config_default_alter',
'metatag_config_delete',
'metatag_config_insert',
'metatag_config_instance_info',
'metatag_config_instance_info_alter',
'metatag_config_load',
'metatag_config_load_presave',
'metatag_config_update',
'metatag_info',
'metatag_info_alter',
);
return array_fill_keys($hooks, array('group' => 'metatag'));
}
/**
* Implements hook_permission().
*/
function metatag_permission() {
$permissions['administer meta tags'] = array(
'title' => t('Administer meta tags'),
'restrict access' => TRUE,
'description' => t('Control the main settings pages and modify per-object meta tags.'),
);
$permissions['edit meta tags'] = array(
'title' => t('Edit meta tags'),
'description' => t('Modify meta tags on individual entity records (nodes, terms, users, etc).'),
);
// Optional extended edit permissions.
if (\Drupal::config('metatag.settings')->get('metatag_extended_permissions')) {
$permissions['edit meta tags']['description'] .= '<br />' . t('<em>Extended Permissions</em> has been enabled. Roles have the :admin permission will see all meta tags on edit forms, otherwise the permissions below will control which meta tags are available and are needed in addition to <em>Edit meta tags</em>.', array(':admin' => t('Administer meta tags')));
$metatags = metatag_get_info();
foreach ($metatags['tags'] as $metatag_name => $metatag) {
$permissions['edit meta tag: ' . $metatag_name] = array(
'title' => t('Extended permission: Edit :tag meta tag', array(':tag' => $metatag['label'])),
'description' => t('Customize the :tag meta tag on individual forms.', array(':tag' => $metatag['label'])),
);
}
}
return $permissions;
}
/**
* Implements hook_menu().
*/
function metatag_menu() {
$items['admin/config/search/metatags'] = array(
'title' => 'Metatag',
'description' => 'Configure Metatag defaults.',
'page callback' => 'metatag_config_overview',
'access arguments' => array('administer meta tags'),
'file' => 'metatag.admin.inc',
);
$items['admin/config/search/metatags/config'] = array(
'title' => 'Defaults',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/config/search/metatags/config/add'] = array(
'title' => 'Add a Metatag default',
'page callback' => 'drupal_get_form',
'page arguments' => array('metatag_config_add_form'),
'access arguments' => array('administer meta tags'),
'file' => 'metatag.admin.inc',
'type' => MENU_LOCAL_ACTION,
);
$items['admin/config/search/metatags/config/%metatag_config'] = array(
'title callback' => 'metatag_config_title',
'title arguments' => array(5),
'page callback' => 'drupal_get_form',
'page arguments' => array('metatag_config_edit_form', 5),
'access arguments' => array('administer meta tags'),
'file' => 'metatag.admin.inc',
);
$items['admin/config/search/metatags/config/%metatag_config/edit'] = array(
'title' => 'Edit',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/config/search/metatags/config/%metatag_config/enable'] = array(
'title' => 'Enable',
'page callback' => 'metatag_config_enable',
'page arguments' => array(5),
'access callback' => 'metatag_config_access',
'access arguments' => array('enable', 5),
'file' => 'metatag.admin.inc',
);
$items['admin/config/search/metatags/config/%metatag_config/disable'] = array(
'title' => 'Disable',
'page callback' => 'metatag_config_disable',
'page arguments' => array(5),
'access callback' => 'metatag_config_access',
'access arguments' => array('disable', 5),
'file' => 'metatag.admin.inc',
);
$items['admin/config/search/metatags/config/%metatag_config/revert'] = array(
'title' => 'Revert',
'page callback' => 'drupal_get_form',
'page arguments' => array('metatag_config_delete_form', 5),
'access callback' => 'metatag_config_access',
'access arguments' => array('revert', 5),
'file' => 'metatag.admin.inc',
'type' => MENU_LOCAL_TASK,
);
$items['admin/config/search/metatags/config/%metatag_config/delete'] = array(
'title' => 'Delete',
'page callback' => 'drupal_get_form',
'page arguments' => array('metatag_config_delete_form', 5),
'access callback' => 'metatag_config_access',
'access arguments' => array('delete', 5),
'file' => 'metatag.admin.inc',
);
$items['admin/config/search/metatags/config/%metatag_config/export'] = array(
'title' => 'Export',
'page callback' => 'metatag_config_export_form',
'page arguments' => array(5),
'access arguments' => array('administer meta tags'),
'file' => 'metatag.admin.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 10,
);
$items['admin/config/search/metatags/settings'] = array(
'title' => 'Advanced settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('metatag_admin_settings_form'),
'access arguments' => array('administer meta tags'),
'type' => MENU_LOCAL_TASK,
'weight' => 30,
'file' => 'metatag.admin.inc',
);
$items['admin/config/search/metatags/bulk-revert'] = array(
'title' => 'Bulk revert',
'page callback' => 'drupal_get_form',
'page arguments' => array('metatag_bulk_revert_form'),
'access arguments' => array('administer meta tags'),
'type' => MENU_LOCAL_TASK,
'weight' => 40,
'file' => 'metatag.admin.inc',
);
return $items;
}
/**
* Implements hook_flush_caches().
*/
function metatag_flush_caches() {
return array('cache_metatag');
}
/**
* Load a metatag configuration record with all the defaults merged in.
*
* For example, given the configuration instance 'node:article', this function
* will load the configuration records for 'node:article', then 'node', and
* then finally 'global', with each attempt using an array merge.
*
* The levels of defaults is arranged by splitting the $instance variable by
* the colon character, and always using a 'global' instance at the end.
*/
function metatag_config_load_with_defaults($instance, $include_global = TRUE) {
$defaults = &drupal_static(__FUNCTION__, array());
// Statically cache defaults since they can include multiple levels.
$cid = "config:{$instance}" . ($include_global ? ':withglobal' : ':withoutglobal');
if (!isset($defaults[$cid])) {
if ($cache = metatag_cache_get($cid)) {
$defaults[$cid] = $cache->data;
}
else {
$defaults[$cid] = array();
$instances = metatag_config_get_parent_instances($instance, $include_global);
$configs = metatag_config_load_multiple($instances);
foreach ($instances as $key) {
// Ignore disabled configurations.
if (!isset($configs[$key]) || !empty($configs[$key]->disabled)) {
continue;
}
// Add config to the defaults array.
if (!empty($configs[$key]->config)) {
$defaults[$cid] += $configs[$key]->config;
}
}
metatag_cache_set($cid, $defaults[$cid]);
}
}
return $defaults[$cid];
}
/**
* Load a metatag configuration record.
*/
function metatag_config_load($instance) {
$results = metatag_config_load_multiple(array($instance));
return !empty($results[$instance]) ? $results[$instance] : FALSE;
}
/**
* Load multiple metatag configuration records.
*/
function metatag_config_load_multiple(array $instances) {
// Load the data.
// @FIXME: Most CTools APIs have moved into core. For more information, see https://www.drupal.org/node/2164623
// ctools_include('export');
// @FIXME: The CTools Export API has into core in the form of exportable configuration and content entities. For more information, see https://www.drupal.org/developing/api/entity
// $configs = ctools_export_load_object('metatag_config', 'names', $instances);
// "Fix" any records that might be using old values. Ideally these will be
// permanently fixed by being re-saved or re-exported.
foreach (metatag_config_get_replacements() as $old_tag => $new_tag) {
foreach ($configs as $config_name => $config) {
if (isset($config->config[$old_tag])) {
$config->config[$new_tag] = $config->config[$old_tag];
unset($config->config[$old_tag]);
}
}
}
return $configs;
}
/**
* Identify the meta tags that have been deprecated and replaced by others.
*/
function metatag_config_get_replacements() {
$replacements = &drupal_static(__FUNCTION__);
if (!isset($replacements)) {
$replacements = array();
foreach (metatag_get_info('tags') as $tag_name => $tag_info) {
if (!empty($tag_info['replaces'])) {
if (!is_array($tag_info['replaces'])) {
$tag_info['replaces'] = array($tag_info['replaces']);
}
foreach ($tag_info['replaces'] as $replaces) {
$replacements[$replaces] = $tag_name;
}
}
}
}
return $replacements;
}
/**
* Save a metatag configuration record to the database.
*/
function metatag_config_save($config) {
$config->is_new = empty($config->cid);
// Allow modules to alter the configuration before it is saved using
// hook_metatag_config_presave().
\Drupal::moduleHandler()->invokeAll('metatag_config_presave', [$config]);
// Update the i18n string
if (function_exists('i18n_string_update')) {
$instance = $config->instance;
foreach ($config->config as $field => $item) {
$name = "metatag:" . $instance . ":" . $field;
i18n_string_update($name, $item['value']);
}
}
if ($config->is_new) {
drupal_write_record('metatag_config', $config);
// Allow modules to act upon the record insertion using
// hook_metatag_config_insert().
\Drupal::moduleHandler()->invokeAll('metatag_config_insert', [$config]);
}
else {
drupal_write_record('metatag_config', $config, array('cid'));
// Allow modules to act upon the record update using
// hook_metatag_config_insert().
\Drupal::moduleHandler()->invokeAll('metatag_config_update', [$config]);
}
unset($config->is_new);
// Clear any caches.
metatag_config_cache_clear();
}
/**
* Delete a metatag configuration record.
*/
function metatag_config_delete($instance) {
db_delete('metatag_config')
->condition('instance', $instance)
->execute();
// Clear any caches.
metatag_config_cache_clear();
}
/**
* Clear the metatag configuration cache.
*/
function metatag_config_cache_clear() {
cache_clear_all('*', 'cache_metatag', TRUE);
drupal_static_reset('metatag_config_load_with_defaults');
drupal_static_reset('metatag_entity_has_metatags');
drupal_static_reset('metatag_entity_supports_metatags');
// @FIXME: Most CTools APIs have moved into core. For more information, see https://www.drupal.org/node/2164623
// ctools_include('export');
// @FIXME: The CTools Export API has into core in the form of exportable configuration and content entities. For more information, see https://www.drupal.org/developing/api/entity
// ctools_export_load_object_reset('metatag_config');
}
/**
* Load an entity's tags.
*
* @param $entity_type
* The entity type to load.
* @param $entity_id
* The ID of the entity to load.
*
* @return
* An array of tag data keyed by revision ID and language.
*/
function metatag_metatags_load($entity_type, $entity_id) {
$metatags = metatag_metatags_load_multiple($entity_type, array($entity_id));
return !empty($metatags) ? reset($metatags) : array();
}
/**
* Load tags for multiple entities.
*
* @param $entity_type
* The entity type to load.
* @param $entity_ids
* The list of entity IDs.
*
* @return
* An array of tag data, keyed by entity ID, revision ID and language.
*/
function metatag_metatags_load_multiple($entity_type, array $entity_ids, array $revision_ids = array()) {
// Double check entity IDs are numeric thanks to Entity API module.
$entity_ids = array_filter($entity_ids, 'is_numeric');
if (empty($entity_ids)) {
return array();
}
// Also need to check if the metatag table exists since this condition could
// fire before the table has been installed yet.
if (!\Drupal::config('metatag.settings')->get('metatag_schema_installed')) {
if (db_table_exists('metatag')) {
\Drupal::config('metatag.settings')->set('metatag_schema_installed', TRUE);
}
else {
\Drupal::logger('metatag')->warning('The system tried to load metatag data before the schema was fully loaded.');
return array();
}
}
// Verify that the metatag.revision_id field has been added to the {metatag}
// table schema.
if (!\Drupal::config('metatag.settings')->get('metatag_has_revision_id')) {
if (db_field_exists('metatag', 'revision_id')) {
\Drupal::config('metatag.settings')->set('metatag_has_revision_id', TRUE);
}
else {
\Drupal::logger('metatag')->warning('The database updates need to be ran.');
return array();
}
}
// Get all translations of tag data for this entity.
$query = db_select('metatag', 'm')
->fields('m', array('entity_id', 'revision_id', 'language', 'data'))
->condition('m.entity_type', $entity_type)
->orderBy('entity_id')
->orderBy('revision_id');
// Filter by revision_ids if they are available. If not, filter by entity_ids.
if (!empty($revision_ids)) {
$query->condition('m.revision_id', $revision_ids, 'IN');
}
else {
$query->condition('m.entity_id', $entity_ids, 'IN');
}
$result = $query->execute();
// Marshal it into an array keyed by entity ID. Each value is an array of
// translations keyed by language code.
$metatags = array();
while ($record = $result->fetchObject()) {
$data = unserialize($record->data);
// "Fix" any records that might be using old values. Ideally these will be
// permanently fixed by being re-saved or re-exported.
foreach (metatag_config_get_replacements() as $old_tag => $new_tag) {
if (isset($data[$old_tag])) {
$data[$new_tag] = $data[$old_tag];
unset($data[$old_tag]);
}
}
$metatags[$record->entity_id][$record->revision_id][$record->language] = $data;
}
return $metatags;
}
/**
* Save an entity's tags.
*
* @param $entity_type
* The entity type to load
* @param $entity_id
* The entity's ID
* @param $revision_id
* The entity's VID.
* @param $metatags
* All of the tag information
* @param $language
* The language of the translation set
*/
function metatag_metatags_save($entity_type, $entity_id, $revision_id, $metatags, $langcode, $old_vid = NULL) {
// If no language assigned, or the language doesn't exist, use the
// has-no-language language.
$languages = language_list();
if (empty($langcode) || !isset($languages[$langcode])) {
$langcode = Language::LANGCODE_NOT_SPECIFIED;
}
// Check that $entity_id is numeric because of Entity API and string IDs.
if (!is_numeric($entity_id)) {
return;
}
// The revision_id must be a numeric value; some entities use NULL for the
// revision so change that to a zero.
if (is_null($revision_id)) {
$revision_id = 0;
}
// Handle scenarios where the metatags are completely empty.
if (empty($metatags)) {
$metatags = array();
// Add an empty array record for each language.
$languages = db_query("SELECT language, ''
FROM {metatag}
WHERE (entity_type = :type)
AND (entity_id = :id)
AND (revision_id = :revision)",
array(
':type' => $entity_type,
':id' => $entity_id,
':revision' => $revision_id,
))->fetchAllKeyed();
foreach ($languages as $oldlang => $empty) {
$metatags[$oldlang] = array();
}
}
// Update each of the per-language metatag configurations in turn.
foreach ($metatags as $langcode => $new_metatags) {
// Allow other modules to alter the meta tags prior to saving using
// hook_metatag_presave().
foreach (\Drupal::moduleHandler()->getImplementations('metatag_presave') as $module) {
$function = "{$module}_metatag_presave";
$function($new_metatags, $entity_type, $entity_id, $revision_id, $langcode);
}
// If the data array is empty, there is no data to actually save, so just
// delete the record from the database.
if (empty($new_metatags)) {
db_delete('metatag')
->condition('entity_type', $entity_type)
->condition('entity_id', $entity_id)
->condition('revision_id', $revision_id)
->condition('language', $langcode)
->execute();
}
// Otherwise save the data for this entity.
else {
db_merge('metatag')
->key(array(
'entity_type' => $entity_type,
'entity_id' => $entity_id,
'language' => $langcode,
'revision_id' => $revision_id,
))
->fields(array(
'data' => serialize($new_metatags),
))
->execute();
}
}
// Clear cached data.
metatag_metatags_cache_clear($entity_type, $entity_id);
}
/**
* Delete an entity's tags.
*
* @param $entity_type
* The entity type
* @param $entity_id
* The entity's ID
* @param $revision_id
* The entity's VID.
* @param $langcode
* The language ID of the entry to delete. If left blank, all language
* entries for this entity will be deleted.
*/
function metatag_metatags_delete($entity_type, $entity_id, $revision_id = NULL, $langcode = NULL) {
$revision_ids = array();
if (!empty($revision_id)) {
$revision_ids[] = $revision_id;
}
return metatag_metatags_delete_multiple($entity_type, array($entity_id), $revision_ids, $langcode);
}
/**
* Delete multiple entities' tags.
*
* @param $entity_type
* The entity type
* @param $entity_ids
* The list of IDs
* @param $revision_id
* An optional list of VIDs, if omitted all revisions will be deleted.
* @param $langcode
* The language ID of the entities to delete. If left blank, all language
* entries for the enities will be deleted.
*/
function metatag_metatags_delete_multiple($entity_type, array $entity_ids, array $revision_ids = array(), $langcode = NULL) {
// Double check entity IDs are numeric thanks to Entity API module.
$entity_ids = array_filter($entity_ids, 'is_numeric');
if ($metatags = metatag_metatags_load_multiple($entity_type, $entity_ids, $revision_ids)) {
$transaction = db_transaction();
try {
// Let other modules know about the records being deleted using
// hook_metatag_metatags_delete().
\Drupal::moduleHandler()->invokeAll('metatag_metatags_delete', [$entity_type, $entity_ids, $revision_ids, $langcode]);
// Set the entity to delete.
$query = db_delete('metatag')
->condition('entity_type', $entity_type)
->condition('entity_id', $entity_ids, 'IN');
// Optionally delete a specific revision.
if (!empty($revision_ids)) {
$query->condition('revision_id', $revision_ids, 'IN');
}
// Specify a language if there is one.
if (!empty($langcode)) {
$query->condition('language', $langcode);
}
// Perform the deletion(s).
$query->execute();
// Clear cached data.
metatag_metatags_cache_clear($entity_type, $entity_ids);
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('metatag', $e);
throw $e;
}
}
}
/**
* Clear the cached records for a given entity type or entity ID.
*
* @param string $entity_type
* The entity type to clear.
*/
function metatag_metatags_cache_clear($entity_type, $entity_ids = NULL) {
if (empty($entity_ids)) {
cache_clear_all("output:$entity_type", 'cache_metatag', TRUE);
}
else {
if (!is_array($entity_ids)) {
$entity_ids = array($entity_ids);
}
foreach ($entity_ids as $entity_id) {
cache_clear_all("output:$entity_type:$entity_id", 'cache_metatag', TRUE);
}
}
}
/**
* Implements hook_entity_load().
*/
function metatag_entity_load($entities, $entity_type) {
// Get the revision_ids.
$revision_ids = array();
/** @var Drupal\Core\Entity\EntityInterface $entity */
foreach ($entities as $key => $entity) {
if ($entity instanceof Drupal\Core\Entity\RevisionableInterface) {
$revision_id = $entity->getRevisionId();
if (!empty($revision_id)) {
$revision_ids[] = $revision_id;
}
}
}
// Wrap this in a try-catch block to work around occasions when the schema
// hasn't been updated yet.
try {
if (metatag_entity_supports_metatags($entity_type)) {
$metatags = metatag_metatags_load_multiple($entity_type, array_keys($entities), $revision_ids);
// Assign the metatag records for the correct revision ID.
foreach ($entities as $entity_id => $entity) {
$entity_id = $entity->id();
$revision_id = $entity->getRevisionId();
$entities[$entity_id]->metatags = isset($metatags[$entity_id][$revision_id]) ? $metatags[$entity_id][$revision_id] : array();
}
}
}
catch (Exception $e) {
\Drupal::logger('metatag')->warning('Error loading meta tag data, do the <a href="@update">database updates</a> need to be run? The error occurred when loading record(s) %ids for the %type entity type. The error message was: %error', array('@update' => base_path() . 'update.php', '%ids' => implode(', ', array_keys($entities)), '%type' => $entity_type, '%error' => $e->getMessage()));
// Don't display the same message twice for Drush.
if (PHP_SAPI === "cli") {
drupal_set_message(t('Run your updates, like drush updb.'));
}
// Only message people who can see it in watchdog and can likely fix it.
elseif (\Drupal::currentUser()->hasPermission('access site reports')) {
drupal_set_message(t('Error loading meta tag data, do the <a href="@update">database updates</a> need to be run?', array('@update' => base_path() . 'update.php')), 'error');
}
}
}
/**
* Implements hook_entity_insert().
*/
function metatag_entity_insert(ContentEntityInterface $entity, $entity_type) {
if (isset($entity->metatags)) {
$entity_id = $entity->id();
$revision_id = $entity->getRevisionId();
// Determine the entity's language.
$langcode = $entity->language();
// Unfortunately due to how core works, the normal entity_language()
// function returns 'und' instead of the node's language during node
// creation.
if ((empty($langcode) || $langcode == Language::LANGCODE_NOT_SPECIFIED) && !empty($entity->language)) {
$langcode = $entity->language;
}
// If no language was still found, use the 'no language' value.
if (empty($langcode)) {
$langcode = Language::LANGCODE_NOT_SPECIFIED;
}
// Work-around for initial entity creation where a language was selection
// but where it's different to the form's value.
if (!isset($entity->metatags[$langcode]) && isset($entity->metatags[Language::LANGCODE_NOT_SPECIFIED])) {
$entity->metatags[$langcode] = $entity->metatags[Language::LANGCODE_NOT_SPECIFIED];
unset($entity->metatags[Language::LANGCODE_NOT_SPECIFIED]);
}
// Support for Workbench Moderation v1.
if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
return;
}
metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $langcode);
}
}
/**
* Implements hook_entity_update().
*/
function metatag_entity_update(ContentEntityInterface $entity, $entity_type) {
if (!metatag_entity_supports_metatags($entity_type)) {
return;
}
$entity_id = $entity->id();
$revision_id = $entity->getRevisionId();
if (isset($entity->metatags)) {
// Determine the entity's new language. This will always be accurate as the
// language value will already have been updated by the time this function
// executes, and it will be loaded for the correct edit process.
$new_language = metatag_entity_get_language($entity_type, $entity);
// If applicable, determine the entity's original language. This cannot be
// obtained via the normal API as that data will already have been updated,
// instead check to see if the entity has an old-fasioned 'language' value.
if (isset($entity->original) && isset($entity->language) && isset($entity->original->language)) {
$old_language = $entity->original->language;
// If the language has changed then additional checking needs to be done.
// Need to compare against the entity's raw language value as they will
// be different when updating a translated entity, versus an untranslated
// entity or a source entity for translation, and give a false positive.
if ($new_language == $entity->language && $new_language != $old_language) {
// If this entity is not translated, or if it is translated but the
// translation was previously created, then some language cleanup needs
// to be done.
if (!isset($entity->translation) || (isset($entity->translation) && !empty($entity->translation['created']))) {
// Delete the old language record. This will not affect old revisions.
db_delete('metatag')
->condition('entity_type', $entity_type)
->condition('entity_id', $entity_id)
->condition('revision_id', $revision_id)
->condition('language', $old_language)
->execute();
// Swap out the metatag values for the two languages.
if (isset($entity->metatags[$old_language])) {
$entity->metatags[$new_language] = $entity->metatags[$old_language];
unset($entity->metatags[$old_language]);
}
}
}
}
// Support for Workbench Moderation v1.
if ($entity_type == 'node' && _metatag_isdefaultrevision($entity)) {
return;
}
// Save the record.
$old_vid = isset($entity->old_vid) ? $entity->old_vid : NULL;
metatag_metatags_save($entity_type, $entity_id, $revision_id, $entity->metatags, $new_language, $old_vid);
}
else {
// Still ensure the meta tag output is cached.
metatag_metatags_cache_clear($entity_type, $entity_id);
}
}
/**
* Implements hook_entity_delete().
*/
function metatag_entity_delete(ContentEntityInterface $entity, $entity_type) {
metatag_metatags_delete($entity_type, $entity->id());
}
/**
* Implements hook_field_attach_delete_revision().
*/
function metatag_field_attach_delete_revision($entity_type, ContentEntityInterface $entity) {
metatag_metatags_delete($entity_type, $entity->id(), $entity->getRevisionId());
}
/**
* Implements hook_entity_view().
*
* Provides additional argument to allow the display to be forced, to work
* around problems elsewhere in the APIs.
*/
function metatag_entity_view(ContentEntityInterface $entity, $entity_type, $view_mode, $langcode, $force = FALSE) {
// Only run this function once per page load.
static $i_will_say_this_only_once = FALSE;
// Only proceed if this entity object is the page being viewed.
if (_metatag_entity_is_page($entity_type, $entity)) {
// Some API calls need to force the data loading.
if (!$force) {
// Only run this function once per page load.
if ($i_will_say_this_only_once) {
return;
}
$i_will_say_this_only_once = TRUE;
}
// CTools uses 'page_manager' view mode to indicate the full entity display
// page rather than 'full', so streamline the internal processes.
if ($view_mode == 'page_manager') {
$view_mode = 'full';
}
// Generate metatags output.
if ($output = metatag_generate_entity_metatags($entity, $entity_type, $langcode, $view_mode)) {
$bundle = $entity->bundle();
$instance = "{$entity_type}:{$bundle}";
// We need to register the term's metatags, so we can later fetch them.
// @see metatag_page_build().
metatag_page_set_metatags($instance, $output);
}
}
}
/**
* Generate the metatags for a given entity.
*
* @param object $entity
* The entity object to generate the metatags for.
* @param string $entity_type
* The entity type of the entity.
* @param string $langcode
* The language code used for rendering the entity.
* @param string $view_mode
* The view mode the entity is rendered in.
* @param bool $cached
* TRUE if metatags can be loaded from and saved to the cache. FALSE if the
* cache should be bypassed.
*
* @return array
* A renderable array of metatags for the given entity.
*/
function metatag_generate_entity_metatags(ContentEntityInterface $entity, $entity_type, $langcode = NULL, $view_mode = 'full', $cached = TRUE) {
// If this entity object isn't allowed meta tags, don't continue.
if (!metatag_entity_has_metatags($entity_type, $entity)) {
return array();
}
// Obtain some details of the entity that are needed elsewhere.
$entity_id = $entity->id();
$revision_id = $entity->getRevisionId();
// Check if a specific metatag config exists, otherwise just use the global
// one, stripping out the bundle.
$instance = "{$entity_type}:{$bundle}";
if (!metatag_config_load_with_defaults($instance, FALSE)) {
$instance = "{$entity_type}";
}
// Determine the language this entity actually uses.
$entity_language = metatag_entity_get_language($entity_type, $entity);
// If no language was requested, try the language defined for this page
// request.
if (empty($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}
// This entity doesn't have any languages defined, i.e. it uses 'und'. This
// can't conflict with loading the wrong language as entities either have no
// language or they have specific one(s), they can't have both.
if ($entity_language == Language::LANGCODE_NOT_SPECIFIED) {
$langcode = Language::LANGCODE_NOT_SPECIFIED;
}
// If there are no meta tags for the currently identified language, and there
// *are* meta tags defined for the entity's default language, use the entity's
// default language's values, unless the "Don't load entity's default
// language values if no languages match" option is enabled on the advanced
// settings page.
elseif (empty($entity->metatags[$langcode]) && !empty($entity->metatags[$entity_language]) && !\Drupal::config('metatag.settings')->get('metatag_entity_no_lang_default')) {
$langcode = $entity_language;
}
// Other scenarios.
else {
// There's no need to do anything else - either there are meta tag values
// created for the requested language or there aren't.
}
$cid = FALSE;
if ($cached) {
// All applicable pieces for this current page.
$cid_parts = array(
'entity_type' => $entity_type,
'bundle' => $bundle,
'entity_id' => $entity_id,
'revision_id' => $revision_id,
// Cache separately based on the language of the passed-in entity and the
// overall active language of the page.
'langcode' => $langcode,
'language_content' => $GLOBALS['language_content']->language,
'view_mode' => $view_mode,
);
$cid = metatag_cache_default_cid_parts($cid_parts);
}
if ($cid && $cache = metatag_cache_get($cid)) {
$output = $cache->data;
}
else {
// Separate the meta tags.
$metatags = isset($entity->metatags) ? $entity->metatags : array();
// Build options for meta tag rendering.
$options = array(
'entity' => $entity,
'entity_type' => $entity_type,
'view_mode' => $view_mode,
);
// Ensure we actually pass a language object rather than language code.
$languages = language_list();
if (isset($languages[$langcode])) {
$options['language'] = $languages[$langcode];
}
// Reload the entity object from cache as it may have been altered.
$token_type = token_get_entity_mapping('entity', $entity_type);
$entities = \Drupal::entityManager()->getStorage($entity_type)->loadMultiple(array($entity_id));
$options['token data'][$token_type] = $entities[$entity_id];
$options['entity'] = $entities[$entity_id];
// Render the metatags and save to the cache.
$output = metatag_metatags_view($instance, $metatags, $options);
if ($cid) {
metatag_cache_set($cid, $output);
}
}
return $output;
}
/**
* Generate the metatags for a given entity.
*
* @param object $entity_id
* The entity id of the entity to generate the metatags for.
* @param string $entity_type
* The entity type of the entity to generate the metatags for.
* @param string $langcode
* The language code used for rendering the entity.
*
* @return array
* A renderable array of metatags for the given entity.
*/
function metatags_get_entity_metatags($entity_id, $entity_type, $langcode = NULL) {
$entities = \Drupal::entityManager()->getStorage($entity_type)->loadMultiple(array($entity_id));
$entity = reset($entities);
return !empty($entity) ? metatag_generate_entity_metatags($entity, $entity_type, $langcode) : array();