-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.module
2614 lines (2412 loc) · 87.9 KB
/
node.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
* The core module that allows content to be submitted to the site.
*
* Modules and scripts may programmatically submit nodes using the usual form
* API pattern.
*/
use Drupal\Core\Language\Language;
use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Database\Query\SelectExtender;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\node\NodeTypeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Template\Attribute;
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
use Drupal\file\Plugin\Core\Entity\File;
use Drupal\user\UserInterface;
/**
* Denotes that the node is not published.
*/
const NODE_NOT_PUBLISHED = 0;
/**
* Denotes that the node is published.
*/
const NODE_PUBLISHED = 1;
/**
* Denotes that the node is not promoted to the front page.
*/
const NODE_NOT_PROMOTED = 0;
/**
* Denotes that the node is promoted to the front page.
*/
const NODE_PROMOTED = 1;
/**
* Denotes that the node is not sticky at the top of the page.
*/
const NODE_NOT_STICKY = 0;
/**
* Denotes that the node is sticky at the top of the page.
*/
const NODE_STICKY = 1;
/**
* Denotes that access is allowed for a node.
*
* Modules should return this value from hook_node_access() to allow access to a
* node.
*/
const NODE_ACCESS_ALLOW = TRUE;
/**
* Denotes that access is denied for a node.
*
* Modules should return this value from hook_node_access() to deny access to a
* node.
*/
const NODE_ACCESS_DENY = FALSE;
/**
* Denotes that access is unaffected for a node.
*
* Modules should return this value from hook_node_access() to indicate no
* effect on node access.
*/
const NODE_ACCESS_IGNORE = NULL;
/**
* Implements hook_help().
*/
function node_help($path, $arg) {
// Remind site administrators about the {node_access} table being flagged
// for rebuild. We don't need to issue the message on the confirm form, or
// while the rebuild is being processed.
if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
&& user_access('access administration pages') && node_access_needs_rebuild()) {
if ($path == 'admin/reports/status') {
$message = t('The content access permissions need to be rebuilt.');
}
else {
$message = t('The content access permissions need to be rebuilt. <a href="@node_access_rebuild">Rebuild permissions</a>.', array('@node_access_rebuild' => url('admin/reports/status/rebuild')));
}
drupal_set_message($message, 'error');
}
switch ($path) {
case 'admin/help#node':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Node module manages the creation, editing, deletion, settings, and display of the main site content. Content items managed by the Node module are typically displayed as pages on your site, and include a title, some meta-data (author, creation time, content type, etc.), and optional fields containing text or other data (fields are managed by the <a href="@field">Field module</a>). For more information, see the online handbook entry for <a href="@node">Node module</a>.', array('@node' => 'http://drupal.org/documentation/modules/node', '@field' => url('admin/help/field'))) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Creating content') . '</dt>';
$output .= '<dd>' . t('When new content is created, the Node module records basic information about the content, including the author, date of creation, and the <a href="@content-type">Content type</a>. It also manages the <em>publishing options</em>, which define whether or not the content is published, promoted to the front page of the site, and/or sticky at the top of content lists. Default settings can be configured for each <a href="@content-type">type of content</a> on your site.', array('@content-type' => url('admin/structure/types'))) . '</dd>';
$output .= '<dt>' . t('Creating custom content types') . '</dt>';
$output .= '<dd>' . t('The Node module gives users with the <em>Administer content types</em> permission the ability to <a href="@content-new">create new content types</a> in addition to the default ones already configured. Creating custom content types allows you the flexibility to add <a href="@field">fields</a> and configure default settings that suit the differing needs of various site content.', array('@content-new' => url('admin/structure/types/add'), '@field' => url('admin/help/field'))) . '</dd>';
$output .= '<dt>' . t('Administering content') . '</dt>';
$output .= '<dd>' . t('The <a href="@content">Content administration page</a> allows you to review and bulk manage your site content.', array('@content' => url('admin/content'))) . '</dd>';
$output .= '<dt>' . t('Creating revisions') . '</dt>';
$output .= '<dd>' . t('The Node module also enables you to create multiple versions of any content, and revert to older versions using the <em>Revision information</em> settings.') . '</dd>';
$output .= '<dt>' . t('User permissions') . '</dt>';
$output .= '<dd>' . t('The Node module makes a number of permissions available for each content type, which can be set by role on the <a href="@permissions">permissions page</a>.', array('@permissions' => url('admin/people/permissions', array('fragment' => 'module-node')))) . '</dd>';
$output .= '</dl>';
return $output;
case 'admin/structure/types/add':
return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
case 'admin/structure/types/manage/%/form-display':
$type = entity_load('node_type', $arg[4]);
return '<p>' . t('Content items can be edited using different form modes. Here, you can define which fields are shown and hidden when %type content is edited in each form mode, and define how the field form widgets are displayed in each form mode.', array('%type' => $type->label())) . '</p>' ;
case 'admin/structure/types/manage/%/display':
$type = entity_load('node_type', $arg[4]);
return '<p>' . t('Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. <em>Teaser</em> is a short format that is typically used in lists of multiple content items. <em>Full content</em> is typically used when the content is displayed on its own page.') . '</p>' .
'<p>' . t('Here, you can define which fields are shown and hidden when %type content is displayed in each view mode, and define how the fields are displayed in each view mode.', array('%type' => $type->label())) . '</p>';
case 'node/%/revisions':
return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
case 'node/%/edit':
$node = node_load($arg[1]);
$type = node_type_load($node->bundle());
return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
}
if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
$type = node_type_load($arg[2]);
return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
}
}
/**
* Implements hook_theme().
*/
function node_theme() {
return array(
'node' => array(
'render element' => 'elements',
'template' => 'node',
),
'node_search_admin' => array(
'render element' => 'form',
),
'node_add_list' => array(
'variables' => array('content' => NULL),
'file' => 'node.pages.inc',
),
'node_preview' => array(
'variables' => array('node' => NULL),
'file' => 'node.pages.inc',
),
'node_recent_block' => array(
'variables' => array('nodes' => NULL),
),
'node_recent_content' => array(
'variables' => array('node' => NULL),
),
'node_edit_form' => array(
'render element' => 'form',
'template' => 'node-edit-form',
),
);
}
/**
* Implements hook_entity_bundle_info().
*/
function node_entity_bundle_info() {
$bundles = array();
// Bundles must provide a human readable name so we can create help and error
// messages.
foreach (node_type_get_names() as $id => $label) {
$bundles['node'][$id]['label'] = $label;
}
return $bundles;
}
/**
* Implements hook_entity_display_alter().
*/
function node_entity_display_alter(EntityDisplay $display, $context) {
// Hide field labels in search index.
if ($context['entity_type'] == 'node' && $context['view_mode'] == 'search_index') {
foreach ($display->getComponents() as $name => $options) {
if (isset($options['label'])) {
$options['label'] = 'hidden';
$display->setComponent($name, $options);
}
}
}
}
/**
* Entity URI callback.
*
* @param \Drupal\Core\Entity\EntityInterface $node
* A node entity.
*
* @return array
* An array with 'path' as the key and the path to the node as its value.
*/
function node_uri(EntityInterface $node) {
return array(
'path' => 'node/' . $node->id(),
);
}
/**
* Implements hook_admin_paths().
*/
function node_admin_paths() {
if (variable_get('node_admin_theme')) {
$paths = array(
'node/*/edit' => TRUE,
'node/*/delete' => TRUE,
'node/*/revisions' => TRUE,
'node/*/revisions/*/revert' => TRUE,
'node/*/revisions/*/delete' => TRUE,
'node/*/translations' => TRUE,
'node/*/translations/*' => TRUE,
'node/add' => TRUE,
'node/add/*' => TRUE,
);
return $paths;
}
}
/**
* Gathers a listing of links to nodes.
*
* @param $result
* A database result object from a query to fetch node entities. If your
* query joins the {node_comment_statistics} table so that the comment_count
* field is available, a title attribute will be added to show the number of
* comments.
* @param $title
* (optional) A heading for the resulting list.
*
* @return
* A renderable array containing a list of linked node titles fetched from
* $result, or FALSE if there are no rows in $result.
*/
function node_title_list($result, $title = NULL) {
$items = array();
$num_rows = FALSE;
foreach ($result as $node) {
// Do not use $node->label() here, because $node comes from the database.
$items[] = l($node->title, 'node/' . $node->nid, !empty($node->comment_count) ? array('attributes' => array('title' => format_plural($node->comment_count, '1 comment', '@count comments'))) : array());
$num_rows = TRUE;
}
return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
}
/**
* Determines the type of marker to be displayed for a given node.
*
* @param $nid
* Node ID whose history supplies the "last viewed" timestamp.
* @param $timestamp
* Time which is compared against node's "last viewed" timestamp.
*
* @return
* One of the MARK constants.
*/
function node_mark($nid, $timestamp) {
global $user;
$cache = &drupal_static(__FUNCTION__, array());
if ($user->isAnonymous() || !module_exists('history')) {
return MARK_READ;
}
if (!isset($cache[$nid])) {
$cache[$nid] = history_read($nid);
}
if ($cache[$nid] == 0 && $timestamp > HISTORY_READ_LIMIT) {
return MARK_NEW;
}
elseif ($timestamp > $cache[$nid] && $timestamp > HISTORY_READ_LIMIT) {
return MARK_UPDATED;
}
return MARK_READ;
}
/**
* Returns a list of all the available node types.
*
* This list can include types that are queued for addition or deletion.
*
* @return array
* An array of node type entities, keyed by ID.
*
* @see node_type_load()
*/
function node_type_get_types() {
return entity_load_multiple('node_type');
}
/**
* Returns a list of available node type names.
*
* This list can include types that are queued for addition or deletion.
*
* @return array
* An array of node type labels, keyed by the node type name.
*/
function node_type_get_names() {
$cid = 'node_type:names:' . language(Language::TYPE_INTERFACE)->id;
if ($cache = cache()->get($cid)) {
return $cache->data;
}
// Not using node_type_get_types() or entity_load_multiple() here, to allow
// this function being used in hook_entity_info() implementations.
// @todo Consider to convert this into a generic config entity helper.
$config_names = config_get_storage_names_with_prefix('node.type.');
$names = array();
foreach ($config_names as $config_name) {
$config = config($config_name);
$names[$config->get('type')] = $config->get('name');
}
cache()->set($cid, $names, CacheBackendInterface::CACHE_PERMANENT, array(
'node_type' => array_keys($names),
'node_types' => TRUE,
));
return $names;
}
/**
* Returns the node type label for the passed node.
*
* @param \Drupal\Core\Entity\EntityInterface $node
* A node entity to return the node type's label for.
*
* @return string|false
* The node type label or FALSE if the node type is not found.
*
* @todo Add this as generic helper method for config entities representing
* entity bundles.
*/
function node_get_type_label(EntityInterface $node) {
$type = entity_load('node_type', $node->bundle());
return $type ? $type->label() : FALSE;
}
/**
* Description callback: Returns the node type description.
*
* @param \Drupal\node\NodeTypeInterface $node_type
* The node type object.
*
* @return string
* The node type description.
*/
function node_type_get_description(NodeTypeInterface $node_type) {
return $node_type->description;
}
/**
* Menu argument loader: Loads a node type by string.
*
* @param $name
* The machine name of a node type to load.
*
* @return \Drupal\node\NodeTypeInterface
* A node type object or NULL if $name does not exist.
*/
function node_type_load($name) {
return entity_load('node_type', $name);
}
/**
* Adds the default body field to a node type.
*
* @param \Drupal\node\NodeTypeInterface $type
* A node type object.
* @param $label
* (optional) The label for the body instance.
*
* @return
* Body field instance.
*/
function node_add_body_field(NodeTypeInterface $type, $label = 'Body') {
// Add or remove the body field, as needed.
$field = field_info_field('body');
$instance = field_info_instance('node', 'body', $type->id());
if (empty($field)) {
$field = entity_create('field_entity', array(
'field_name' => 'body',
'type' => 'text_with_summary',
'entity_types' => array('node'),
));
$field->save();
}
if (empty($instance)) {
$instance = entity_create('field_instance', array(
'field_name' => 'body',
'entity_type' => 'node',
'bundle' => $type->id(),
'label' => $label,
'settings' => array('display_summary' => TRUE),
));
$instance->save();
// Assign widget settings for the 'default' form mode.
entity_get_form_display('node', $type->type, 'default')
->setComponent($field->id(), array(
'type' => 'text_textarea_with_summary',
))
->save();
// Assign display settings for the 'default' and 'teaser' view modes.
entity_get_display('node', $type->type, 'default')
->setComponent($field->id(), array(
'label' => 'hidden',
'type' => 'text_default',
))
->save();
entity_get_display('node', $type->type, 'teaser')
->setComponent($field->id(), array(
'label' => 'hidden',
'type' => 'text_summary_or_trimmed',
))
->save();
}
return $instance;
}
/**
* Implements hook_field_extra_fields().
*/
function node_field_extra_fields() {
$extra = array();
$module_language_enabled = module_exists('language');
$description = t('Node module element');
foreach (node_type_get_types() as $bundle) {
if ($bundle->has_title) {
$extra['node'][$bundle->type]['form']['title'] = array(
'label' => $bundle->title_label,
'description' => $description,
'weight' => -5,
);
}
// Add also the 'language' select if Language module is enabled and the
// bundle has multilingual support.
// Visibility of the ordering of the language selector is the same as on the
// node/add form.
if ($module_language_enabled) {
$configuration = language_get_default_configuration('node', $bundle->type);
if ($configuration['language_show']) {
$extra['node'][$bundle->type]['form']['language'] = array(
'label' => t('Language'),
'description' => $description,
'weight' => 0,
);
}
}
$extra['node'][$bundle->type]['display']['language'] = array(
'label' => t('Language'),
'description' => $description,
'weight' => 0,
'visible' => FALSE,
);
}
return $extra;
}
/**
* Updates all nodes of one type to be of another type.
*
* @param string $old_id
* The current node type of the nodes.
* @param string $new_id
* The new node type of the nodes.
*
* @return
* The number of nodes whose node type field was modified.
*/
function node_type_update_nodes($old_id, $new_id) {
return db_update('node')
->fields(array('type' => $new_id))
->condition('type', $old_id)
->execute();
}
/**
* Loads node entities from the database.
*
* This function should be used whenever you need to load more than one node
* from the database. Nodes are loaded into memory and will not require database
* access if loaded again during the same page request.
*
* @param array $nids
* (optional) An array of entity IDs. If omitted, all entities are loaded.
* @param bool $reset
* (optional) Whether to reset the internal node_load() cache. Defaults to
* FALSE.
*
* @return array
* An array of node entities indexed by nid.
*
* @see entity_load_multiple()
* @see Drupal\Core\Entity\Query\EntityQueryInterface
*/
function node_load_multiple(array $nids = NULL, $reset = FALSE) {
$entities = entity_load_multiple('node', $nids, $reset);
// Return BC-entities.
foreach ($entities as $id => $entity) {
$entities[$id] = $entity->getBCEntity();
}
return $entities;
}
/**
* Loads a node entity from the database.
*
* @param int $nid
* The node ID.
* @param bool $reset
* (optional) Whether to reset the node_load_multiple() cache. Defaults to
* FALSE.
*
* @return \Drupal\node\Node|null
* A fully-populated node entity or NULL if the node is not found.
*/
function node_load($nid = NULL, $reset = FALSE) {
$entity = entity_load('node', $nid, $reset);
return $entity ? $entity->getBCEntity() : NULL;
}
/**
* Loads a node revision from the database.
*
* @param int $nid
* The node revision id.
*
* @return \Drupal\node\Node|null
* A fully-populated node entity or NULL if the node is not found.
*/
function node_revision_load($vid = NULL) {
return entity_revision_load('node', $vid);
}
/**
* Prepares a node for saving by populating the author and creation date.
*
* @param \Drupal\Core\Entity\EntityInterface $node
* A node object.
*
* @return Drupal\node\Node
* An updated node object.
*/
function node_submit(EntityInterface $node) {
global $user;
// A user might assign the node author by entering a user name in the node
// form, which we then need to translate to a user ID.
if (isset($node->name)) {
if ($account = user_load_by_name($node->name)) {
$node->setAuthorId($account->id());
}
else {
$node->setAuthorId(0);
}
}
// If a new revision is created, save the current user as revision author.
if ($node->isNewRevision()) {
$node->setRevisionAuthorId($user->id());
$node->setRevisionCreationTime(REQUEST_TIME);
}
$node->setCreatedTime(!empty($node->date) && $node->date instanceOf DrupalDateTime ? $node->date->getTimestamp() : REQUEST_TIME);
$node->validated = TRUE;
return $node;
}
/**
* Deletes a node revision.
*
* @param $revision_id
* The revision ID to delete.
*
* @return
* TRUE if the revision deletion was successful; otherwise, FALSE.
*/
function node_revision_delete($revision_id) {
entity_revision_delete('node', $revision_id);
}
/**
* Page callback: Generates an array which displays a node detail page.
*
* @param \Drupal\Core\Entity\EntityInterface $node
* A node entity.
* @param $message
* (optional) A flag which sets a page title relevant to the revision being
* viewed. Default is FALSE.
*
* @return
* A $page element suitable for use by drupal_render().
*
* @see node_menu()
*/
function node_show(EntityInterface $node, $message = FALSE) {
if ($message) {
drupal_set_title(t('Revision of %title from %date', array('%title' => $node->label(), '%date' => format_date($node->getRevisionCreationTime()))), PASS_THROUGH);
}
// For markup consistency with other pages, use node_view_multiple() rather than node_view().
$nodes = array('nodes' => node_view_multiple(array($node->id() => $node), 'full'));
// Update the history table, stating that this user viewed this node.
if (module_exists('history')) {
history_write($node->id());
}
return $nodes;
}
/**
* Checks whether the current page is the full page view of the passed-in node.
*
* @param \Drupal\Core\Entity\EntityInterface $node
* A node entity.
*
* @return
* The ID of the node if this is a full page view, otherwise FALSE.
*/
function node_is_page(EntityInterface $node) {
$page_node = menu_get_object();
return (!empty($page_node) ? $page_node->id() == $node->id() : FALSE);
}
/**
* Implements hook_preprocess_HOOK() for block.html.twig.
*/
function node_preprocess_block(&$variables) {
if ($variables['configuration']['module'] == 'node') {
switch ($variables['elements']['#plugin_id']) {
case 'node_syndicate_block':
$variables['attributes']['role'] = 'complementary';
break;
case 'node_recent_block':
$variables['attributes']['role'] = 'navigation';
break;
}
}
}
/**
* Prepares variables for node templates.
*
* Default template: node.html.twig.
*
* Most themes utilize their own copy of node.html.twig. The default is located
* inside "/core/modules/node/templates/node.html.twig". Look in there for the full
* list of variables.
*
* @param array $variables
* An associative array containing:
* - elements: An array of elements to display in view mode.
* - node: The node object.
* - view_mode: View mode; e.g., 'full', 'teaser'...
*/
function template_preprocess_node(&$variables) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
// Provide a distinct $teaser boolean.
$variables['teaser'] = $variables['view_mode'] == 'teaser';
$variables['node'] = $variables['elements']['#node'];
$node = $variables['node'];
$variables['date'] = format_date($node->getCreatedTime());
// @todo Change 'name' to 'author' and also convert to a render array pending
// http://drupal.org/node/1941286.
$username = array(
'#theme' => 'username',
'#account' => user_load($node->uid),
'#link_options' => array('attributes' => array('rel' => 'author')),
);
$variables['name'] = drupal_render($username);
$uri = $node->uri();
$variables['node_url'] = url($uri['path'], $uri['options']);
$variables['label'] = check_plain($node->label());
$variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);
// Helpful $content variable for templates.
$variables += array('content' => array());
foreach (element_children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
// Make the field variables available with the appropriate language.
field_attach_preprocess($node, $variables['content'], $variables);
// Display post information only on certain node types.
// Avoid loading the entire node type config entity here.
$submitted = Drupal::config('node.type.' . $node->bundle())->get('settings.node.submitted') ?: TRUE;
if ($submitted) {
$variables['display_submitted'] = TRUE;
$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
if (theme_get_setting('features.node_user_picture')) {
// To change user picture settings (e.g. image style), edit the 'compact'
// view mode on the User entity. Note that the 'compact' view mode might
// not be configured, so remember to always check the theme setting first.
$variables['user_picture'] = user_view($node->getAuthor(), 'compact');
}
else {
$variables['user_picture'] = array();
}
}
else {
$variables['display_submitted'] = FALSE;
$variables['submitted'] = '';
$variables['user_picture'] = '';
}
// Add article ARIA role.
$variables['attributes']['role'] = 'article';
// Gather node classes.
$variables['attributes']['class'][] = 'node';
$variables['attributes']['class'][] = drupal_html_class('node-' . $node->bundle());
if ($node->isPromoted()) {
$variables['attributes']['class'][] = 'promoted';
}
if ($node->isSticky()) {
$variables['attributes']['class'][] = 'sticky';
}
if (!$node->isPublished()) {
$variables['attributes']['class'][] = 'unpublished';
}
if ($variables['view_mode']) {
$variables['attributes']['class'][] = drupal_html_class('view-mode-' . $variables['view_mode']);
}
if (isset($variables['preview'])) {
$variables['attributes']['class'][] = 'preview';
}
// Clean up name so there are no underscores.
$variables['theme_hook_suggestions'][] = 'node__' . $node->bundle();
$variables['theme_hook_suggestions'][] = 'node__' . $node->id();
$variables['content_attributes']['class'][] = 'content';
}
/**
* Implements hook_permission().
*/
function node_permission() {
$perms = array(
'bypass node access' => array(
'title' => t('Bypass content access control'),
'description' => t('View, edit and delete all content regardless of permission restrictions.'),
'restrict access' => TRUE,
),
'administer content types' => array(
'title' => t('Administer content types'),
'restrict access' => TRUE,
),
'administer nodes' => array(
'title' => t('Administer content'),
'restrict access' => TRUE,
),
'access content overview' => array(
'title' => t('Access the Content overview page'),
'description' => user_access('access content overview')
? t('Get an overview of <a href="@url">all content</a>.', array('@url' => url('admin/content')))
: t('Get an overview of all content.'),
),
'access content' => array(
'title' => t('View published content'),
),
'view own unpublished content' => array(
'title' => t('View own unpublished content'),
),
'view all revisions' => array(
'title' => t('View all revisions'),
),
'revert all revisions' => array(
'title' => t('Revert all revisions'),
'description' => t('Role requires permission <em>view revisions</em> and <em>edit rights</em> for nodes in question, or <em>administer nodes</em>.'),
),
'delete all revisions' => array(
'title' => t('Delete all revisions'),
'description' => t('Role requires permission to <em>view revisions</em> and <em>delete rights</em> for nodes in question, or <em>administer nodes</em>.'),
),
);
// Generate standard node permissions for all applicable node types.
foreach (node_permissions_get_configured_types() as $name => $type) {
$perms += node_list_permissions($type);
}
return $perms;
}
/**
* Gathers the rankings from the the hook_ranking() implementations.
*
* @param $query
* A query object that has been extended with the Search DB Extender.
*/
function _node_rankings(SelectExtender $query) {
if ($ranking = Drupal::moduleHandler()->invokeAll('ranking')) {
$tables = &$query->getTables();
foreach ($ranking as $rank => $values) {
if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
// If the table defined in the ranking isn't already joined, then add it.
if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
$query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
}
$arguments = isset($values['arguments']) ? $values['arguments'] : array();
$query->addScore($values['score'], $arguments, $node_rank);
}
}
}
}
/**
* Implements hook_search_info().
*/
function node_search_info() {
return array(
'title' => 'Content',
'path' => 'node',
);
}
/**
* Implements hook_search_access().
*/
function node_search_access() {
return user_access('access content');
}
/**
* Implements hook_search_reset().
*/
function node_search_reset() {
db_update('search_dataset')
->fields(array('reindex' => REQUEST_TIME))
->condition('type', 'node')
->execute();
}
/**
* Implements hook_search_status().
*/
function node_search_status() {
$total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
$remaining = db_query("SELECT COUNT(*) FROM {node} n LEFT JOIN {search_dataset} d ON d.type = 'node' AND d.sid = n.nid WHERE d.sid IS NULL OR d.reindex <> 0")->fetchField();
return array('remaining' => $remaining, 'total' => $total);
}
/**
* Implements hook_search_admin().
*/
function node_search_admin() {
// Output form for defining rank factor weights.
$form['content_ranking'] = array(
'#type' => 'details',
'#title' => t('Content ranking'),
);
$form['content_ranking']['#theme'] = 'node_search_admin';
$form['content_ranking']['info'] = array(
'#value' => '<em>' . t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em>'
);
// Note: reversed to reflect that higher number = higher ranking.
$options = drupal_map_assoc(range(0, 10));
foreach (Drupal::moduleHandler()->invokeAll('ranking') as $var => $values) {
$form['content_ranking']['factors']['node_rank_' . $var] = array(
'#title' => $values['title'],
'#type' => 'select',
'#options' => $options,
'#default_value' => variable_get('node_rank_' . $var, 0),
);
}
return $form;
}
/**
* Implements hook_search_execute().
*/
function node_search_execute($keys = NULL, $conditions = NULL) {
// Build matching conditions
$query = db_select('search_index', 'i', array('target' => 'slave'))
->extend('Drupal\search\SearchQuery')
->extend('Drupal\Core\Database\Query\PagerSelectExtender');
$query->join('node_field_data', 'n', 'n.nid = i.sid');
$query
->condition('n.status', 1)
->addTag('node_access')
->searchExpression($keys, 'node');
// Insert special keywords.
$query->setOption('type', 'n.type');
$query->setOption('langcode', 'n.langcode');
if ($query->setOption('term', 'ti.tid')) {
$query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
}
// Only continue if the first pass query matches.
if (!$query->executeFirstPass()) {
return array();
}
// Add the ranking expressions.
_node_rankings($query);
// Load results.
$find = $query
// Add the language code of the indexed item to the result of the query,
// since the node will be rendered using the respective language.
->fields('i', array('langcode'))
->limit(10)
->execute();
$results = array();
foreach ($find as $item) {
// Render the node.
$node = node_load($item->sid);
$build = node_view($node, 'search_result', $item->langcode);
unset($build['#theme']);
$node->rendered = drupal_render($build);
// Fetch comments for snippet.
$node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node, $item->langcode);
$extra = Drupal::moduleHandler()->invokeAll('node_search_result', array($node, $item->langcode));
$language = language_load($item->langcode);
$uri = $node->uri();
$username = array(
'#theme' => 'username',
'#account' => user_load($node->uid),
);
$results[] = array(
'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE, 'language' => $language))),
'type' => check_plain(node_get_type_label($node)),
'title' => $node->label($item->langcode),
'user' => drupal_render($username),
'date' => $node->getChangedTime(),
'node' => $node,
'extra' => $extra,
'score' => $item->calculated_score,
'snippet' => search_excerpt($keys, $node->rendered, $item->langcode),
'langcode' => $node->language()->id,
);
}
return $results;
}
/**
* Implements hook_ranking().
*/
function node_ranking() {
// Create the ranking array and add the basic ranking options.
$ranking = array(
'relevance' => array(
'title' => t('Keyword relevance'),
// Average relevance values hover around 0.15
'score' => 'i.relevance',
),
'sticky' => array(
'title' => t('Content is sticky at top of lists'),
// The sticky flag is either 0 or 1, which is automatically normalized.
'score' => 'n.sticky',
),
'promote' => array(
'title' => t('Content is promoted to the front page'),
// The promote flag is either 0 or 1, which is automatically normalized.
'score' => 'n.promote',
),
);
// Add relevance based on creation or changed date.
if ($node_cron_last = Drupal::state()->get('node.cron_last')) {
$ranking['recent'] = array(
'title' => t('Recently posted'),
// Exponential decay with half-life of 6 months, starting at last indexed node
'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',