Projet

Général

Profil

Paste
Télécharger (136 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / node / node.module @ 6ff32cea

1
<?php
2

    
3
/**
4
 * @file
5
 * The core that allows content to be submitted to the site. Modules and
6
 * scripts may programmatically submit nodes using the usual form API pattern.
7
 */
8

    
9
/**
10
 * Node is not published.
11
 */
12
define('NODE_NOT_PUBLISHED', 0);
13

    
14
/**
15
 * Node is published.
16
 */
17
define('NODE_PUBLISHED', 1);
18

    
19
/**
20
 * Node is not promoted to front page.
21
 */
22
define('NODE_NOT_PROMOTED', 0);
23

    
24
/**
25
 * Node is promoted to front page.
26
 */
27
define('NODE_PROMOTED', 1);
28

    
29
/**
30
 * Node is not sticky at top of the page.
31
 */
32
define('NODE_NOT_STICKY', 0);
33

    
34
/**
35
 * Node is sticky at top of the page.
36
 */
37
define('NODE_STICKY', 1);
38

    
39
/**
40
 * Nodes changed before this time are always marked as read.
41
 *
42
 * Nodes changed after this time may be marked new, updated, or read, depending
43
 * on their state for the current user. Defaults to 30 days ago.
44
 */
45
define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
46

    
47
/**
48
 * Modules should return this value from hook_node_access() to allow access to a node.
49
 */
50
define('NODE_ACCESS_ALLOW', 'allow');
51

    
52
/**
53
 * Modules should return this value from hook_node_access() to deny access to a node.
54
 */
55
define('NODE_ACCESS_DENY', 'deny');
56

    
57
/**
58
 * Modules should return this value from hook_node_access() to not affect node access.
59
 */
60
define('NODE_ACCESS_IGNORE', NULL);
61

    
62
/**
63
 * Implements hook_help().
64
 */
65
function node_help($path, $arg) {
66
  // Remind site administrators about the {node_access} table being flagged
67
  // for rebuild. We don't need to issue the message on the confirm form, or
68
  // while the rebuild is being processed.
69
  if ($path != 'admin/reports/status/rebuild' && $path != 'batch' && strpos($path, '#') === FALSE
70
      && user_access('access administration pages') && node_access_needs_rebuild()) {
71
    if ($path == 'admin/reports/status') {
72
      $message = t('The content access permissions need to be rebuilt.');
73
    }
74
    else {
75
      $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')));
76
    }
77
    drupal_set_message($message, 'error');
78
  }
79

    
80
  switch ($path) {
81
    case 'admin/help#node':
82
      $output = '';
83
      $output .= '<h3>' . t('About') . '</h3>';
84
      $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>';
85
      $output .= '<h3>' . t('Uses') . '</h3>';
86
      $output .= '<dl>';
87
      $output .= '<dt>' . t('Creating content') . '</dt>';
88
      $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>';
89
      $output .= '<dt>' . t('Creating custom content types') . '</dt>';
90
      $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>';
91
      $output .= '<dt>' . t('Administering content') . '</dt>';
92
      $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>';
93
      $output .= '<dt>' . t('Creating revisions') . '</dt>';
94
      $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>';
95
      $output .= '<dt>' . t('User permissions') . '</dt>';
96
      $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>';
97
      $output .= '</dl>';
98
      return $output;
99

    
100
    case 'admin/structure/types/add':
101
      return '<p>' . t('Individual content types can have different fields, behaviors, and permissions assigned to them.') . '</p>';
102

    
103
    case 'admin/structure/types/manage/%/display':
104
      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>' .
105
        '<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' => node_type_get_name($arg[4]))) . '</p>';
106

    
107
    case 'node/%/revisions':
108
      return '<p>' . t('Revisions allow you to track differences between multiple versions of your content, and revert back to older versions.') . '</p>';
109

    
110
    case 'node/%/edit':
111
      $node = node_load($arg[1]);
112
      $type = node_type_get_type($node);
113
      return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
114
  }
115

    
116
  if ($arg[0] == 'node' && $arg[1] == 'add' && $arg[2]) {
117
    $type = node_type_get_type(str_replace('-', '_', $arg[2]));
118
    return (!empty($type->help) ? '<p>' . filter_xss_admin($type->help) . '</p>' : '');
119
  }
120
}
121

    
122
/**
123
 * Implements hook_theme().
124
 */
125
function node_theme() {
126
  return array(
127
    'node' => array(
128
      'render element' => 'elements',
129
      'template' => 'node',
130
    ),
131
    'node_search_admin' => array(
132
      'render element' => 'form',
133
    ),
134
    'node_add_list' => array(
135
      'variables' => array('content' => NULL),
136
      'file' => 'node.pages.inc',
137
    ),
138
    'node_preview' => array(
139
      'variables' => array('node' => NULL),
140
      'file' => 'node.pages.inc',
141
    ),
142
    'node_admin_overview' => array(
143
      'variables' => array('name' => NULL, 'type' => NULL),
144
      'file' => 'content_types.inc',
145
    ),
146
    'node_recent_block' => array(
147
      'variables' => array('nodes' => NULL),
148
    ),
149
    'node_recent_content' => array(
150
      'variables' => array('node' => NULL),
151
    ),
152
  );
153
}
154

    
155
/**
156
 * Implements hook_cron().
157
 */
158
function node_cron() {
159
  db_delete('history')
160
    ->condition('timestamp', NODE_NEW_LIMIT, '<')
161
    ->execute();
162
}
163

    
164
/**
165
 * Implements hook_entity_info().
166
 */
167
function node_entity_info() {
168
  $return = array(
169
    'node' => array(
170
      'label' => t('Node'),
171
      'controller class' => 'NodeController',
172
      'base table' => 'node',
173
      'revision table' => 'node_revision',
174
      'uri callback' => 'node_uri',
175
      'fieldable' => TRUE,
176
      'entity keys' => array(
177
        'id' => 'nid',
178
        'revision' => 'vid',
179
        'bundle' => 'type',
180
        'label' => 'title',
181
        'language' => 'language',
182
      ),
183
      'bundle keys' => array(
184
        'bundle' => 'type',
185
      ),
186
      'bundles' => array(),
187
      'view modes' => array(
188
        'full' => array(
189
          'label' => t('Full content'),
190
          'custom settings' => FALSE,
191
        ),
192
        'teaser' => array(
193
          'label' => t('Teaser'),
194
          'custom settings' => TRUE,
195
        ),
196
        'rss' => array(
197
          'label' => t('RSS'),
198
          'custom settings' => FALSE,
199
        ),
200
      ),
201
    ),
202
  );
203

    
204
  // Search integration is provided by node.module, so search-related view modes
205
  // for nodes are defined here and not in search.module.
206
  if (module_exists('search')) {
207
    $return['node']['view modes'] += array(
208
      'search_index' => array(
209
        'label' => t('Search index'),
210
        'custom settings' => FALSE,
211
      ),
212
      'search_result' => array(
213
        'label' => t('Search result highlighting input'),
214
        'custom settings' => FALSE,
215
      ),
216
    );
217
  }
218

    
219
  // Bundles must provide a human readable name so we can create help and error
220
  // messages, and the path to attach Field admin pages to.
221
  foreach (node_type_get_names() as $type => $name) {
222
    $return['node']['bundles'][$type] = array(
223
      'label' => $name,
224
      'admin' => array(
225
        'path' => 'admin/structure/types/manage/%node_type',
226
        'real path' => 'admin/structure/types/manage/' . str_replace('_', '-', $type),
227
        'bundle argument' => 4,
228
        'access arguments' => array('administer content types'),
229
      ),
230
    );
231
  }
232

    
233
  return $return;
234
}
235

    
236
/**
237
 * Implements hook_field_display_ENTITY_TYPE_alter().
238
 */
239
function node_field_display_node_alter(&$display, $context) {
240
  // Hide field labels in search index.
241
  if ($context['view_mode'] == 'search_index') {
242
    $display['label'] = 'hidden';
243
  }
244
}
245

    
246
/**
247
 * Implements callback_entity_info_uri().
248
 */
249
function node_uri($node) {
250
  return array(
251
    'path' => 'node/' . $node->nid,
252
  );
253
}
254

    
255
/**
256
 * Implements hook_admin_paths().
257
 */
258
function node_admin_paths() {
259
  if (variable_get('node_admin_theme')) {
260
    $paths = array(
261
      'node/*/edit' => TRUE,
262
      'node/*/delete' => TRUE,
263
      'node/*/revisions' => TRUE,
264
      'node/*/revisions/*/revert' => TRUE,
265
      'node/*/revisions/*/delete' => TRUE,
266
      'node/add' => TRUE,
267
      'node/add/*' => TRUE,
268
    );
269
    return $paths;
270
  }
271
}
272

    
273
/**
274
 * Gathers a listing of links to nodes.
275
 *
276
 * @param $result
277
 *   A database result object from a query to fetch node entities. If your
278
 *   query joins the {node_comment_statistics} table so that the comment_count
279
 *   field is available, a title attribute will be added to show the number of
280
 *   comments.
281
 * @param $title
282
 *   A heading for the resulting list.
283
 *
284
 * @return
285
 *   A renderable array containing a list of linked node titles fetched from
286
 *   $result, or FALSE if there are no rows in $result.
287
 */
288
function node_title_list($result, $title = NULL) {
289
  $items = array();
290
  $num_rows = FALSE;
291
  foreach ($result as $node) {
292
    $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());
293
    $num_rows = TRUE;
294
  }
295

    
296
  return $num_rows ? array('#theme' => 'item_list__node', '#items' => $items, '#title' => $title) : FALSE;
297
}
298

    
299
/**
300
 * Updates the 'last viewed' timestamp of the specified node for current user.
301
 *
302
 * @param $node
303
 *   A node object.
304
 */
305
function node_tag_new($node) {
306
  global $user;
307
  if ($user->uid) {
308
    db_merge('history')
309
      ->key(array(
310
        'uid' => $user->uid,
311
        'nid' => $node->nid,
312
      ))
313
      ->fields(array('timestamp' => REQUEST_TIME))
314
      ->execute();
315
   }
316
}
317

    
318
/**
319
 * Retrieves the timestamp for the current user's last view of a specified node.
320
 *
321
 * @param $nid
322
 *   A node ID.
323
 *
324
 * @return
325
 *   If a node has been previously viewed by the user, the timestamp in seconds
326
 *   of when the last view occurred; otherwise, zero.
327
 */
328
function node_last_viewed($nid) {
329
  global $user;
330
  $history = &drupal_static(__FUNCTION__, array());
331

    
332
  if (!isset($history[$nid])) {
333
    $history[$nid] = db_query("SELECT timestamp FROM {history} WHERE uid = :uid AND nid = :nid", array(':uid' => $user->uid, ':nid' => $nid))->fetchObject();
334
  }
335

    
336
  return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
337
}
338

    
339
/**
340
 * Determines the type of marker to be displayed for a given node.
341
 *
342
 * @param $nid
343
 *   Node ID whose history supplies the "last viewed" timestamp.
344
 * @param $timestamp
345
 *   Time which is compared against node's "last viewed" timestamp.
346
 *
347
 * @return
348
 *   One of the MARK constants.
349
 */
350
function node_mark($nid, $timestamp) {
351
  global $user;
352
  $cache = &drupal_static(__FUNCTION__, array());
353

    
354
  if (!$user->uid) {
355
    return MARK_READ;
356
  }
357
  if (!isset($cache[$nid])) {
358
    $cache[$nid] = node_last_viewed($nid);
359
  }
360
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
361
    return MARK_NEW;
362
  }
363
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
364
    return MARK_UPDATED;
365
  }
366
  return MARK_READ;
367
}
368

    
369
/**
370
 * Extracts the type name.
371
 *
372
 * @param $node
373
 *   Either a string or object, containing the node type information.
374
 *
375
 * @return
376
 *   Node type of the passed-in data.
377
 */
378
function _node_extract_type($node) {
379
  return is_object($node) ? $node->type : $node;
380
}
381

    
382
/**
383
 * Returns a list of all the available node types.
384
 *
385
 * This list can include types that are queued for addition or deletion.
386
 * See _node_types_build() for details.
387
 *
388
 * @return
389
 *   An array of node types, as objects, keyed by the type.
390
 *
391
 * @see node_type_get_type()
392
 */
393
function node_type_get_types() {
394
  return _node_types_build()->types;
395
}
396

    
397
/**
398
 * Returns the node type of the passed node or node type string.
399
 *
400
 * @param $node
401
 *   A node object or string that indicates the node type to return.
402
 *
403
 * @return
404
 *   A single node type, as an object, or FALSE if the node type is not found.
405
 *   The node type is an object containing fields from hook_node_info() return
406
 *   values, as well as the field 'type' (the machine-readable type) and other
407
 *   fields used internally and defined in _node_types_build(),
408
 *   hook_node_info(), and node_type_set_defaults().
409
 */
410
function node_type_get_type($node) {
411
  $type = _node_extract_type($node);
412
  $types = _node_types_build()->types;
413
  return isset($types[$type]) ? $types[$type] : FALSE;
414
}
415

    
416
/**
417
 * Returns the node type base of the passed node or node type string.
418
 *
419
 * The base indicates which module implements this node type and is used to
420
 * execute node-type-specific hooks. For types defined in the user interface
421
 * and managed by node.module, the base is 'node_content'.
422
 *
423
 * @param $node
424
 *   A node object or string that indicates the node type to return.
425
 *
426
 * @return
427
 *   The node type base or FALSE if the node type is not found.
428
 *
429
 * @see node_invoke()
430
 */
431
function node_type_get_base($node) {
432
  $type = _node_extract_type($node);
433
  $types = _node_types_build()->types;
434
  return isset($types[$type]) && isset($types[$type]->base) ? $types[$type]->base : FALSE;
435
}
436

    
437
/**
438
 * Returns a list of available node type names.
439
 *
440
 * This list can include types that are queued for addition or deletion.
441
 * See _node_types_build() for details.
442
 *
443
 * @return
444
 *   An array of node type names, keyed by the type.
445
 */
446
function node_type_get_names() {
447
  return _node_types_build()->names;
448
}
449

    
450
/**
451
 * Returns the node type name of the passed node or node type string.
452
 *
453
 * @param $node
454
 *   A node object or string that indicates the node type to return.
455
 *
456
 * @return
457
 *   The node type name or FALSE if the node type is not found.
458
 */
459
function node_type_get_name($node) {
460
  $type = _node_extract_type($node);
461
  $types = _node_types_build()->names;
462
  return isset($types[$type]) ? $types[$type] : FALSE;
463
}
464

    
465
/**
466
 * Updates the database cache of node types.
467
 *
468
 * All new module-defined node types are saved to the database via a call to
469
 * node_type_save(), and obsolete ones are deleted via a call to
470
 * node_type_delete(). See _node_types_build() for an explanation of the new
471
 * and obsolete types.
472
 *
473
 * @see _node_types_build()
474
 */
475
function node_types_rebuild() {
476
  _node_types_build(TRUE);
477
}
478

    
479
/**
480
 * Menu argument loader: loads a node type by string.
481
 *
482
 * @param $name
483
 *   The machine-readable name of a node type to load, where '_' is replaced
484
 *   with '-'.
485
 *
486
 * @return
487
 *   A node type object or FALSE if $name does not exist.
488
 */
489
function node_type_load($name) {
490
  return node_type_get_type(strtr($name, array('-' => '_')));
491
}
492

    
493
/**
494
 * Saves a node type to the database.
495
 *
496
 * @param object $info
497
 *   The node type to save; an object with the following properties:
498
 *   - type: A string giving the machine name of the node type.
499
 *   - name: A string giving the human-readable name of the node type.
500
 *   - base: A string that indicates the base string for hook functions. For
501
 *     example, 'node_content' is the value used by the UI when creating a new
502
 *     node type.
503
 *   - description: A string that describes the node type.
504
 *   - help: A string giving the help information shown to the user when
505
 *     creating a node of this type.
506
 *   - custom: TRUE or FALSE indicating whether this type is defined by a module
507
 *     (FALSE) or by a user (TRUE) via Add Content Type.
508
 *   - modified: TRUE or FALSE indicating whether this type has been modified by
509
 *     an administrator. When modifying an existing node type, set to TRUE, or
510
 *     the change will be ignored on node_types_rebuild().
511
 *   - locked: TRUE or FALSE indicating whether the administrator can change the
512
 *     machine name of this type.
513
 *   - disabled: TRUE or FALSE indicating whether this type has been disabled.
514
 *   - has_title: TRUE or FALSE indicating whether this type uses the node title
515
 *     field.
516
 *   - title_label: A string containing the label for the title.
517
 *   - module: A string giving the module defining this type of node.
518
 *   - orig_type: A string giving the original machine-readable name of this
519
 *     node type. This may be different from the current type name if the
520
 *     'locked' key is FALSE.
521
 *
522
 * @return int
523
 *   A status flag indicating the outcome of the operation, either SAVED_NEW or
524
 *   SAVED_UPDATED.
525
 */
526
function node_type_save($info) {
527
  $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
528
  $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
529
  $type = node_type_set_defaults($info);
530

    
531
  $fields = array(
532
    'type' => (string) $type->type,
533
    'name' => (string) $type->name,
534
    'base' => (string) $type->base,
535
    'has_title' => (int) $type->has_title,
536
    'title_label' => (string) $type->title_label,
537
    'description' => (string) $type->description,
538
    'help' => (string) $type->help,
539
    'custom' => (int) $type->custom,
540
    'modified' => (int) $type->modified,
541
    'locked' => (int) $type->locked,
542
    'disabled' => (int) $type->disabled,
543
    'module' => $type->module,
544
  );
545

    
546
  if ($is_existing) {
547
    db_update('node_type')
548
      ->fields($fields)
549
      ->condition('type', $existing_type)
550
      ->execute();
551

    
552
    if (!empty($type->old_type) && $type->old_type != $type->type) {
553
      field_attach_rename_bundle('node', $type->old_type, $type->type);
554
    }
555
    module_invoke_all('node_type_update', $type);
556
    $status = SAVED_UPDATED;
557
  }
558
  else {
559
    $fields['orig_type'] = (string) $type->orig_type;
560
    db_insert('node_type')
561
      ->fields($fields)
562
      ->execute();
563

    
564
    field_attach_create_bundle('node', $type->type);
565

    
566
    module_invoke_all('node_type_insert', $type);
567
    $status = SAVED_NEW;
568
  }
569

    
570
  // Clear the node type cache.
571
  node_type_cache_reset();
572

    
573
  return $status;
574
}
575

    
576
/**
577
 * Adds default body field to a node type.
578
 *
579
 * @param $type
580
 *   A node type object.
581
 * @param $label
582
 *   The label for the body instance.
583
 *
584
 * @return
585
 *   Body field instance.
586
 */
587
function node_add_body_field($type, $label = 'Body') {
588
   // Add or remove the body field, as needed.
589
  $field = field_info_field('body');
590
  $instance = field_info_instance('node', 'body', $type->type);
591
  if (empty($field)) {
592
    $field = array(
593
      'field_name' => 'body',
594
      'type' => 'text_with_summary',
595
      'entity_types' => array('node'),
596
    );
597
    $field = field_create_field($field);
598
  }
599
  if (empty($instance)) {
600
    $instance = array(
601
      'field_name' => 'body',
602
      'entity_type' => 'node',
603
      'bundle' => $type->type,
604
      'label' => $label,
605
      'widget' => array('type' => 'text_textarea_with_summary'),
606
      'settings' => array('display_summary' => TRUE),
607
      'display' => array(
608
        'default' => array(
609
          'label' => 'hidden',
610
          'type' => 'text_default',
611
        ),
612
        'teaser' => array(
613
          'label' => 'hidden',
614
          'type' => 'text_summary_or_trimmed',
615
        ),
616
      ),
617
    );
618
    $instance = field_create_instance($instance);
619
  }
620
  return $instance;
621
}
622

    
623
/**
624
 * Implements hook_field_extra_fields().
625
 */
626
function node_field_extra_fields() {
627
  $extra = array();
628

    
629
  foreach (node_type_get_types() as $type) {
630
    if ($type->has_title) {
631
      $extra['node'][$type->type] = array(
632
        'form' => array(
633
          'title' => array(
634
            'label' => $type->title_label,
635
            'description' => t('Node module element'),
636
            'weight' => -5,
637
          ),
638
        ),
639
      );
640
    }
641
  }
642

    
643
  return $extra;
644
}
645

    
646
/**
647
 * Deletes a node type from the database.
648
 *
649
 * @param $type
650
 *   The machine-readable name of the node type to be deleted.
651
 */
652
function node_type_delete($type) {
653
  $info = node_type_get_type($type);
654
  db_delete('node_type')
655
    ->condition('type', $type)
656
    ->execute();
657
  field_attach_delete_bundle('node', $type);
658
  module_invoke_all('node_type_delete', $info);
659

    
660
  // Clear the node type cache.
661
  node_type_cache_reset();
662
}
663

    
664
/**
665
 * Updates all nodes of one type to be of another type.
666
 *
667
 * @param $old_type
668
 *   The current node type of the nodes.
669
 * @param $type
670
 *   The new node type of the nodes.
671
 *
672
 * @return
673
 *   The number of nodes whose node type field was modified.
674
 */
675
function node_type_update_nodes($old_type, $type) {
676
  return db_update('node')
677
    ->fields(array('type' => $type))
678
    ->condition('type', $old_type)
679
    ->execute();
680
}
681

    
682
/**
683
 * Builds and returns the list of available node types.
684
 *
685
 * The list of types is built by invoking hook_node_info() on all modules and
686
 * comparing this information with the node types in the {node_type} table.
687
 * These two information sources are not synchronized during module installation
688
 * until node_types_rebuild() is called.
689
 *
690
 * @param $rebuild
691
 *  TRUE to rebuild node types. Equivalent to calling node_types_rebuild().
692
 *
693
 * @return
694
 *   An object with two properties:
695
 *   - names: Associative array of the names of node types, keyed by the type.
696
 *   - types: Associative array of node type objects, keyed by the type.
697
 *   Both of these arrays will include new types that have been defined by
698
 *   hook_node_info() implementations but not yet saved in the {node_type}
699
 *   table. These are indicated in the type object by $type->is_new being set
700
 *   to the value 1. These arrays will also include obsolete types: types that
701
 *   were previously defined by modules that have now been disabled, or for
702
 *   whatever reason are no longer being defined in hook_node_info()
703
 *   implementations, but are still in the database. These are indicated in the
704
 *   type object by $type->disabled being set to TRUE.
705
 */
706
function _node_types_build($rebuild = FALSE) {
707
  $cid = 'node_types:' . $GLOBALS['language']->language;
708

    
709
  if (!$rebuild) {
710
    $_node_types = &drupal_static(__FUNCTION__);
711
    if (isset($_node_types)) {
712
      return $_node_types;
713
    }
714
    if ($cache = cache_get($cid)) {
715
      $_node_types = $cache->data;
716
      return $_node_types;
717
    }
718
  }
719

    
720
  $_node_types = (object) array('types' => array(), 'names' => array());
721

    
722
  foreach (module_implements('node_info') as $module) {
723
    $info_array = module_invoke($module, 'node_info');
724
    foreach ($info_array as $type => $info) {
725
      $info['type'] = $type;
726
      $_node_types->types[$type] = node_type_set_defaults($info);
727
      $_node_types->types[$type]->module = $module;
728
      $_node_types->names[$type] = $info['name'];
729
    }
730
  }
731
  $query = db_select('node_type', 'nt')
732
    ->addTag('translatable')
733
    ->addTag('node_type_access')
734
    ->fields('nt')
735
    ->orderBy('nt.type', 'ASC');
736
  if (!$rebuild) {
737
    $query->condition('disabled', 0);
738
  }
739
  foreach ($query->execute() as $type_object) {
740
    $type_db = $type_object->type;
741
    // Original disabled value.
742
    $disabled = $type_object->disabled;
743
    // Check for node types either from disabled modules or otherwise not defined
744
    // and mark as disabled.
745
    if (empty($type_object->custom) && empty($_node_types->types[$type_db])) {
746
      $type_object->disabled = TRUE;
747
    }
748
    if (isset($_node_types->types[$type_db])) {
749
      $type_object->disabled = FALSE;
750
    }
751
    if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
752
      $_node_types->types[$type_db] = $type_object;
753
      $_node_types->names[$type_db] = $type_object->name;
754

    
755
      if ($type_db != $type_object->orig_type) {
756
        unset($_node_types->types[$type_object->orig_type]);
757
        unset($_node_types->names[$type_object->orig_type]);
758
      }
759
    }
760
    $_node_types->types[$type_db]->disabled = $type_object->disabled;
761
    $_node_types->types[$type_db]->disabled_changed = $disabled != $type_object->disabled;
762
  }
763

    
764
  if ($rebuild) {
765
    foreach ($_node_types->types as $type => $type_object) {
766
      if (!empty($type_object->is_new) || !empty($type_object->disabled_changed)) {
767
        node_type_save($type_object);
768
      }
769
    }
770
  }
771

    
772
  asort($_node_types->names);
773

    
774
  cache_set($cid, $_node_types);
775

    
776
  return $_node_types;
777
}
778

    
779
/**
780
 * Clears the node type cache.
781
 */
782
function node_type_cache_reset() {
783
  cache_clear_all('node_types:', 'cache', TRUE);
784
  drupal_static_reset('_node_types_build');
785
}
786

    
787
/**
788
 * Sets the default values for a node type.
789
 *
790
 * The defaults are appropriate for a type defined through hook_node_info(),
791
 * since 'custom' is TRUE for types defined in the user interface, and FALSE
792
 * for types defined by modules. (The 'custom' flag prevents types from being
793
 * deleted through the user interface.) Also, the default for 'locked' is TRUE,
794
 * which prevents users from changing the machine name of the type.
795
 *
796
 * @param $info
797
 *   (optional) An object or array containing values to override the defaults.
798
 *   See hook_node_info() for details on what the array elements mean. Defaults
799
 *   to an empty array.
800
 *
801
 * @return
802
 *   A node type object, with missing values in $info set to their defaults.
803
 */
804
function node_type_set_defaults($info = array()) {
805
  $info = (array) $info;
806
  $new_type = $info + array(
807
    'type' => '',
808
    'name' => '',
809
    'base' => '',
810
    'description' => '',
811
    'help' => '',
812
    'custom' => 0,
813
    'modified' => 0,
814
    'locked' => 1,
815
    'disabled' => 0,
816
    'is_new' => 1,
817
    'has_title' => 1,
818
    'title_label' => 'Title',
819
  );
820
  $new_type = (object) $new_type;
821

    
822
  // If the type has no title, set an empty label.
823
  if (!$new_type->has_title) {
824
    $new_type->title_label = '';
825
  }
826
  if (empty($new_type->module)) {
827
    $new_type->module = $new_type->base == 'node_content' ? 'node' : '';
828
  }
829
  $new_type->orig_type = isset($info['type']) ? $info['type'] : '';
830

    
831
  return $new_type;
832
}
833

    
834
/**
835
 * Implements hook_rdf_mapping().
836
 */
837
function node_rdf_mapping() {
838
  return array(
839
    array(
840
      'type' => 'node',
841
      'bundle' => RDF_DEFAULT_BUNDLE,
842
      'mapping' => array(
843
        'rdftype' => array('sioc:Item', 'foaf:Document'),
844
        'title' => array(
845
          'predicates' => array('dc:title'),
846
        ),
847
        'created' => array(
848
          'predicates' => array('dc:date', 'dc:created'),
849
          'datatype' => 'xsd:dateTime',
850
          'callback' => 'date_iso8601',
851
        ),
852
        'changed' => array(
853
          'predicates' => array('dc:modified'),
854
          'datatype' => 'xsd:dateTime',
855
          'callback' => 'date_iso8601',
856
        ),
857
        'body' => array(
858
          'predicates' => array('content:encoded'),
859
        ),
860
        'uid' => array(
861
          'predicates' => array('sioc:has_creator'),
862
          'type' => 'rel',
863
        ),
864
        'name' => array(
865
          'predicates' => array('foaf:name'),
866
        ),
867
        'comment_count' => array(
868
          'predicates' => array('sioc:num_replies'),
869
          'datatype' => 'xsd:integer',
870
        ),
871
        'last_activity' => array(
872
          'predicates' => array('sioc:last_activity_date'),
873
          'datatype' => 'xsd:dateTime',
874
          'callback' => 'date_iso8601',
875
        ),
876
      ),
877
    ),
878
  );
879
}
880

    
881
/**
882
 * Determines whether a node hook exists.
883
 *
884
 * @param $node
885
 *   A node object or a string containing the node type.
886
 * @param $hook
887
 *   A string containing the name of the hook.
888
 *
889
 * @return
890
 *   TRUE if the $hook exists in the node type of $node.
891
 */
892
function node_hook($node, $hook) {
893
  $base = node_type_get_base($node);
894
  return module_hook($base, $hook);
895
}
896

    
897
/**
898
 * Invokes a node hook.
899
 *
900
 * @param $node
901
 *   A node object or a string containing the node type.
902
 * @param $hook
903
 *   A string containing the name of the hook.
904
 * @param $a2, $a3, $a4
905
 *   Arguments to pass on to the hook, after the $node argument.
906
 *
907
 * @return
908
 *   The returned value of the invoked hook.
909
 */
910
function node_invoke($node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
911
  if (node_hook($node, $hook)) {
912
    $base = node_type_get_base($node);
913
    $function = $base . '_' . $hook;
914
    return ($function($node, $a2, $a3, $a4));
915
  }
916
}
917

    
918
/**
919
 * Loads node entities from the database.
920
 *
921
 * This function should be used whenever you need to load more than one node
922
 * from the database. Nodes are loaded into memory and will not require database
923
 * access if loaded again during the same page request.
924
 *
925
 * @see entity_load()
926
 * @see EntityFieldQuery
927
 *
928
 * @param $nids
929
 *   An array of node IDs.
930
 * @param $conditions
931
 *   (deprecated) An associative array of conditions on the {node}
932
 *   table, where the keys are the database fields and the values are the
933
 *   values those fields must have. Instead, it is preferable to use
934
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
935
 *   this function.
936
 * @param $reset
937
 *   Whether to reset the internal node_load cache.
938
 *
939
 * @return
940
 *   An array of node objects indexed by nid.
941
 *
942
 * @todo Remove $conditions in Drupal 8.
943
 */
944
function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
945
  return entity_load('node', $nids, $conditions, $reset);
946
}
947

    
948
/**
949
 * Loads a node object from the database.
950
 *
951
 * @param $nid
952
 *   The node ID.
953
 * @param $vid
954
 *   The revision ID.
955
 * @param $reset
956
 *   Whether to reset the node_load_multiple cache.
957
 *
958
 * @return
959
 *   A fully-populated node object, or FALSE if the node is not found.
960
 */
961
function node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
962
  $nids = (isset($nid) ? array($nid) : array());
963
  $conditions = (isset($vid) ? array('vid' => $vid) : array());
964
  $node = node_load_multiple($nids, $conditions, $reset);
965
  return $node ? reset($node) : FALSE;
966
}
967

    
968
/**
969
 * Prepares a node object for editing.
970
 *
971
 * Fills in a few default values, and then invokes hook_prepare() on the node
972
 * type module, and hook_node_prepare() on all modules.
973
 *
974
 * @param $node
975
 *   A node object.
976
 */
977
function node_object_prepare($node) {
978
  // Set up default values, if required.
979
  $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
980
  // If this is a new node, fill in the default values.
981
  if (!isset($node->nid) || isset($node->is_new)) {
982
    foreach (array('status', 'promote', 'sticky') as $key) {
983
      // Multistep node forms might have filled in something already.
984
      if (!isset($node->$key)) {
985
        $node->$key = (int) in_array($key, $node_options);
986
      }
987
    }
988
    global $user;
989
    $node->uid = $user->uid;
990
    $node->created = REQUEST_TIME;
991
  }
992
  else {
993
    $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
994
    // Remove the log message from the original node object.
995
    $node->log = NULL;
996
  }
997
  // Always use the default revision setting.
998
  $node->revision = in_array('revision', $node_options);
999

    
1000
  node_invoke($node, 'prepare');
1001
  module_invoke_all('node_prepare', $node);
1002
}
1003

    
1004
/**
1005
 * Implements hook_validate().
1006
 *
1007
 * Performs validation checks on the given node.
1008
 */
1009
function node_validate($node, $form, &$form_state) {
1010
  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
1011
    form_set_error('changed', t('The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.'));
1012
  }
1013

    
1014
  // Validate the "authored by" field.
1015
  if (!empty($node->name) && !($account = user_load_by_name($node->name))) {
1016
    // The use of empty() is mandatory in the context of usernames
1017
    // as the empty string denotes the anonymous user. In case we
1018
    // are dealing with an anonymous user we set the user ID to 0.
1019
    form_set_error('name', t('The username %name does not exist.', array('%name' => $node->name)));
1020
  }
1021

    
1022
  // Validate the "authored on" field.
1023
  if (!empty($node->date) && strtotime($node->date) === FALSE) {
1024
    form_set_error('date', t('You have to specify a valid date.'));
1025
  }
1026

    
1027
  // Invoke hook_validate() for node type specific validation and
1028
  // hook_node_validate() for miscellaneous validation needed by modules. Can't
1029
  // use node_invoke() or module_invoke_all(), because $form_state must be
1030
  // receivable by reference.
1031
  $function = node_type_get_base($node) . '_validate';
1032
  if (function_exists($function)) {
1033
    $function($node, $form, $form_state);
1034
  }
1035
  foreach (module_implements('node_validate') as $module) {
1036
    $function = $module . '_node_validate';
1037
    $function($node, $form, $form_state);
1038
  }
1039
}
1040

    
1041
/**
1042
 * Prepares node for saving by populating author and creation date.
1043
 *
1044
 * @param $node
1045
 *   A node object.
1046
 *
1047
 * @return
1048
 *   An updated node object.
1049
 */
1050
function node_submit($node) {
1051
  // A user might assign the node author by entering a user name in the node
1052
  // form, which we then need to translate to a user ID.
1053
  if (isset($node->name)) {
1054
    if ($account = user_load_by_name($node->name)) {
1055
      $node->uid = $account->uid;
1056
    }
1057
    else {
1058
      $node->uid = 0;
1059
    }
1060
  }
1061

    
1062
  $node->created = !empty($node->date) ? strtotime($node->date) : REQUEST_TIME;
1063
  $node->validated = TRUE;
1064

    
1065
  return $node;
1066
}
1067

    
1068
/**
1069
 * Saves changes to a node or adds a new node.
1070
 *
1071
 * @param $node
1072
 *   The $node object to be saved. If $node->nid is
1073
 *   omitted (or $node->is_new is TRUE), a new node will be added.
1074
 */
1075
function node_save($node) {
1076
  $transaction = db_transaction();
1077

    
1078
  try {
1079
    // Load the stored entity, if any.
1080
    if (!empty($node->nid) && !isset($node->original)) {
1081
      $node->original = entity_load_unchanged('node', $node->nid);
1082
    }
1083

    
1084
    field_attach_presave('node', $node);
1085
    global $user;
1086

    
1087
    // Determine if we will be inserting a new node.
1088
    if (!isset($node->is_new)) {
1089
      $node->is_new = empty($node->nid);
1090
    }
1091

    
1092
    // Set the timestamp fields.
1093
    if (empty($node->created)) {
1094
      $node->created = REQUEST_TIME;
1095
    }
1096
    // The changed timestamp is always updated for bookkeeping purposes,
1097
    // for example: revisions, searching, etc.
1098
    $node->changed = REQUEST_TIME;
1099

    
1100
    $node->timestamp = REQUEST_TIME;
1101
    $update_node = TRUE;
1102

    
1103
    // Let modules modify the node before it is saved to the database.
1104
    module_invoke_all('node_presave', $node);
1105
    module_invoke_all('entity_presave', $node, 'node');
1106

    
1107
    if ($node->is_new || !empty($node->revision)) {
1108
      // When inserting either a new node or a new node revision, $node->log
1109
      // must be set because {node_revision}.log is a text column and therefore
1110
      // cannot have a default value. However, it might not be set at this
1111
      // point (for example, if the user submitting a node form does not have
1112
      // permission to create revisions), so we ensure that it is at least an
1113
      // empty string in that case.
1114
      // @todo: Make the {node_revision}.log column nullable so that we can
1115
      // remove this check.
1116
      if (!isset($node->log)) {
1117
        $node->log = '';
1118
      }
1119
    }
1120
    elseif (!isset($node->log) || $node->log === '') {
1121
      // If we are updating an existing node without adding a new revision, we
1122
      // need to make sure $node->log is unset whenever it is empty. As long as
1123
      // $node->log is unset, drupal_write_record() will not attempt to update
1124
      // the existing database column when re-saving the revision; therefore,
1125
      // this code allows us to avoid clobbering an existing log entry with an
1126
      // empty one.
1127
      unset($node->log);
1128
    }
1129

    
1130
    // When saving a new node revision, unset any existing $node->vid so as to
1131
    // ensure that a new revision will actually be created, then store the old
1132
    // revision ID in a separate property for use by node hook implementations.
1133
    if (!$node->is_new && !empty($node->revision) && $node->vid) {
1134
      $node->old_vid = $node->vid;
1135
      unset($node->vid);
1136
    }
1137

    
1138
    // Save the node and node revision.
1139
    if ($node->is_new) {
1140
      // For new nodes, save new records for both the node itself and the node
1141
      // revision.
1142
      drupal_write_record('node', $node);
1143
      _node_save_revision($node, $user->uid);
1144
      $op = 'insert';
1145
    }
1146
    else {
1147
      // For existing nodes, update the node record which matches the value of
1148
      // $node->nid.
1149
      drupal_write_record('node', $node, 'nid');
1150
      // Then, if a new node revision was requested, save a new record for
1151
      // that; otherwise, update the node revision record which matches the
1152
      // value of $node->vid.
1153
      if (!empty($node->revision)) {
1154
        _node_save_revision($node, $user->uid);
1155
      }
1156
      else {
1157
        _node_save_revision($node, $user->uid, 'vid');
1158
        $update_node = FALSE;
1159
      }
1160
      $op = 'update';
1161
    }
1162
    if ($update_node) {
1163
      db_update('node')
1164
        ->fields(array('vid' => $node->vid))
1165
        ->condition('nid', $node->nid)
1166
        ->execute();
1167
    }
1168

    
1169
    // Call the node specific callback (if any). This can be
1170
    // node_invoke($node, 'insert') or
1171
    // node_invoke($node, 'update').
1172
    node_invoke($node, $op);
1173

    
1174
    // Save fields.
1175
    $function = "field_attach_$op";
1176
    $function('node', $node);
1177

    
1178
    module_invoke_all('node_' . $op, $node);
1179
    module_invoke_all('entity_' . $op, $node, 'node');
1180

    
1181
    // Update the node access table for this node.
1182
    node_access_acquire_grants($node);
1183

    
1184
    // Clear internal properties.
1185
    unset($node->is_new);
1186
    unset($node->original);
1187
    // Clear the static loading cache.
1188
    entity_get_controller('node')->resetCache(array($node->nid));
1189

    
1190
    // Ignore slave server temporarily to give time for the
1191
    // saved node to be propagated to the slave.
1192
    db_ignore_slave();
1193
  }
1194
  catch (Exception $e) {
1195
    $transaction->rollback();
1196
    watchdog_exception('node', $e);
1197
    throw $e;
1198
  }
1199
}
1200

    
1201
/**
1202
 * Helper function to save a revision with the uid of the current user.
1203
 *
1204
 * The resulting revision ID is available afterward in $node->vid.
1205
 *
1206
 * @param $node
1207
 *   A node object.
1208
 * @param $uid
1209
 *   The current user's UID.
1210
 * @param $update
1211
 *   (optional) An array of primary keys' field names to update.
1212
 */
1213
function _node_save_revision($node, $uid, $update = NULL) {
1214
  $temp_uid = $node->uid;
1215
  $node->uid = $uid;
1216
  if (isset($update)) {
1217
    drupal_write_record('node_revision', $node, $update);
1218
  }
1219
  else {
1220
    drupal_write_record('node_revision', $node);
1221
  }
1222
  // Have node object still show node owner's uid, not revision author's.
1223
  $node->uid = $temp_uid;
1224
}
1225

    
1226
/**
1227
 * Deletes a node.
1228
 *
1229
 * @param $nid
1230
 *   A node ID.
1231
 */
1232
function node_delete($nid) {
1233
  node_delete_multiple(array($nid));
1234
}
1235

    
1236
/**
1237
 * Deletes multiple nodes.
1238
 *
1239
 * @param $nids
1240
 *   An array of node IDs.
1241
 */
1242
function node_delete_multiple($nids) {
1243
  $transaction = db_transaction();
1244
  if (!empty($nids)) {
1245
    $nodes = node_load_multiple($nids, array());
1246

    
1247
    try {
1248
      foreach ($nodes as $nid => $node) {
1249
        // Call the node-specific callback (if any):
1250
        node_invoke($node, 'delete');
1251
        module_invoke_all('node_delete', $node);
1252
        module_invoke_all('entity_delete', $node, 'node');
1253
        field_attach_delete('node', $node);
1254

    
1255
        // Remove this node from the search index if needed.
1256
        // This code is implemented in node module rather than in search module,
1257
        // because node module is implementing search module's API, not the other
1258
        // way around.
1259
        if (module_exists('search')) {
1260
          search_reindex($nid, 'node');
1261
        }
1262
      }
1263

    
1264
      // Delete after calling hooks so that they can query node tables as needed.
1265
      db_delete('node')
1266
        ->condition('nid', $nids, 'IN')
1267
        ->execute();
1268
      db_delete('node_revision')
1269
        ->condition('nid', $nids, 'IN')
1270
        ->execute();
1271
      db_delete('history')
1272
        ->condition('nid', $nids, 'IN')
1273
        ->execute();
1274
      db_delete('node_access')
1275
       ->condition('nid', $nids, 'IN')
1276
       ->execute();
1277
    }
1278
    catch (Exception $e) {
1279
      $transaction->rollback();
1280
      watchdog_exception('node', $e);
1281
      throw $e;
1282
    }
1283

    
1284
    // Clear the page and block and node_load_multiple caches.
1285
    entity_get_controller('node')->resetCache();
1286
  }
1287
}
1288

    
1289
/**
1290
 * Deletes a node revision.
1291
 *
1292
 * @param $revision_id
1293
 *   The revision ID to delete.
1294
 */
1295
function node_revision_delete($revision_id) {
1296
  if ($revision = node_load(NULL, $revision_id)) {
1297
    // Prevent deleting the current revision.
1298
    $node = node_load($revision->nid);
1299
    if ($revision_id == $node->vid) {
1300
      return FALSE;
1301
    }
1302

    
1303
    db_delete('node_revision')
1304
      ->condition('nid', $revision->nid)
1305
      ->condition('vid', $revision->vid)
1306
      ->execute();
1307
    module_invoke_all('node_revision_delete', $revision);
1308
    field_attach_delete_revision('node', $revision);
1309
    return TRUE;
1310
  }
1311
  return FALSE;
1312
}
1313

    
1314
/**
1315
 * Generates an array for rendering the given node.
1316
 *
1317
 * @param $node
1318
 *   A node object.
1319
 * @param $view_mode
1320
 *   View mode, e.g. 'full', 'teaser'...
1321
 * @param $langcode
1322
 *   (optional) A language code to use for rendering. Defaults to the global
1323
 *   content language of the current request.
1324
 *
1325
 * @return
1326
 *   An array as expected by drupal_render().
1327
 */
1328
function node_view($node, $view_mode = 'full', $langcode = NULL) {
1329
  if (!isset($langcode)) {
1330
    $langcode = $GLOBALS['language_content']->language;
1331
  }
1332

    
1333
  // Populate $node->content with a render() array.
1334
  node_build_content($node, $view_mode, $langcode);
1335

    
1336
  $build = $node->content;
1337
  // We don't need duplicate rendering info in node->content.
1338
  unset($node->content);
1339

    
1340
  $build += array(
1341
    '#theme' => 'node',
1342
    '#node' => $node,
1343
    '#view_mode' => $view_mode,
1344
    '#language' => $langcode,
1345
  );
1346

    
1347
  // Add contextual links for this node, except when the node is already being
1348
  // displayed on its own page. Modules may alter this behavior (for example,
1349
  // to restrict contextual links to certain view modes) by implementing
1350
  // hook_node_view_alter().
1351
  if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
1352
    $build['#contextual_links']['node'] = array('node', array($node->nid));
1353
  }
1354

    
1355
  // Allow modules to modify the structured node.
1356
  $type = 'node';
1357
  drupal_alter(array('node_view', 'entity_view'), $build, $type);
1358

    
1359
  return $build;
1360
}
1361

    
1362
/**
1363
 * Builds a structured array representing the node's content.
1364
 *
1365
 * The content built for the node (field values, comments, file attachments or
1366
 * other node components) will vary depending on the $view_mode parameter.
1367
 *
1368
 * Drupal core defines the following view modes for nodes, with the following
1369
 * default use cases:
1370
 *   - full (default): node is being displayed on its own page (node/123)
1371
 *   - teaser: node is being displayed on the default home page listing, on
1372
 *     taxonomy listing pages, or on blog listing pages.
1373
 *   - rss: node displayed in an RSS feed.
1374
 *   If search.module is enabled:
1375
 *   - search_index: node is being indexed for search.
1376
 *   - search_result: node is being displayed as a search result.
1377
 *   If book.module is enabled:
1378
 *   - print: node is being displayed in print-friendly mode.
1379
 * Contributed modules might define additional view modes, or use existing
1380
 * view modes in additional contexts.
1381
 *
1382
 * @param $node
1383
 *   A node object.
1384
 * @param $view_mode
1385
 *   View mode, e.g. 'full', 'teaser'...
1386
 * @param $langcode
1387
 *   (optional) A language code to use for rendering. Defaults to the global
1388
 *   content language of the current request.
1389
 */
1390
function node_build_content($node, $view_mode = 'full', $langcode = NULL) {
1391
  if (!isset($langcode)) {
1392
    $langcode = $GLOBALS['language_content']->language;
1393
  }
1394

    
1395
  // Remove previously built content, if exists.
1396
  $node->content = array();
1397

    
1398
  // Allow modules to change the view mode.
1399
  $view_mode = key(entity_view_mode_prepare('node', array($node->nid => $node), $view_mode, $langcode));
1400

    
1401
  // The 'view' hook can be implemented to overwrite the default function
1402
  // to display nodes.
1403
  if (node_hook($node, 'view')) {
1404
    $node = node_invoke($node, 'view', $view_mode, $langcode);
1405
  }
1406

    
1407
  // Build fields content.
1408
  // In case of a multiple view, node_view_multiple() already ran the
1409
  // 'prepare_view' step. An internal flag prevents the operation from running
1410
  // twice.
1411
  field_attach_prepare_view('node', array($node->nid => $node), $view_mode, $langcode);
1412
  entity_prepare_view('node', array($node->nid => $node), $langcode);
1413
  $node->content += field_attach_view('node', $node, $view_mode, $langcode);
1414

    
1415
  // Always display a read more link on teasers because we have no way to know
1416
  // when a teaser view is different than a full view.
1417
  $links = array();
1418
  $node->content['links'] = array(
1419
    '#theme' => 'links__node',
1420
    '#pre_render' => array('drupal_pre_render_links'),
1421
    '#attributes' => array('class' => array('links', 'inline')),
1422
  );
1423
  if ($view_mode == 'teaser') {
1424
    $node_title_stripped = strip_tags($node->title);
1425
    $links['node-readmore'] = array(
1426
      'title' => t('Read more<span class="element-invisible"> about @title</span>', array('@title' => $node_title_stripped)),
1427
      'href' => 'node/' . $node->nid,
1428
      'html' => TRUE,
1429
      'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped),
1430
    );
1431
  }
1432
  $node->content['links']['node'] = array(
1433
    '#theme' => 'links__node__node',
1434
    '#links' => $links,
1435
    '#attributes' => array('class' => array('links', 'inline')),
1436
  );
1437

    
1438
  // Allow modules to make their own additions to the node.
1439
  module_invoke_all('node_view', $node, $view_mode, $langcode);
1440
  module_invoke_all('entity_view', $node, 'node', $view_mode, $langcode);
1441

    
1442
  // Make sure the current view mode is stored if no module has already
1443
  // populated the related key.
1444
  $node->content += array('#view_mode' => $view_mode);
1445
}
1446

    
1447
/**
1448
 * Generates an array which displays a node detail page.
1449
 *
1450
 * @param $node
1451
 *   A node object.
1452
 * @param $message
1453
 *   A flag which sets a page title relevant to the revision being viewed.
1454
 *
1455
 * @return
1456
 *   A $page element suitable for use by drupal_render().
1457
 */
1458
function node_show($node, $message = FALSE) {
1459
  if ($message) {
1460
    drupal_set_title(t('Revision of %title from %date', array('%title' => $node->title, '%date' => format_date($node->revision_timestamp))), PASS_THROUGH);
1461
  }
1462

    
1463
  // For markup consistency with other pages, use node_view_multiple() rather than node_view().
1464
  $nodes = node_view_multiple(array($node->nid => $node), 'full');
1465

    
1466
  // Update the history table, stating that this user viewed this node.
1467
  node_tag_new($node);
1468

    
1469
  return $nodes;
1470
}
1471

    
1472
/**
1473
 * Returns whether the current page is the full page view of the passed-in node.
1474
 *
1475
 * @param $node
1476
 *   A node object.
1477
 *
1478
 * @return
1479
 *   The ID of the node if this is a full page view, otherwise FALSE.
1480
 */
1481
function node_is_page($node) {
1482
  $page_node = menu_get_object();
1483
  return (!empty($page_node) ? $page_node->nid == $node->nid : FALSE);
1484
}
1485

    
1486
/**
1487
 * Processes variables for node.tpl.php
1488
 *
1489
 * Most themes utilize their own copy of node.tpl.php. The default is located
1490
 * inside "modules/node/node.tpl.php". Look in there for the full list of
1491
 * variables.
1492
 *
1493
 * The $variables array contains the following arguments:
1494
 * - $node
1495
 * - $view_mode
1496
 * - $page
1497
 *
1498
 * @see node.tpl.php
1499
 */
1500
function template_preprocess_node(&$variables) {
1501
  $variables['view_mode'] = $variables['elements']['#view_mode'];
1502
  // Provide a distinct $teaser boolean.
1503
  $variables['teaser'] = $variables['view_mode'] == 'teaser';
1504
  $variables['node'] = $variables['elements']['#node'];
1505
  $node = $variables['node'];
1506

    
1507
  $variables['date']      = format_date($node->created);
1508
  $variables['name']      = theme('username', array('account' => $node));
1509

    
1510
  $uri = entity_uri('node', $node);
1511
  $variables['node_url']  = url($uri['path'], $uri['options']);
1512
  $variables['title']     = check_plain($node->title);
1513
  $variables['page']      = $variables['view_mode'] == 'full' && node_is_page($node);
1514

    
1515
  // Flatten the node object's member fields.
1516
  $variables = array_merge((array) $node, $variables);
1517

    
1518
  // Helpful $content variable for templates.
1519
  $variables += array('content' => array());
1520
  foreach (element_children($variables['elements']) as $key) {
1521
    $variables['content'][$key] = $variables['elements'][$key];
1522
  }
1523

    
1524
  // Make the field variables available with the appropriate language.
1525
  field_attach_preprocess('node', $node, $variables['content'], $variables);
1526

    
1527
  // Display post information only on certain node types.
1528
  if (variable_get('node_submitted_' . $node->type, TRUE)) {
1529
    $variables['display_submitted'] = TRUE;
1530
    $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
1531
    $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
1532
  }
1533
  else {
1534
    $variables['display_submitted'] = FALSE;
1535
    $variables['submitted'] = '';
1536
    $variables['user_picture'] = '';
1537
  }
1538

    
1539
  // Gather node classes.
1540
  $variables['classes_array'][] = drupal_html_class('node-' . $node->type);
1541
  if ($variables['promote']) {
1542
    $variables['classes_array'][] = 'node-promoted';
1543
  }
1544
  if ($variables['sticky']) {
1545
    $variables['classes_array'][] = 'node-sticky';
1546
  }
1547
  if (!$variables['status']) {
1548
    $variables['classes_array'][] = 'node-unpublished';
1549
  }
1550
  if ($variables['teaser']) {
1551
    $variables['classes_array'][] = 'node-teaser';
1552
  }
1553
  if (isset($variables['preview'])) {
1554
    $variables['classes_array'][] = 'node-preview';
1555
  }
1556

    
1557
  // Clean up name so there are no underscores.
1558
  $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
1559
  $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
1560
}
1561

    
1562
/**
1563
 * Implements hook_permission().
1564
 */
1565
function node_permission() {
1566
  $perms = array(
1567
    'bypass node access' => array(
1568
      'title' => t('Bypass content access control'),
1569
      'description' => t('View, edit and delete all content regardless of permission restrictions.'),
1570
      'restrict access' => TRUE,
1571
    ),
1572
    'administer content types' => array(
1573
      'title' => t('Administer content types'),
1574
      'restrict access' => TRUE,
1575
    ),
1576
    'administer nodes' => array(
1577
      'title' => t('Administer content'),
1578
      'restrict access' => TRUE,
1579
    ),
1580
    'access content overview' => array(
1581
      'title' => t('Access the content overview page'),
1582
      'description' => t('Get an overview of <a href="@url">all content</a>.', array('@url' => url('admin/content'))),
1583
    ),
1584
    'access content' => array(
1585
      'title' => t('View published content'),
1586
    ),
1587
    'view own unpublished content' => array(
1588
      'title' => t('View own unpublished content'),
1589
    ),
1590
    'view revisions' => array(
1591
      'title' => t('View content revisions'),
1592
    ),
1593
    'revert revisions' => array(
1594
      'title' => t('Revert content revisions'),
1595
    ),
1596
    'delete revisions' => array(
1597
      'title' => t('Delete content revisions'),
1598
    ),
1599
  );
1600

    
1601
  // Generate standard node permissions for all applicable node types.
1602
  foreach (node_permissions_get_configured_types() as $type) {
1603
    $perms += node_list_permissions($type);
1604
  }
1605

    
1606
  return $perms;
1607
}
1608

    
1609
/**
1610
 * Gathers the rankings from the hook_ranking() implementations.
1611
 *
1612
 * @param $query
1613
 *   A query object that has been extended with the Search DB Extender.
1614
 */
1615
function _node_rankings(SelectQueryExtender $query) {
1616
  if ($ranking = module_invoke_all('ranking')) {
1617
    $tables = &$query->getTables();
1618
    foreach ($ranking as $rank => $values) {
1619
      if ($node_rank = variable_get('node_rank_' . $rank, 0)) {
1620
        // If the table defined in the ranking isn't already joined, then add it.
1621
        if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
1622
          $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
1623
        }
1624
        $arguments = isset($values['arguments']) ? $values['arguments'] : array();
1625
        $query->addScore($values['score'], $arguments, $node_rank);
1626
      }
1627
    }
1628
  }
1629
}
1630

    
1631
/**
1632
 * Implements hook_search_info().
1633
 */
1634
function node_search_info() {
1635
  return array(
1636
    'title' => 'Content',
1637
    'path' => 'node',
1638
  );
1639
}
1640

    
1641
/**
1642
 * Implements hook_search_access().
1643
 */
1644
function node_search_access() {
1645
  return user_access('access content');
1646
}
1647

    
1648
/**
1649
 * Implements hook_search_reset().
1650
 */
1651
function node_search_reset() {
1652
  db_update('search_dataset')
1653
    ->fields(array('reindex' => REQUEST_TIME))
1654
    ->condition('type', 'node')
1655
    ->execute();
1656
}
1657

    
1658
/**
1659
 * Implements hook_search_status().
1660
 */
1661
function node_search_status() {
1662
  $total = db_query('SELECT COUNT(*) FROM {node}')->fetchField();
1663
  $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();
1664
  return array('remaining' => $remaining, 'total' => $total);
1665
}
1666

    
1667
/**
1668
 * Implements hook_search_admin().
1669
 */
1670
function node_search_admin() {
1671
  // Output form for defining rank factor weights.
1672
  $form['content_ranking'] = array(
1673
    '#type' => 'fieldset',
1674
    '#title' => t('Content ranking'),
1675
  );
1676
  $form['content_ranking']['#theme'] = 'node_search_admin';
1677
  $form['content_ranking']['info'] = array(
1678
    '#markup' => '<p><em>' . t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em></p>'
1679
  );
1680

    
1681
  // Note: reversed to reflect that higher number = higher ranking.
1682
  $options = drupal_map_assoc(range(0, 10));
1683
  foreach (module_invoke_all('ranking') as $var => $values) {
1684
    $form['content_ranking']['factors']['node_rank_' . $var] = array(
1685
      '#title' => $values['title'],
1686
      '#type' => 'select',
1687
      '#options' => $options,
1688
      '#default_value' => variable_get('node_rank_' . $var, 0),
1689
    );
1690
  }
1691
  return $form;
1692
}
1693

    
1694
/**
1695
 * Implements hook_search_execute().
1696
 */
1697
function node_search_execute($keys = NULL, $conditions = NULL) {
1698
  // Build matching conditions
1699
  $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
1700
  $query->join('node', 'n', 'n.nid = i.sid');
1701
  $query
1702
    ->condition('n.status', 1)
1703
    ->addTag('node_access')
1704
    ->searchExpression($keys, 'node');
1705

    
1706
  // Insert special keywords.
1707
  $query->setOption('type', 'n.type');
1708
  $query->setOption('language', 'n.language');
1709
  if ($query->setOption('term', 'ti.tid')) {
1710
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
1711
  }
1712
  // Only continue if the first pass query matches.
1713
  if (!$query->executeFirstPass()) {
1714
    return array();
1715
  }
1716

    
1717
  // Add the ranking expressions.
1718
  _node_rankings($query);
1719

    
1720
  // Load results.
1721
  $find = $query
1722
    ->limit(10)
1723
    ->execute();
1724
  $results = array();
1725
  foreach ($find as $item) {
1726
    // Render the node.
1727
    $node = node_load($item->sid);
1728
    $build = node_view($node, 'search_result');
1729
    unset($build['#theme']);
1730
    $node->rendered = drupal_render($build);
1731

    
1732
    // Fetch comments for snippet.
1733
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
1734

    
1735
    $extra = module_invoke_all('node_search_result', $node);
1736

    
1737
    $uri = entity_uri('node', $node);
1738
    $results[] = array(
1739
      'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
1740
      'type' => check_plain(node_type_get_name($node)),
1741
      'title' => $node->title,
1742
      'user' => theme('username', array('account' => $node)),
1743
      'date' => $node->changed,
1744
      'node' => $node,
1745
      'extra' => $extra,
1746
      'score' => $item->calculated_score,
1747
      'snippet' => search_excerpt($keys, $node->rendered),
1748
      'language' => entity_language('node', $node),
1749
    );
1750
  }
1751
  return $results;
1752
}
1753

    
1754
/**
1755
 * Implements hook_ranking().
1756
 */
1757
function node_ranking() {
1758
  // Create the ranking array and add the basic ranking options.
1759
  $ranking = array(
1760
    'relevance' => array(
1761
      'title' => t('Keyword relevance'),
1762
      // Average relevance values hover around 0.15
1763
      'score' => 'i.relevance',
1764
    ),
1765
    'sticky' => array(
1766
      'title' => t('Content is sticky at top of lists'),
1767
      // The sticky flag is either 0 or 1, which is automatically normalized.
1768
      'score' => 'n.sticky',
1769
    ),
1770
    'promote' => array(
1771
      'title' => t('Content is promoted to the front page'),
1772
      // The promote flag is either 0 or 1, which is automatically normalized.
1773
      'score' => 'n.promote',
1774
    ),
1775
  );
1776

    
1777
  // Add relevance based on creation or changed date.
1778
  if ($node_cron_last = variable_get('node_cron_last', 0)) {
1779
    $ranking['recent'] = array(
1780
      'title' => t('Recently posted'),
1781
      // Exponential decay with half-life of 6 months, starting at last indexed node
1782
      'score' => 'POW(2.0, (GREATEST(n.created, n.changed) - :node_cron_last) * 6.43e-8)',
1783
      'arguments' => array(':node_cron_last' => $node_cron_last),
1784
    );
1785
  }
1786
  return $ranking;
1787
}
1788

    
1789
/**
1790
 * Implements hook_user_cancel().
1791
 */
1792
function node_user_cancel($edit, $account, $method) {
1793
  switch ($method) {
1794
    case 'user_cancel_block_unpublish':
1795
      // Unpublish nodes (current revisions).
1796
      module_load_include('inc', 'node', 'node.admin');
1797
      $nodes = db_select('node', 'n')
1798
        ->fields('n', array('nid'))
1799
        ->condition('uid', $account->uid)
1800
        ->execute()
1801
        ->fetchCol();
1802
      node_mass_update($nodes, array('status' => 0));
1803
      break;
1804

    
1805
    case 'user_cancel_reassign':
1806
      // Anonymize nodes (current revisions).
1807
      module_load_include('inc', 'node', 'node.admin');
1808
      $nodes = db_select('node', 'n')
1809
        ->fields('n', array('nid'))
1810
        ->condition('uid', $account->uid)
1811
        ->execute()
1812
        ->fetchCol();
1813
      node_mass_update($nodes, array('uid' => 0));
1814
      // Anonymize old revisions.
1815
      db_update('node_revision')
1816
        ->fields(array('uid' => 0))
1817
        ->condition('uid', $account->uid)
1818
        ->execute();
1819
      // Clean history.
1820
      db_delete('history')
1821
        ->condition('uid', $account->uid)
1822
        ->execute();
1823
      break;
1824
  }
1825
}
1826

    
1827
/**
1828
 * Implements hook_user_delete().
1829
 */
1830
function node_user_delete($account) {
1831
  // Delete nodes (current revisions).
1832
  // @todo Introduce node_mass_delete() or make node_mass_update() more flexible.
1833
  $nodes = db_select('node', 'n')
1834
    ->fields('n', array('nid'))
1835
    ->condition('uid', $account->uid)
1836
    ->execute()
1837
    ->fetchCol();
1838
  node_delete_multiple($nodes);
1839
  // Delete old revisions.
1840
  $revisions = db_query('SELECT vid FROM {node_revision} WHERE uid = :uid', array(':uid' => $account->uid))->fetchCol();
1841
  foreach ($revisions as $revision) {
1842
    node_revision_delete($revision);
1843
  }
1844
  // Clean history.
1845
  db_delete('history')
1846
    ->condition('uid', $account->uid)
1847
    ->execute();
1848
}
1849

    
1850
/**
1851
 * Returns HTML for the content ranking part of the search settings admin page.
1852
 *
1853
 * @param $variables
1854
 *   An associative array containing:
1855
 *   - form: A render element representing the form.
1856
 *
1857
 * @see node_search_admin()
1858
 * @ingroup themeable
1859
 */
1860
function theme_node_search_admin($variables) {
1861
  $form = $variables['form'];
1862

    
1863
  $output = drupal_render($form['info']);
1864

    
1865
  $header = array(t('Factor'), t('Influence'));
1866
  foreach (element_children($form['factors']) as $key) {
1867
    $row = array();
1868
    $row[] = $form['factors'][$key]['#title'];
1869
    $form['factors'][$key]['#title_display'] = 'invisible';
1870
    $row[] = drupal_render($form['factors'][$key]);
1871
    $rows[] = $row;
1872
  }
1873
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
1874

    
1875
  $output .= drupal_render_children($form);
1876
  return $output;
1877
}
1878

    
1879
/**
1880
 * Access callback: Checks node revision access.
1881
 *
1882
 * @param $node
1883
 *   The node to check.
1884
 * @param $op
1885
 *   (optional) The specific operation being checked. Defaults to 'view.'
1886
 * @param object $account
1887
 *   (optional) A user object representing the user for whom the operation is
1888
 *   to be performed. Determines access for a user other than the current user.
1889
 *
1890
 * @return
1891
 *   TRUE if the operation may be performed, FALSE otherwise.
1892
 *
1893
 * @see node_menu()
1894
 */
1895
function _node_revision_access($node, $op = 'view', $account = NULL) {
1896
  $access = &drupal_static(__FUNCTION__, array());
1897

    
1898
  $map = array(
1899
    'view' => 'view revisions',
1900
    'update' => 'revert revisions',
1901
    'delete' => 'delete revisions',
1902
  );
1903

    
1904
  if (!$node || !isset($map[$op])) {
1905
    // If there was no node to check against, or the $op was not one of the
1906
    // supported ones, we return access denied.
1907
    return FALSE;
1908
  }
1909

    
1910
  if (!isset($account)) {
1911
    $account = $GLOBALS['user'];
1912
  }
1913

    
1914
  // Statically cache access by revision ID, user account ID, and operation.
1915
  $cid = $node->vid . ':' . $account->uid . ':' . $op;
1916

    
1917
  if (!isset($access[$cid])) {
1918
    // Perform basic permission checks first.
1919
    if (!user_access($map[$op], $account) && !user_access('administer nodes', $account)) {
1920
      return $access[$cid] = FALSE;
1921
    }
1922

    
1923
    $node_current_revision = node_load($node->nid);
1924
    $is_current_revision = $node_current_revision->vid == $node->vid;
1925

    
1926
    // There should be at least two revisions. If the vid of the given node and
1927
    // the vid of the current revision differ, then we already have two
1928
    // different revisions so there is no need for a separate database check.
1929
    // Also, if you try to revert to or delete the current revision, that's not
1930
    // good.
1931
    if ($is_current_revision && (db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid', array(':nid' => $node->nid))->fetchField() == 1 || $op == 'update' || $op == 'delete')) {
1932
      $access[$cid] = FALSE;
1933
    }
1934
    elseif (user_access('administer nodes', $account)) {
1935
      $access[$cid] = TRUE;
1936
    }
1937
    else {
1938
      // First check the access to the current revision and finally, if the node
1939
      // passed in is not the current revision then access to that, too.
1940
      $access[$cid] = node_access($op, $node_current_revision, $account) && ($is_current_revision || node_access($op, $node, $account));
1941
    }
1942
  }
1943

    
1944
  return $access[$cid];
1945
}
1946

    
1947
/**
1948
 * Access callback: Checks whether the user has permission to add a node.
1949
 *
1950
 * @return
1951
 *   TRUE if the user has add permission, otherwise FALSE.
1952
 *
1953
 * @see node_menu()
1954
 */
1955
function _node_add_access() {
1956
  $types = node_type_get_types();
1957
  foreach ($types as $type) {
1958
    if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
1959
      return TRUE;
1960
    }
1961
  }
1962
  if (user_access('administer content types')) {
1963
    // There are no content types defined that the user has permission to create,
1964
    // but the user does have the permission to administer the content types, so
1965
    // grant them access to the page anyway.
1966
    return TRUE;
1967
  }
1968
  return FALSE;
1969
}
1970

    
1971
/**
1972
 * Implements hook_menu().
1973
 */
1974
function node_menu() {
1975
  $items['admin/content'] = array(
1976
    'title' => 'Content',
1977
    'description' => 'Find and manage content.',
1978
    'page callback' => 'drupal_get_form',
1979
    'page arguments' => array('node_admin_content'),
1980
    'access arguments' => array('access content overview'),
1981
    'weight' => -10,
1982
    'file' => 'node.admin.inc',
1983
  );
1984
  $items['admin/content/node'] = array(
1985
    'title' => 'Content',
1986
    'type' => MENU_DEFAULT_LOCAL_TASK,
1987
    'weight' => -10,
1988
  );
1989

    
1990
  $items['admin/reports/status/rebuild'] = array(
1991
    'title' => 'Rebuild permissions',
1992
    'page callback' => 'drupal_get_form',
1993
    'page arguments' => array('node_configure_rebuild_confirm'),
1994
    // Any user than can potentially trigger a node_access_needs_rebuild(TRUE)
1995
    // has to be allowed access to the 'node access rebuild' confirm form.
1996
    'access arguments' => array('access administration pages'),
1997
    'type' => MENU_CALLBACK,
1998
    'file' => 'node.admin.inc',
1999
  );
2000

    
2001
  $items['admin/structure/types'] = array(
2002
    'title' => 'Content types',
2003
    'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
2004
    'page callback' => 'node_overview_types',
2005
    'access arguments' => array('administer content types'),
2006
    'file' => 'content_types.inc',
2007
  );
2008
  $items['admin/structure/types/list'] = array(
2009
    'title' => 'List',
2010
    'type' => MENU_DEFAULT_LOCAL_TASK,
2011
    'weight' => -10,
2012
  );
2013
  $items['admin/structure/types/add'] = array(
2014
    'title' => 'Add content type',
2015
    'page callback' => 'drupal_get_form',
2016
    'page arguments' => array('node_type_form'),
2017
    'access arguments' => array('administer content types'),
2018
    'type' => MENU_LOCAL_ACTION,
2019
    'file' => 'content_types.inc',
2020
  );
2021
  $items['admin/structure/types/manage/%node_type'] = array(
2022
    'title' => 'Edit content type',
2023
    'title callback' => 'node_type_page_title',
2024
    'title arguments' => array(4),
2025
    'page callback' => 'drupal_get_form',
2026
    'page arguments' => array('node_type_form', 4),
2027
    'access arguments' => array('administer content types'),
2028
    'file' => 'content_types.inc',
2029
  );
2030
  $items['admin/structure/types/manage/%node_type/edit'] = array(
2031
    'title' => 'Edit',
2032
    'type' => MENU_DEFAULT_LOCAL_TASK,
2033
  );
2034
  $items['admin/structure/types/manage/%node_type/delete'] = array(
2035
    'title' => 'Delete',
2036
    'page arguments' => array('node_type_delete_confirm', 4),
2037
    'access arguments' => array('administer content types'),
2038
    'file' => 'content_types.inc',
2039
  );
2040

    
2041
  $items['node'] = array(
2042
    'page callback' => 'node_page_default',
2043
    'access arguments' => array('access content'),
2044
    'menu_name' => 'navigation',
2045
    'type' => MENU_CALLBACK,
2046
  );
2047
  $items['node/add'] = array(
2048
    'title' => 'Add content',
2049
    'page callback' => 'node_add_page',
2050
    'access callback' => '_node_add_access',
2051
    'file' => 'node.pages.inc',
2052
  );
2053
  $items['rss.xml'] = array(
2054
    'title' => 'RSS feed',
2055
    'page callback' => 'node_feed',
2056
    'access arguments' => array('access content'),
2057
    'type' => MENU_CALLBACK,
2058
    // Pass a FALSE and array argument to ensure that additional path components
2059
    // are not passed to node_feed().
2060
    'page arguments' => array(FALSE, array()),
2061
  );
2062
  // @todo Remove this loop when we have a 'description callback' property.
2063
  // Reset internal static cache of _node_types_build(), forces to rebuild the
2064
  // node type information.
2065
  node_type_cache_reset();
2066
  foreach (node_type_get_types() as $type) {
2067
    $type_url_str = str_replace('_', '-', $type->type);
2068
    $items['node/add/' . $type_url_str] = array(
2069
      'title' => $type->name,
2070
      'title callback' => 'check_plain',
2071
      'page callback' => 'node_add',
2072
      'page arguments' => array($type->type),
2073
      'access callback' => 'node_access',
2074
      'access arguments' => array('create', $type->type),
2075
      'description' => $type->description,
2076
      'file' => 'node.pages.inc',
2077
    );
2078
  }
2079
  $items['node/%node'] = array(
2080
    'title callback' => 'node_page_title',
2081
    'title arguments' => array(1),
2082
    // The page callback also invokes drupal_set_title() in case
2083
    // the menu router's title is overridden by a menu link.
2084
    'page callback' => 'node_page_view',
2085
    'page arguments' => array(1),
2086
    'access callback' => 'node_access',
2087
    'access arguments' => array('view', 1),
2088
  );
2089
  $items['node/%node/view'] = array(
2090
    'title' => 'View',
2091
    'type' => MENU_DEFAULT_LOCAL_TASK,
2092
    'weight' => -10,
2093
  );
2094
  $items['node/%node/edit'] = array(
2095
    'title' => 'Edit',
2096
    'page callback' => 'node_page_edit',
2097
    'page arguments' => array(1),
2098
    'access callback' => 'node_access',
2099
    'access arguments' => array('update', 1),
2100
    'weight' => 0,
2101
    'type' => MENU_LOCAL_TASK,
2102
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
2103
    'file' => 'node.pages.inc',
2104
  );
2105
  $items['node/%node/delete'] = array(
2106
    'title' => 'Delete',
2107
    'page callback' => 'drupal_get_form',
2108
    'page arguments' => array('node_delete_confirm', 1),
2109
    'access callback' => 'node_access',
2110
    'access arguments' => array('delete', 1),
2111
    'weight' => 1,
2112
    'type' => MENU_LOCAL_TASK,
2113
    'context' => MENU_CONTEXT_INLINE,
2114
    'file' => 'node.pages.inc',
2115
  );
2116
  $items['node/%node/revisions'] = array(
2117
    'title' => 'Revisions',
2118
    'page callback' => 'node_revision_overview',
2119
    'page arguments' => array(1),
2120
    'access callback' => '_node_revision_access',
2121
    'access arguments' => array(1),
2122
    'weight' => 2,
2123
    'type' => MENU_LOCAL_TASK,
2124
    'file' => 'node.pages.inc',
2125
  );
2126
  $items['node/%node/revisions/%/view'] = array(
2127
    'title' => 'Revisions',
2128
    'load arguments' => array(3),
2129
    'page callback' => 'node_show',
2130
    'page arguments' => array(1, TRUE),
2131
    'access callback' => '_node_revision_access',
2132
    'access arguments' => array(1),
2133
  );
2134
  $items['node/%node/revisions/%/revert'] = array(
2135
    'title' => 'Revert to earlier revision',
2136
    'load arguments' => array(3),
2137
    'page callback' => 'drupal_get_form',
2138
    'page arguments' => array('node_revision_revert_confirm', 1),
2139
    'access callback' => '_node_revision_access',
2140
    'access arguments' => array(1, 'update'),
2141
    'file' => 'node.pages.inc',
2142
  );
2143
  $items['node/%node/revisions/%/delete'] = array(
2144
    'title' => 'Delete earlier revision',
2145
    'load arguments' => array(3),
2146
    'page callback' => 'drupal_get_form',
2147
    'page arguments' => array('node_revision_delete_confirm', 1),
2148
    'access callback' => '_node_revision_access',
2149
    'access arguments' => array(1, 'delete'),
2150
    'file' => 'node.pages.inc',
2151
  );
2152
  return $items;
2153
}
2154

    
2155
/**
2156
 * Implements hook_menu_local_tasks_alter().
2157
 */
2158
function node_menu_local_tasks_alter(&$data, $router_item, $root_path) {
2159
  // Add action link to 'node/add' on 'admin/content' page.
2160
  if ($root_path == 'admin/content') {
2161
    $item = menu_get_item('node/add');
2162
    if ($item['access']) {
2163
      $data['actions']['output'][] = array(
2164
        '#theme' => 'menu_local_action',
2165
        '#link' => $item,
2166
      );
2167
    }
2168
  }
2169
}
2170

    
2171
/**
2172
 * Title callback: Returns the unsanitized title of the node type edit form.
2173
 *
2174
 * @param $type
2175
 *   The node type object.
2176
 *
2177
 * @return string
2178
 *   An unsanitized string that is the title of the node type edit form.
2179
 *
2180
 * @see node_menu()
2181
 */
2182
function node_type_page_title($type) {
2183
  return $type->name;
2184
}
2185

    
2186
/**
2187
 * Title callback: Returns the title of the node.
2188
 *
2189
 * @param $node
2190
 *   The node object.
2191
 *
2192
 * @return
2193
 *   An unsanitized string that is the title of the node.
2194
 *
2195
 * @see node_menu()
2196
 */
2197
function node_page_title($node) {
2198
  return $node->title;
2199
}
2200

    
2201
/**
2202
 * Finds the last time a node was changed.
2203
 *
2204
 * @param $nid
2205
 *   The ID of a node.
2206
 *
2207
 * @return
2208
 *   A unix timestamp indicating the last time the node was changed.
2209
 */
2210
function node_last_changed($nid) {
2211
  return db_query('SELECT changed FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetch()->changed;
2212
}
2213

    
2214
/**
2215
 * Returns a list of all the existing revision numbers.
2216
 *
2217
 * @param $node
2218
 *   The node object.
2219
 *
2220
 * @return
2221
 *   An associative array keyed by node revision number.
2222
 */
2223
function node_revision_list($node) {
2224
  $revisions = array();
2225
  $result = db_query('SELECT r.vid, r.title, r.log, r.uid, n.vid AS current_vid, r.timestamp, u.name FROM {node_revision} r LEFT JOIN {node} n ON n.vid = r.vid INNER JOIN {users} u ON u.uid = r.uid WHERE r.nid = :nid ORDER BY r.vid DESC', array(':nid' => $node->nid));
2226
  foreach ($result as $revision) {
2227
    $revisions[$revision->vid] = $revision;
2228
  }
2229

    
2230
  return $revisions;
2231
}
2232

    
2233
/**
2234
 * Implements hook_block_info().
2235
 */
2236
function node_block_info() {
2237
  $blocks['syndicate']['info'] = t('Syndicate');
2238
  // Not worth caching.
2239
  $blocks['syndicate']['cache'] = DRUPAL_NO_CACHE;
2240

    
2241
  $blocks['recent']['info'] = t('Recent content');
2242
  $blocks['recent']['properties']['administrative'] = TRUE;
2243

    
2244
  return $blocks;
2245
}
2246

    
2247
/**
2248
 * Implements hook_block_view().
2249
 */
2250
function node_block_view($delta = '') {
2251
  $block = array();
2252

    
2253
  switch ($delta) {
2254
    case 'syndicate':
2255
      $block['subject'] = t('Syndicate');
2256
      $block['content'] = theme('feed_icon', array('url' => 'rss.xml', 'title' => t('Syndicate')));
2257
      break;
2258

    
2259
    case 'recent':
2260
      if (user_access('access content')) {
2261
        $block['subject'] = t('Recent content');
2262
        if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {
2263
          $block['content'] = theme('node_recent_block', array(
2264
            'nodes' => $nodes,
2265
          ));
2266
        } else {
2267
          $block['content'] = t('No content available.');
2268
        }
2269
      }
2270
      break;
2271
  }
2272
  return $block;
2273
}
2274

    
2275
/**
2276
 * Implements hook_block_configure().
2277
 */
2278
function node_block_configure($delta = '') {
2279
  $form = array();
2280
  if ($delta == 'recent') {
2281
    $form['node_recent_block_count'] = array(
2282
      '#type' => 'select',
2283
      '#title' => t('Number of recent content items to display'),
2284
      '#default_value' => variable_get('node_recent_block_count', 10),
2285
      '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30)),
2286
    );
2287
  }
2288
  return $form;
2289
}
2290

    
2291
/**
2292
 * Implements hook_block_save().
2293
 */
2294
function node_block_save($delta = '', $edit = array()) {
2295
  if ($delta == 'recent') {
2296
    variable_set('node_recent_block_count', $edit['node_recent_block_count']);
2297
  }
2298
}
2299

    
2300
/**
2301
 * Finds the most recently changed nodes that are available to the current user.
2302
 *
2303
 * @param $number
2304
 *   (optional) The maximum number of nodes to find. Defaults to 10.
2305
 *
2306
 * @return
2307
 *   An array of node entities or an empty array if there are no recent nodes
2308
 *   visible to the current user.
2309
 */
2310
function node_get_recent($number = 10) {
2311
  $query = db_select('node', 'n');
2312

    
2313
  if (!user_access('bypass node access')) {
2314
    // If the user is able to view their own unpublished nodes, allow them to
2315
    // see these in addition to published nodes. Check that they actually have
2316
    // some unpublished nodes to view before adding the condition.
2317
    if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT nid FROM {node} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => NODE_NOT_PUBLISHED))->fetchCol()) {
2318
      $query->condition(db_or()
2319
        ->condition('n.status', NODE_PUBLISHED)
2320
        ->condition('n.nid', $own_unpublished, 'IN')
2321
      );
2322
    }
2323
    else {
2324
      // If not, restrict the query to published nodes.
2325
      $query->condition('n.status', NODE_PUBLISHED);
2326
    }
2327
  }
2328
  $nids = $query
2329
    ->fields('n', array('nid'))
2330
    ->orderBy('n.changed', 'DESC')
2331
    ->range(0, $number)
2332
    ->addTag('node_access')
2333
    ->execute()
2334
    ->fetchCol();
2335

    
2336
  $nodes = node_load_multiple($nids);
2337

    
2338
  return $nodes ? $nodes : array();
2339
}
2340

    
2341
/**
2342
 * Returns HTML for a list of recent content.
2343
 *
2344
 * @param $variables
2345
 *   An associative array containing:
2346
 *   - nodes: An array of recent node objects.
2347
 *
2348
 * @ingroup themeable
2349
 */
2350
function theme_node_recent_block($variables) {
2351
  $rows = array();
2352
  $output = '';
2353

    
2354
  $l_options = array('query' => drupal_get_destination());
2355
  foreach ($variables['nodes'] as $node) {
2356
    $row = array();
2357
    $row[] = array(
2358
      'data' => theme('node_recent_content', array('node' => $node)),
2359
      'class' => 'title-author',
2360
    );
2361
    $row[] = array(
2362
      'data' => node_access('update', $node) ? l(t('edit'), 'node/' . $node->nid . '/edit', $l_options) : '',
2363
      'class' => 'edit',
2364
    );
2365
    $row[] = array(
2366
      'data' => node_access('delete', $node) ? l(t('delete'), 'node/' . $node->nid . '/delete', $l_options) : '',
2367
      'class' => 'delete',
2368
    );
2369
    $rows[] = $row;
2370
  }
2371

    
2372
  if ($rows) {
2373
    $output = theme('table', array('rows' => $rows));
2374
    if (user_access('access content overview')) {
2375
      $output .= theme('more_link', array('url' => 'admin/content', 'title' => t('Show more content')));
2376
    }
2377
  }
2378

    
2379
  return $output;
2380
}
2381

    
2382
/**
2383
 * Returns HTML for a recent node to be displayed in the recent content block.
2384
 *
2385
 * @param $variables
2386
 *   An associative array containing:
2387
 *   - node: A node object.
2388
 *
2389
 * @ingroup themeable
2390
 */
2391
function theme_node_recent_content($variables) {
2392
  $node = $variables['node'];
2393

    
2394
  $output = '<div class="node-title">';
2395
  $output .= l($node->title, 'node/' . $node->nid);
2396
  $output .= theme('mark', array('type' => node_mark($node->nid, $node->changed)));
2397
  $output .= '</div><div class="node-author">';
2398
  $output .= theme('username', array('account' => user_load($node->uid)));
2399
  $output .= '</div>';
2400

    
2401
  return $output;
2402
}
2403

    
2404
/**
2405
 * Implements hook_form_FORMID_alter().
2406
 *
2407
 * Adds node-type specific visibility options to add block form.
2408
 *
2409
 * @see block_add_block_form()
2410
 */
2411
function node_form_block_add_block_form_alter(&$form, &$form_state) {
2412
  node_form_block_admin_configure_alter($form, $form_state);
2413
}
2414

    
2415
/**
2416
 * Implements hook_form_FORMID_alter().
2417
 *
2418
 * Adds node-type specific visibility options to block configuration form.
2419
 *
2420
 * @see block_admin_configure()
2421
 */
2422
function node_form_block_admin_configure_alter(&$form, &$form_state) {
2423
  $default_type_options = db_query("SELECT type FROM {block_node_type} WHERE module = :module AND delta = :delta", array(
2424
    ':module' => $form['module']['#value'],
2425
    ':delta' => $form['delta']['#value'],
2426
  ))->fetchCol();
2427
  $form['visibility']['node_type'] = array(
2428
    '#type' => 'fieldset',
2429
    '#title' => t('Content types'),
2430
    '#collapsible' => TRUE,
2431
    '#collapsed' => TRUE,
2432
    '#group' => 'visibility',
2433
    '#weight' => 5,
2434
  );
2435
  $form['visibility']['node_type']['types'] = array(
2436
    '#type' => 'checkboxes',
2437
    '#title' => t('Show block for specific content types'),
2438
    '#default_value' => $default_type_options,
2439
    '#options' => node_type_get_names(),
2440
    '#description' => t('Show this block only on pages that display content of the given type(s). If you select no types, there will be no type-specific limitation.'),
2441
  );
2442
  $form['#submit'][] = 'node_form_block_admin_configure_submit';
2443
}
2444

    
2445
/**
2446
 * Form submission handler for node_form_block_admin_configure_alter().
2447
 *
2448
 * @see node_form_block_admin_configure_alter()
2449
 */
2450
function node_form_block_admin_configure_submit($form, &$form_state) {
2451
  db_delete('block_node_type')
2452
    ->condition('module', $form_state['values']['module'])
2453
    ->condition('delta', $form_state['values']['delta'])
2454
    ->execute();
2455
  $query = db_insert('block_node_type')->fields(array('type', 'module', 'delta'));
2456
  foreach (array_filter($form_state['values']['types']) as $type) {
2457
    $query->values(array(
2458
      'type' => $type,
2459
      'module' => $form_state['values']['module'],
2460
      'delta' => $form_state['values']['delta'],
2461
    ));
2462
  }
2463
  $query->execute();
2464
}
2465

    
2466
/**
2467
 * Implements hook_form_FORMID_alter().
2468
 *
2469
 * Adds node specific submit handler to delete custom block form.
2470
 *
2471
 * @see block_custom_block_delete()
2472
 */
2473
function node_form_block_custom_block_delete_alter(&$form, &$form_state) {
2474
  $form['#submit'][] = 'node_form_block_custom_block_delete_submit';
2475
}
2476

    
2477
/**
2478
 * Form submission handler for node_form_block_custom_block_delete_alter().
2479
 *
2480
 * @see node_form_block_custom_block_delete_alter()
2481
 */
2482
function node_form_block_custom_block_delete_submit($form, &$form_state) {
2483
  db_delete('block_node_type')
2484
    ->condition('module', 'block')
2485
    ->condition('delta', $form_state['values']['bid'])
2486
    ->execute();
2487
}
2488

    
2489
/**
2490
 * Implements hook_modules_uninstalled().
2491
 *
2492
 * Cleanup {block_node_type} table from modules' blocks.
2493
 */
2494
function node_modules_uninstalled($modules) {
2495
  db_delete('block_node_type')
2496
    ->condition('module', $modules, 'IN')
2497
    ->execute();
2498
}
2499

    
2500
/**
2501
 * Implements hook_block_list_alter().
2502
 *
2503
 * Check the content type specific visibilty settings. Remove the block if the
2504
 * visibility conditions are not met.
2505
 */
2506
function node_block_list_alter(&$blocks) {
2507
  global $theme_key;
2508

    
2509
  // Build an array of node types for each block.
2510
  $block_node_types = array();
2511
  $result = db_query('SELECT module, delta, type FROM {block_node_type}');
2512
  foreach ($result as $record) {
2513
    $block_node_types[$record->module][$record->delta][$record->type] = TRUE;
2514
  }
2515

    
2516
  $node = menu_get_object();
2517
  $node_types = node_type_get_types();
2518
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2)) {
2519
    $node_add_arg = strtr(arg(2), '-', '_');
2520
  }
2521
  foreach ($blocks as $key => $block) {
2522
    if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
2523
      // This block was added by a contrib module, leave it in the list.
2524
      continue;
2525
    }
2526

    
2527
    // If a block has no node types associated, it is displayed for every type.
2528
    // For blocks with node types associated, if the node type does not match
2529
    // the settings from this block, remove it from the block list.
2530
    if (isset($block_node_types[$block->module][$block->delta])) {
2531
      if (!empty($node)) {
2532
        // This is a node or node edit page.
2533
        if (!isset($block_node_types[$block->module][$block->delta][$node->type])) {
2534
          // This block should not be displayed for this node type.
2535
          unset($blocks[$key]);
2536
          continue;
2537
        }
2538
      }
2539
      elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {
2540
        // This is a node creation page
2541
        if (!isset($block_node_types[$block->module][$block->delta][$node_add_arg])) {
2542
          // This block should not be displayed for this node type.
2543
          unset($blocks[$key]);
2544
          continue;
2545
        }
2546
      }
2547
      else {
2548
        // This is not a node page, remove the block.
2549
        unset($blocks[$key]);
2550
        continue;
2551
      }
2552
    }
2553
  }
2554
}
2555

    
2556
/**
2557
 * Generates and prints an RSS feed.
2558
 *
2559
 * Generates an RSS feed from an array of node IDs, and prints it with an HTTP
2560
 * header, with Content Type set to RSS/XML.
2561
 *
2562
 * @param $nids
2563
 *   An array of node IDs (nid). Defaults to FALSE so empty feeds can be
2564
 *   generated with passing an empty array, if no items are to be added
2565
 *   to the feed.
2566
 * @param $channel
2567
 *   An associative array containing title, link, description and other keys,
2568
 *   to be parsed by format_rss_channel() and format_xml_elements().
2569
 *   A list of channel elements can be found at the
2570
 *   @link http://cyber.law.harvard.edu/rss/rss.html RSS 2.0 Specification. @endlink
2571
 *   The link should be an absolute URL.
2572
 */
2573
function node_feed($nids = FALSE, $channel = array()) {
2574
  global $base_url, $language_content;
2575

    
2576
  if ($nids === FALSE) {
2577
    $nids = db_select('node', 'n')
2578
      ->fields('n', array('nid', 'created'))
2579
      ->condition('n.promote', 1)
2580
      ->condition('n.status', 1)
2581
      ->orderBy('n.created', 'DESC')
2582
      ->range(0, variable_get('feed_default_items', 10))
2583
      ->addTag('node_access')
2584
      ->execute()
2585
      ->fetchCol();
2586
  }
2587

    
2588
  $item_length = variable_get('feed_item_length', 'fulltext');
2589
  $namespaces = array('xmlns:dc' => 'http://purl.org/dc/elements/1.1/');
2590

    
2591
  // Load all nodes to be rendered.
2592
  $nodes = node_load_multiple($nids);
2593
  $items = '';
2594
  foreach ($nodes as $node) {
2595
    $item_text = '';
2596

    
2597
    $node->link = url("node/$node->nid", array('absolute' => TRUE));
2598
    $node->rss_namespaces = array();
2599
    $account = user_load($node->uid);
2600
    $node->rss_elements = array(
2601
      array('key' => 'pubDate', 'value' => gmdate('r', $node->created)),
2602
      array('key' => 'dc:creator', 'value' => format_username($account)),
2603
      array('key' => 'guid', 'value' => $node->nid . ' at ' . $base_url, 'attributes' => array('isPermaLink' => 'false'))
2604
    );
2605

    
2606
    // The node gets built and modules add to or modify $node->rss_elements
2607
    // and $node->rss_namespaces.
2608
    $build = node_view($node, 'rss');
2609
    unset($build['#theme']);
2610

    
2611
    if (!empty($node->rss_namespaces)) {
2612
      $namespaces = array_merge($namespaces, $node->rss_namespaces);
2613
    }
2614

    
2615
    if ($item_length != 'title') {
2616
      // We render node contents and force links to be last.
2617
      $build['links']['#weight'] = 1000;
2618
      $item_text .= drupal_render($build);
2619
    }
2620

    
2621
    $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements);
2622
  }
2623

    
2624
  $channel_defaults = array(
2625
    'version'     => '2.0',
2626
    'title'       => variable_get('site_name', 'Drupal'),
2627
    'link'        => $base_url,
2628
    'description' => variable_get('feed_description', ''),
2629
    'language'    => $language_content->language
2630
  );
2631
  $channel_extras = array_diff_key($channel, $channel_defaults);
2632
  $channel = array_merge($channel_defaults, $channel);
2633

    
2634
  $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
2635
  $output .= "<rss version=\"" . $channel["version"] . "\" xml:base=\"" . $base_url . "\" " . drupal_attributes($namespaces) . ">\n";
2636
  $output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language'], $channel_extras);
2637
  $output .= "</rss>\n";
2638

    
2639
  drupal_add_http_header('Content-Type', 'application/rss+xml; charset=utf-8');
2640
  print $output;
2641
}
2642

    
2643
/**
2644
 * Constructs a drupal_render() style array from an array of loaded nodes.
2645
 *
2646
 * @param $nodes
2647
 *   An array of nodes as returned by node_load_multiple().
2648
 * @param $view_mode
2649
 *   View mode, e.g. 'full', 'teaser'...
2650
 * @param $weight
2651
 *   An integer representing the weight of the first node in the list.
2652
 * @param $langcode
2653
 *   (optional) A language code to use for rendering. Defaults to NULL which is
2654
 *   the global content language of the current request.
2655
 *
2656
 * @return
2657
 *   An array in the format expected by drupal_render().
2658
 */
2659
function node_view_multiple($nodes, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
2660
  $build = array();
2661
  $entities_by_view_mode = entity_view_mode_prepare('node', $nodes, $view_mode, $langcode);
2662
  foreach ($entities_by_view_mode as $entity_view_mode => $entities) {
2663
    field_attach_prepare_view('node', $entities, $entity_view_mode, $langcode);
2664
    entity_prepare_view('node', $entities, $langcode);
2665

    
2666
    foreach ($entities as $entity) {
2667
      $build['nodes'][$entity->nid] = node_view($entity, $entity_view_mode, $langcode);
2668
    }
2669
  }
2670

    
2671
  foreach ($nodes as $node) {
2672
    $build['nodes'][$node->nid]['#weight'] = $weight;
2673
    $weight++;
2674
  }
2675
  // Sort here, to preserve the input order of the entities that were passed to
2676
  // this function.
2677
  uasort($build['nodes'], 'element_sort');
2678
  $build['nodes']['#sorted'] = TRUE;
2679

    
2680
  return $build;
2681
}
2682

    
2683
/**
2684
 * Menu callback: Generates a listing of promoted nodes.
2685
 *
2686
 * @return array
2687
 *   An array in the format expected by drupal_render().
2688
 *
2689
 * @see node_menu()
2690
 */
2691
function node_page_default() {
2692
  $select = db_select('node', 'n')
2693
    ->fields('n', array('nid', 'sticky', 'created'))
2694
    ->condition('n.promote', 1)
2695
    ->condition('n.status', 1)
2696
    ->orderBy('n.sticky', 'DESC')
2697
    ->orderBy('n.created', 'DESC')
2698
    ->extend('PagerDefault')
2699
    ->limit(variable_get('default_nodes_main', 10))
2700
    ->addTag('node_access');
2701

    
2702
  $nids = $select->execute()->fetchCol();
2703

    
2704
  if (!empty($nids)) {
2705
    $nodes = node_load_multiple($nids);
2706
    $build = node_view_multiple($nodes);
2707

    
2708
    // 'rss.xml' is a path, not a file, registered in node_menu().
2709
    drupal_add_feed('rss.xml', variable_get('site_name', 'Drupal') . ' ' . t('RSS'));
2710
    $build['pager'] = array(
2711
      '#theme' => 'pager',
2712
      '#weight' => 5,
2713
    );
2714
    drupal_set_title('');
2715
  }
2716
  else {
2717
    drupal_set_title(t('Welcome to @site-name', array('@site-name' => variable_get('site_name', 'Drupal'))), PASS_THROUGH);
2718

    
2719
    $default_message = '<p>' . t('No front page content has been created yet.') . '</p>';
2720

    
2721
    $default_links = array();
2722
    if (_node_add_access()) {
2723
      $default_links[] = l(t('Add new content'), 'node/add');
2724
    }
2725
    if (!empty($default_links)) {
2726
      $default_message .= theme('item_list', array('items' => $default_links));
2727
    }
2728

    
2729
    $build['default_message'] = array(
2730
      '#markup' => $default_message,
2731
      '#prefix' => '<div id="first-time">',
2732
      '#suffix' => '</div>',
2733
    );
2734
  }
2735
  return $build;
2736
}
2737

    
2738
/**
2739
 * Menu callback: Displays a single node.
2740
 *
2741
 * @param $node
2742
 *   The node object.
2743
 *
2744
 * @return
2745
 *   A page array suitable for use by drupal_render().
2746
 *
2747
 * @see node_menu()
2748
 */
2749
function node_page_view($node) {
2750
  // If there is a menu link to this node, the link becomes the last part
2751
  // of the active trail, and the link name becomes the page title.
2752
  // Thus, we must explicitly set the page title to be the node title.
2753
  drupal_set_title($node->title);
2754
  $uri = entity_uri('node', $node);
2755
  // Set the node path as the canonical URL to prevent duplicate content.
2756
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
2757
  // Set the non-aliased path as a default shortlink.
2758
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
2759
  return node_show($node);
2760
}
2761

    
2762
/**
2763
 * Implements hook_update_index().
2764
 */
2765
function node_update_index() {
2766
  $limit = (int)variable_get('search_cron_limit', 100);
2767

    
2768
  $result = db_query_range("SELECT n.nid 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 ORDER BY d.reindex ASC, n.nid ASC", 0, $limit, array(), array('target' => 'slave'));
2769

    
2770
  foreach ($result as $node) {
2771
    _node_index_node($node);
2772
  }
2773
}
2774

    
2775
/**
2776
 * Indexes a single node.
2777
 *
2778
 * @param $node
2779
 *   The node to index.
2780
 */
2781
function _node_index_node($node) {
2782
  $node = node_load($node->nid);
2783

    
2784
  // Save the changed time of the most recent indexed node, for the search
2785
  // results half-life calculation.
2786
  variable_set('node_cron_last', $node->changed);
2787

    
2788
  // Render the node.
2789
  $build = node_view($node, 'search_index');
2790
  unset($build['#theme']);
2791
  $node->rendered = drupal_render($build);
2792

    
2793
  $text = '<h1>' . check_plain($node->title) . '</h1>' . $node->rendered;
2794

    
2795
  // Fetch extra data normally not visible
2796
  $extra = module_invoke_all('node_update_index', $node);
2797
  foreach ($extra as $t) {
2798
    $text .= $t;
2799
  }
2800

    
2801
  // Update index
2802
  search_index($node->nid, 'node', $text);
2803
}
2804

    
2805
/**
2806
 * Implements hook_form_FORM_ID_alter().
2807
 */
2808
function node_form_search_form_alter(&$form, $form_state) {
2809
  if (isset($form['module']) && $form['module']['#value'] == 'node' && user_access('use advanced search')) {
2810
    // Keyword boxes:
2811
    $form['advanced'] = array(
2812
      '#type' => 'fieldset',
2813
      '#title' => t('Advanced search'),
2814
      '#collapsible' => TRUE,
2815
      '#collapsed' => TRUE,
2816
      '#attributes' => array('class' => array('search-advanced')),
2817
    );
2818
    $form['advanced']['keywords'] = array(
2819
      '#prefix' => '<div class="criterion">',
2820
      '#suffix' => '</div>',
2821
    );
2822
    $form['advanced']['keywords']['or'] = array(
2823
      '#type' => 'textfield',
2824
      '#title' => t('Containing any of the words'),
2825
      '#size' => 30,
2826
      '#maxlength' => 255,
2827
    );
2828
    $form['advanced']['keywords']['phrase'] = array(
2829
      '#type' => 'textfield',
2830
      '#title' => t('Containing the phrase'),
2831
      '#size' => 30,
2832
      '#maxlength' => 255,
2833
    );
2834
    $form['advanced']['keywords']['negative'] = array(
2835
      '#type' => 'textfield',
2836
      '#title' => t('Containing none of the words'),
2837
      '#size' => 30,
2838
      '#maxlength' => 255,
2839
    );
2840

    
2841
    // Node types:
2842
    $types = array_map('check_plain', node_type_get_names());
2843
    $form['advanced']['type'] = array(
2844
      '#type' => 'checkboxes',
2845
      '#title' => t('Only of the type(s)'),
2846
      '#prefix' => '<div class="criterion">',
2847
      '#suffix' => '</div>',
2848
      '#options' => $types,
2849
    );
2850
    $form['advanced']['submit'] = array(
2851
      '#type' => 'submit',
2852
      '#value' => t('Advanced search'),
2853
      '#prefix' => '<div class="action">',
2854
      '#suffix' => '</div>',
2855
      '#weight' => 100,
2856
    );
2857

    
2858
    // Languages:
2859
    $language_options = array();
2860
    foreach (language_list('language') as $key => $entity) {
2861
      if ($entity->enabled) {
2862
        $language_options[$key] = $entity->name;
2863
      }
2864
    }
2865
    if (count($language_options) > 1) {
2866
      $form['advanced']['language'] = array(
2867
        '#type' => 'checkboxes',
2868
        '#title' => t('Languages'),
2869
        '#prefix' => '<div class="criterion">',
2870
        '#suffix' => '</div>',
2871
        '#options' => $language_options,
2872
      );
2873
    }
2874

    
2875
    $form['#validate'][] = 'node_search_validate';
2876
  }
2877
}
2878

    
2879
/**
2880
 * Form validation handler for node_form_alter().
2881
 */
2882
function node_search_validate($form, &$form_state) {
2883
  // Initialize using any existing basic search keywords.
2884
  $keys = $form_state['values']['processed_keys'];
2885

    
2886
  // Insert extra restrictions into the search keywords string.
2887
  if (isset($form_state['values']['type']) && is_array($form_state['values']['type'])) {
2888
    // Retrieve selected types - Form API sets the value of unselected
2889
    // checkboxes to 0.
2890
    $form_state['values']['type'] = array_filter($form_state['values']['type']);
2891
    if (count($form_state['values']['type'])) {
2892
      $keys = search_expression_insert($keys, 'type', implode(',', array_keys($form_state['values']['type'])));
2893
    }
2894
  }
2895

    
2896
  if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
2897
    $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
2898
  }
2899
  if (isset($form_state['values']['language']) && is_array($form_state['values']['language'])) {
2900
    $languages = array_filter($form_state['values']['language']);
2901
    if (count($languages)) {
2902
      $keys = search_expression_insert($keys, 'language', implode(',', $languages));
2903
    }
2904
  }
2905
  if ($form_state['values']['or'] != '') {
2906
    if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['or'], $matches)) {
2907
      $keys .= ' ' . implode(' OR ', $matches[1]);
2908
    }
2909
  }
2910
  if ($form_state['values']['negative'] != '') {
2911
    if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state['values']['negative'], $matches)) {
2912
      $keys .= ' -' . implode(' -', $matches[1]);
2913
    }
2914
  }
2915
  if ($form_state['values']['phrase'] != '') {
2916
    $keys .= ' "' . str_replace('"', ' ', $form_state['values']['phrase']) . '"';
2917
  }
2918
  if (!empty($keys)) {
2919
    form_set_value($form['basic']['processed_keys'], trim($keys), $form_state);
2920
  }
2921
}
2922

    
2923
/**
2924
 * @defgroup node_access Node access rights
2925
 * @{
2926
 * The node access system determines who can do what to which nodes.
2927
 *
2928
 * In determining access rights for a node, node_access() first checks whether
2929
 * the user has the "bypass node access" permission. Such users have
2930
 * unrestricted access to all nodes. user 1 will always pass this check.
2931
 *
2932
 * Next, all implementations of hook_node_access() will be called. Each
2933
 * implementation may explicitly allow, explicitly deny, or ignore the access
2934
 * request. If at least one module says to deny the request, it will be rejected.
2935
 * If no modules deny the request and at least one says to allow it, the request
2936
 * will be permitted.
2937
 *
2938
 * If all modules ignore the access request, then the node_access table is used
2939
 * to determine access. All node access modules are queried using
2940
 * hook_node_grants() to assemble a list of "grant IDs" for the user. This list
2941
 * is compared against the table. If any row contains the node ID in question
2942
 * (or 0, which stands for "all nodes"), one of the grant IDs returned, and a
2943
 * value of TRUE for the operation in question, then access is granted. Note
2944
 * that this table is a list of grants; any matching row is sufficient to
2945
 * grant access to the node.
2946
 *
2947
 * In node listings (lists of nodes generated from a select query, such as the
2948
 * default home page at path 'node', an RSS feed, a recent content block, etc.),
2949
 * the process above is followed except that hook_node_access() is not called on
2950
 * each node for performance reasons and for proper functioning of the pager
2951
 * system. When adding a node listing to your module, be sure to use a dynamic
2952
 * query created by db_select() and add a tag of "node_access". This will allow
2953
 * modules dealing with node access to ensure only nodes to which the user has
2954
 * access are retrieved, through the use of hook_query_TAG_alter().
2955
 *
2956
 * Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
2957
 * will block access to the node. Therefore, implementers should take care to
2958
 * not deny access unless they really intend to. Unless a module wishes to
2959
 * actively deny access it should return NODE_ACCESS_IGNORE (or simply return
2960
 * nothing) to allow other modules or the node_access table to control access.
2961
 *
2962
 * To see how to write a node access module of your own, see
2963
 * node_access_example.module.
2964
 */
2965

    
2966
/**
2967
 * Determines whether the current user may perform the operation on the node.
2968
 *
2969
 * @param $op
2970
 *   The operation to be performed on the node. Possible values are:
2971
 *   - "view"
2972
 *   - "update"
2973
 *   - "delete"
2974
 *   - "create"
2975
 * @param $node
2976
 *   The node object on which the operation is to be performed, or node type
2977
 *   (e.g. 'forum') for "create" operation.
2978
 * @param $account
2979
 *   Optional, a user object representing the user for whom the operation is to
2980
 *   be performed. Determines access for a user other than the current user.
2981
 *
2982
 * @return
2983
 *   TRUE if the operation may be performed, FALSE otherwise.
2984
 */
2985
function node_access($op, $node, $account = NULL) {
2986
  $rights = &drupal_static(__FUNCTION__, array());
2987

    
2988
  if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
2989
    // If there was no node to check against, or the $op was not one of the
2990
    // supported ones, we return access denied.
2991
    return FALSE;
2992
  }
2993
  // If no user object is supplied, the access check is for the current user.
2994
  if (empty($account)) {
2995
    $account = $GLOBALS['user'];
2996
  }
2997

    
2998
  // $node may be either an object or a node type. Since node types cannot be
2999
  // an integer, use either nid or type as the static cache id.
3000

    
3001
  $cid = is_object($node) ? $node->nid : $node;
3002

    
3003
  // If we've already checked access for this node, user and op, return from
3004
  // cache.
3005
  if (isset($rights[$account->uid][$cid][$op])) {
3006
    return $rights[$account->uid][$cid][$op];
3007
  }
3008

    
3009
  if (user_access('bypass node access', $account)) {
3010
    $rights[$account->uid][$cid][$op] = TRUE;
3011
    return TRUE;
3012
  }
3013
  if (!user_access('access content', $account)) {
3014
    $rights[$account->uid][$cid][$op] = FALSE;
3015
    return FALSE;
3016
  }
3017

    
3018
  // We grant access to the node if both of the following conditions are met:
3019
  // - No modules say to deny access.
3020
  // - At least one module says to grant access.
3021
  // If no module specified either allow or deny, we fall back to the
3022
  // node_access table.
3023
  $access = module_invoke_all('node_access', $node, $op, $account);
3024
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
3025
    $rights[$account->uid][$cid][$op] = FALSE;
3026
    return FALSE;
3027
  }
3028
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
3029
    $rights[$account->uid][$cid][$op] = TRUE;
3030
    return TRUE;
3031
  }
3032

    
3033
  // Check if authors can view their own unpublished nodes.
3034
  if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
3035
    $rights[$account->uid][$cid][$op] = TRUE;
3036
    return TRUE;
3037
  }
3038

    
3039
  // If the module did not override the access rights, use those set in the
3040
  // node_access table.
3041
  if ($op != 'create' && $node->nid) {
3042
    if (module_implements('node_grants')) {
3043
      $query = db_select('node_access');
3044
      $query->addExpression('1');
3045
      $query->condition('grant_' . $op, 1, '>=');
3046
      $nids = db_or()->condition('nid', $node->nid);
3047
      if ($node->status) {
3048
        $nids->condition('nid', 0);
3049
      }
3050
      $query->condition($nids);
3051
      $query->range(0, 1);
3052

    
3053
      $grants = db_or();
3054
      foreach (node_access_grants($op, $account) as $realm => $gids) {
3055
        foreach ($gids as $gid) {
3056
          $grants->condition(db_and()
3057
            ->condition('gid', $gid)
3058
            ->condition('realm', $realm)
3059
          );
3060
        }
3061
      }
3062
      if (count($grants) > 0) {
3063
        $query->condition($grants);
3064
      }
3065
      $result =  (bool) $query
3066
        ->execute()
3067
        ->fetchField();
3068
      $rights[$account->uid][$cid][$op] = $result;
3069
      return $result;
3070
    }
3071
    elseif (is_object($node) && $op == 'view' && $node->status) {
3072
      // If no modules implement hook_node_grants(), the default behavior is to
3073
      // allow all users to view published nodes, so reflect that here.
3074
      $rights[$account->uid][$cid][$op] = TRUE;
3075
      return TRUE;
3076
    }
3077
  }
3078

    
3079
  return FALSE;
3080
}
3081

    
3082
/**
3083
 * Implements hook_node_access().
3084
 */
3085
function node_node_access($node, $op, $account) {
3086
  $type = is_string($node) ? $node : $node->type;
3087

    
3088
  if (in_array($type, node_permissions_get_configured_types())) {
3089
    if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
3090
      return NODE_ACCESS_ALLOW;
3091
    }
3092

    
3093
    if ($op == 'update') {
3094
      if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
3095
        return NODE_ACCESS_ALLOW;
3096
      }
3097
    }
3098

    
3099
    if ($op == 'delete') {
3100
      if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
3101
        return NODE_ACCESS_ALLOW;
3102
      }
3103
    }
3104
  }
3105

    
3106
  return NODE_ACCESS_IGNORE;
3107
}
3108

    
3109
/**
3110
 * Helper function to generate standard node permission list for a given type.
3111
 *
3112
 * @param $type
3113
 *   The machine-readable name of the node type.
3114
 *
3115
 * @return array
3116
 *   An array of permission names and descriptions.
3117
 */
3118
function node_list_permissions($type) {
3119
  $info = node_type_get_type($type);
3120

    
3121
  // Build standard list of node permissions for this type.
3122
  $perms = array(
3123
    "create $type content" => array(
3124
      'title' => t('%type_name: Create new content', array('%type_name' => $info->name)),
3125
    ),
3126
    "edit own $type content" => array(
3127
      'title' => t('%type_name: Edit own content', array('%type_name' => $info->name)),
3128
    ),
3129
    "edit any $type content" => array(
3130
      'title' => t('%type_name: Edit any content', array('%type_name' => $info->name)),
3131
    ),
3132
    "delete own $type content" => array(
3133
      'title' => t('%type_name: Delete own content', array('%type_name' => $info->name)),
3134
    ),
3135
    "delete any $type content" => array(
3136
      'title' => t('%type_name: Delete any content', array('%type_name' => $info->name)),
3137
    ),
3138
  );
3139

    
3140
  return $perms;
3141
}
3142

    
3143
/**
3144
 * Returns an array of node types that should be managed by permissions.
3145
 *
3146
 * By default, this will include all node types in the system. To exclude a
3147
 * specific node from getting permissions defined for it, set the
3148
 * node_permissions_$type variable to 0. Core does not provide an interface for
3149
 * doing so. However, contrib modules may exclude their own nodes in
3150
 * hook_install(). Alternatively, contrib modules may configure all node types
3151
 * at once, or decide to apply some other hook_node_access() implementation to
3152
 * some or all node types.
3153
 *
3154
 * @return
3155
 *   An array of node types managed by this module.
3156
 */
3157
function node_permissions_get_configured_types() {
3158

    
3159
  $configured_types = array();
3160

    
3161
  foreach (node_type_get_types() as $type => $info) {
3162
    if (variable_get('node_permissions_' . $type, 1)) {
3163
      $configured_types[] = $type;
3164
    }
3165
  }
3166

    
3167
  return $configured_types;
3168
}
3169

    
3170
/**
3171
 * Fetches an array of permission IDs granted to the given user ID.
3172
 *
3173
 * The implementation here provides only the universal "all" grant. A node
3174
 * access module should implement hook_node_grants() to provide a grant list for
3175
 * the user.
3176
 *
3177
 * After the default grants have been loaded, we allow modules to alter the
3178
 * grants array by reference. This hook allows for complex business logic to be
3179
 * applied when integrating multiple node access modules.
3180
 *
3181
 * @param $op
3182
 *   The operation that the user is trying to perform.
3183
 * @param $account
3184
 *   The user object for the user performing the operation. If omitted, the
3185
 *   current user is used.
3186
 *
3187
 * @return
3188
 *   An associative array in which the keys are realms, and the values are
3189
 *   arrays of grants for those realms.
3190
 */
3191
function node_access_grants($op, $account = NULL) {
3192

    
3193
  if (!isset($account)) {
3194
    $account = $GLOBALS['user'];
3195
  }
3196

    
3197
  // Fetch node access grants from other modules.
3198
  $grants = module_invoke_all('node_grants', $account, $op);
3199
  // Allow modules to alter the assigned grants.
3200
  drupal_alter('node_grants', $grants, $account, $op);
3201

    
3202
  return array_merge(array('all' => array(0)), $grants);
3203
}
3204

    
3205
/**
3206
 * Determines whether the user has a global viewing grant for all nodes.
3207
 *
3208
 * Checks to see whether any module grants global 'view' access to a user
3209
 * account; global 'view' access is encoded in the {node_access} table as a
3210
 * grant with nid=0. If no node access modules are enabled, node.module defines
3211
 * such a global 'view' access grant.
3212
 *
3213
 * This function is called when a node listing query is tagged with
3214
 * 'node_access'; when this function returns TRUE, no node access joins are
3215
 * added to the query.
3216
 *
3217
 * @param $account
3218
 *   The user object for the user whose access is being checked. If omitted,
3219
 *   the current user is used.
3220
 *
3221
 * @return
3222
 *   TRUE if 'view' access to all nodes is granted, FALSE otherwise.
3223
 *
3224
 * @see hook_node_grants()
3225
 * @see _node_query_node_access_alter()
3226
 */
3227
function node_access_view_all_nodes($account = NULL) {
3228
  global $user;
3229
  if (!$account) {
3230
    $account = $user;
3231
  }
3232

    
3233
  // Statically cache results in an array keyed by $account->uid.
3234
  $access = &drupal_static(__FUNCTION__);
3235
  if (isset($access[$account->uid])) {
3236
    return $access[$account->uid];
3237
  }
3238

    
3239
  // If no modules implement the node access system, access is always TRUE.
3240
  if (!module_implements('node_grants')) {
3241
    $access[$account->uid] = TRUE;
3242
  }
3243
  else {
3244
    $query = db_select('node_access');
3245
    $query->addExpression('COUNT(*)');
3246
    $query
3247
      ->condition('nid', 0)
3248
      ->condition('grant_view', 1, '>=');
3249

    
3250
    $grants = db_or();
3251
    foreach (node_access_grants('view', $account) as $realm => $gids) {
3252
      foreach ($gids as $gid) {
3253
        $grants->condition(db_and()
3254
          ->condition('gid', $gid)
3255
          ->condition('realm', $realm)
3256
        );
3257
      }
3258
    }
3259
    if (count($grants) > 0 ) {
3260
      $query->condition($grants);
3261
    }
3262
    $access[$account->uid] = $query
3263
      ->execute()
3264
      ->fetchField();
3265
  }
3266

    
3267
  return $access[$account->uid];
3268
}
3269

    
3270

    
3271
/**
3272
 * Implements hook_query_TAG_alter().
3273
 *
3274
 * This is the hook_query_alter() for queries tagged with 'node_access'. It adds
3275
 * node access checks for the user account given by the 'account' meta-data (or
3276
 * global $user if not provided), for an operation given by the 'op' meta-data
3277
 * (or 'view' if not provided; other possible values are 'update' and 'delete').
3278
 */
3279
function node_query_node_access_alter(QueryAlterableInterface $query) {
3280
  _node_query_node_access_alter($query, 'node');
3281
}
3282

    
3283
/**
3284
 * Implements hook_query_TAG_alter().
3285
 *
3286
 * This function implements the same functionality as
3287
 * node_query_node_access_alter() for the SQL field storage engine. Node access
3288
 * conditions are added for field values belonging to nodes only.
3289
 */
3290
function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
3291
  _node_query_node_access_alter($query, 'entity');
3292
}
3293

    
3294
/**
3295
 * Helper for node access functions.
3296
 *
3297
 * Queries tagged with 'node_access' that are not against the {node} table
3298
 * should add the base table as metadata. For example:
3299
 * @code
3300
 *   $query
3301
 *     ->addTag('node_access')
3302
 *     ->addMetaData('base_table', 'taxonomy_index');
3303
 * @endcode
3304
 * If the query is not against the {node} table, an attempt is made to guess
3305
 * the table, but is not recommended to rely on this as it is deprecated and not
3306
 * allowed in Drupal 8. It is always safer to provide the table.
3307
 *
3308
 * @param $query
3309
 *   The query to add conditions to.
3310
 * @param $type
3311
 *   Either 'node' or 'entity' depending on what sort of query it is. See
3312
 *   node_query_node_access_alter() and node_query_entity_field_access_alter()
3313
 *   for more.
3314
 */
3315
function _node_query_node_access_alter($query, $type) {
3316
  global $user;
3317

    
3318
  // Read meta-data from query, if provided.
3319
  if (!$account = $query->getMetaData('account')) {
3320
    $account = $user;
3321
  }
3322
  if (!$op = $query->getMetaData('op')) {
3323
    $op = 'view';
3324
  }
3325

    
3326
  // If $account can bypass node access, or there are no node access modules,
3327
  // or the operation is 'view' and the $account has a global view grant
3328
  // (such as a view grant for node ID 0), we don't need to alter the query.
3329
  if (user_access('bypass node access', $account)) {
3330
    return;
3331
  }
3332
  if (!count(module_implements('node_grants'))) {
3333
    return;
3334
  }
3335
  if ($op == 'view' && node_access_view_all_nodes($account)) {
3336
    return;
3337
  }
3338

    
3339
  $tables = $query->getTables();
3340
  $base_table = $query->getMetaData('base_table');
3341
  // If no base table is specified explicitly, search for one.
3342
  if (!$base_table) {
3343
    $fallback = '';
3344
    foreach ($tables as $alias => $table_info) {
3345
      if (!($table_info instanceof SelectQueryInterface)) {
3346
        $table = $table_info['table'];
3347
        // If the node table is in the query, it wins immediately.
3348
        if ($table == 'node') {
3349
          $base_table = $table;
3350
          break;
3351
        }
3352
        // Check whether the table has a foreign key to node.nid. If it does,
3353
        // do not run this check again as we found a base table and only node
3354
        // can triumph that.
3355
        if (!$base_table) {
3356
          // The schema is cached.
3357
          $schema = drupal_get_schema($table);
3358
          if (isset($schema['fields']['nid'])) {
3359
            if (isset($schema['foreign keys'])) {
3360
              foreach ($schema['foreign keys'] as $relation) {
3361
                if ($relation['table'] === 'node' && $relation['columns'] === array('nid' => 'nid')) {
3362
                  $base_table = $table;
3363
                }
3364
              }
3365
            }
3366
            else {
3367
              // At least it's a nid. A table with a field called nid is very
3368
              // very likely to be a node.nid in a node access query.
3369
              $fallback = $table;
3370
            }
3371
          }
3372
        }
3373
      }
3374
    }
3375
    // If there is nothing else, use the fallback.
3376
    if (!$base_table) {
3377
      if ($fallback) {
3378
        watchdog('security', 'Your node listing query is using @fallback as a base table in a query tagged for node access. This might not be secure and might not even work. Specify foreign keys in your schema to node.nid ', array('@fallback' => $fallback), WATCHDOG_WARNING);
3379
        $base_table = $fallback;
3380
      }
3381
      else {
3382
        throw new Exception(t('Query tagged for node access but there is no nid. Add foreign keys to node.nid in schema to fix.'));
3383
      }
3384
    }
3385
  }
3386

    
3387
  // Find all instances of the base table being joined -- could appear
3388
  // more than once in the query, and could be aliased. Join each one to
3389
  // the node_access table.
3390

    
3391
  $grants = node_access_grants($op, $account);
3392
  if ($type == 'entity') {
3393
    // The original query looked something like:
3394
    // @code
3395
    //  SELECT nid FROM sometable s
3396
    //  INNER JOIN node_access na ON na.nid = s.nid
3397
    //  WHERE ($node_access_conditions)
3398
    // @endcode
3399
    //
3400
    // Our query will look like:
3401
    // @code
3402
    //  SELECT entity_type, entity_id
3403
    //  FROM field_data_something s
3404
    //  LEFT JOIN node_access na ON s.entity_id = na.nid
3405
    //  WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
3406
    // @endcode
3407
    //
3408
    // So instead of directly adding to the query object, we need to collect
3409
    // all of the node access conditions in a separate db_and() object and
3410
    // then add it to the query at the end.
3411
    $node_conditions = db_and();
3412
  }
3413
  foreach ($tables as $nalias => $tableinfo) {
3414
    $table = $tableinfo['table'];
3415
    if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
3416
      // Set the subquery.
3417
      $subquery = db_select('node_access', 'na')
3418
       ->fields('na', array('nid'));
3419

    
3420
      $grant_conditions = db_or();
3421
      // If any grant exists for the specified user, then user has access
3422
      // to the node for the specified operation.
3423
      foreach ($grants as $realm => $gids) {
3424
        foreach ($gids as $gid) {
3425
          $grant_conditions->condition(db_and()
3426
            ->condition('na.gid', $gid)
3427
            ->condition('na.realm', $realm)
3428
          );
3429
        }
3430
      }
3431

    
3432
      // Attach conditions to the subquery for nodes.
3433
      if (count($grant_conditions->conditions())) {
3434
        $subquery->condition($grant_conditions);
3435
      }
3436
      $subquery->condition('na.grant_' . $op, 1, '>=');
3437
      $field = 'nid';
3438
      // Now handle entities.
3439
      if ($type == 'entity') {
3440
        // Set a common alias for entities.
3441
        $base_alias = $nalias;
3442
        $field = 'entity_id';
3443
      }
3444
      $subquery->where("$nalias.$field = na.nid");
3445

    
3446
      // For an entity query, attach the subquery to entity conditions.
3447
      if ($type == 'entity') {
3448
        $node_conditions->exists($subquery);
3449
      }
3450
      // Otherwise attach it to the node query itself.
3451
      else {
3452
        $query->exists($subquery);
3453
      }
3454
    }
3455
  }
3456

    
3457
  if ($type == 'entity' && count($subquery->conditions())) {
3458
    // All the node access conditions are only for field values belonging to
3459
    // nodes.
3460
    $node_conditions->condition("$base_alias.entity_type", 'node');
3461
    $or = db_or();
3462
    $or->condition($node_conditions);
3463
    // If the field value belongs to a non-node entity type then this function
3464
    // does not do anything with it.
3465
    $or->condition("$base_alias.entity_type", 'node', '<>');
3466
    // Add the compiled set of rules to the query.
3467
    $query->condition($or);
3468
  }
3469

    
3470
}
3471

    
3472
/**
3473
 * Gets the list of node access grants and writes them to the database.
3474
 *
3475
 * This function is called when a node is saved, and can also be called by
3476
 * modules if something other than a node save causes node access permissions to
3477
 * change. It collects all node access grants for the node from
3478
 * hook_node_access_records() implementations, allows these grants to be altered
3479
 * via hook_node_access_records_alter() implementations, and saves the collected
3480
 * and altered grants to the database.
3481
 *
3482
 * @param $node
3483
 *   The $node to acquire grants for.
3484
 *
3485
 * @param $delete
3486
 *   Whether to delete existing node access records before inserting new ones.
3487
 *   Defaults to TRUE.
3488
 */
3489
function node_access_acquire_grants($node, $delete = TRUE) {
3490
  $grants = module_invoke_all('node_access_records', $node);
3491
  // Let modules alter the grants.
3492
  drupal_alter('node_access_records', $grants, $node);
3493
  // If no grants are set and the node is published, then use the default grant.
3494
  if (empty($grants) && !empty($node->status)) {
3495
    $grants[] = array('realm' => 'all', 'gid' => 0, 'grant_view' => 1, 'grant_update' => 0, 'grant_delete' => 0);
3496
  }
3497
  else {
3498
    // Retain grants by highest priority.
3499
    $grant_by_priority = array();
3500
    foreach ($grants as $g) {
3501
      $grant_by_priority[intval($g['priority'])][] = $g;
3502
    }
3503
    krsort($grant_by_priority);
3504
    $grants = array_shift($grant_by_priority);
3505
  }
3506

    
3507
  node_access_write_grants($node, $grants, NULL, $delete);
3508
}
3509

    
3510
/**
3511
 * Writes a list of grants to the database, deleting any previously saved ones.
3512
 *
3513
 * If a realm is provided, it will only delete grants from that realm, but it
3514
 * will always delete a grant from the 'all' realm. Modules that utilize
3515
 * node_access() can use this function when doing mass updates due to widespread
3516
 * permission changes.
3517
 *
3518
 * Note: Don't call this function directly from a contributed module. Call
3519
 * node_access_acquire_grants() instead.
3520
 *
3521
 * @param $node
3522
 *   The node whose grants are being written.
3523
 * @param $grants
3524
 *   A list of grants to write. Each grant is an array that must contain the
3525
 *   following keys: realm, gid, grant_view, grant_update, grant_delete.
3526
 *   The realm is specified by a particular module; the gid is as well, and
3527
 *   is a module-defined id to define grant privileges. each grant_* field
3528
 *   is a boolean value.
3529
 * @param $realm
3530
 *   (optional) If provided, read/write grants for that realm only. Defaults to
3531
 *   NULL.
3532
 * @param $delete
3533
 *   (optional) If false, does not delete records. This is only for optimization
3534
 *   purposes, and assumes the caller has already performed a mass delete of
3535
 *   some form. Defaults to TRUE.
3536
 *
3537
 * @see node_access_acquire_grants()
3538
 */
3539
function node_access_write_grants($node, $grants, $realm = NULL, $delete = TRUE) {
3540
  if ($delete) {
3541
    $query = db_delete('node_access')->condition('nid', $node->nid);
3542
    if ($realm) {
3543
      $query->condition('realm', array($realm, 'all'), 'IN');
3544
    }
3545
    $query->execute();
3546
  }
3547

    
3548
  // Only perform work when node_access modules are active.
3549
  if (!empty($grants) && count(module_implements('node_grants'))) {
3550
    $query = db_insert('node_access')->fields(array('nid', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete'));
3551
    foreach ($grants as $grant) {
3552
      if ($realm && $realm != $grant['realm']) {
3553
        continue;
3554
      }
3555
      // Only write grants; denies are implicit.
3556
      if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
3557
        $grant['nid'] = $node->nid;
3558
        $query->values($grant);
3559
      }
3560
    }
3561
    $query->execute();
3562
  }
3563
}
3564

    
3565
/**
3566
 * Flags or unflags the node access grants for rebuilding.
3567
 *
3568
 * If the argument isn't specified, the current value of the flag is returned.
3569
 * When the flag is set, a message is displayed to users with 'access
3570
 * administration pages' permission, pointing to the 'rebuild' confirm form.
3571
 * This can be used as an alternative to direct node_access_rebuild calls,
3572
 * allowing administrators to decide when they want to perform the actual
3573
 * (possibly time consuming) rebuild. When unsure if the current user is an
3574
 * administrator, node_access_rebuild() should be used instead.
3575
 *
3576
 * @param $rebuild
3577
 *   (Optional) The boolean value to be written.
3578
 *
3579
 * @return
3580
 *   The current value of the flag if no value was provided for $rebuild.
3581
 *
3582
 * @see node_access_rebuild()
3583
 */
3584
function node_access_needs_rebuild($rebuild = NULL) {
3585
  if (!isset($rebuild)) {
3586
    return variable_get('node_access_needs_rebuild', FALSE);
3587
  }
3588
  elseif ($rebuild) {
3589
    variable_set('node_access_needs_rebuild', TRUE);
3590
  }
3591
  else {
3592
    variable_del('node_access_needs_rebuild');
3593
  }
3594
}
3595

    
3596
/**
3597
 * Rebuilds the node access database.
3598
 *
3599
 * This is occasionally needed by modules that make system-wide changes to
3600
 * access levels. When the rebuild is required by an admin-triggered action (e.g
3601
 * module settings form), calling node_access_needs_rebuild(TRUE) instead of
3602
 * node_access_rebuild() lets the user perform his changes and actually
3603
 * rebuild only once he is done.
3604
 *
3605
 * Note: As of Drupal 6, node access modules are not required to (and actually
3606
 * should not) call node_access_rebuild() in hook_enable/disable anymore.
3607
 *
3608
 * @see node_access_needs_rebuild()
3609
 *
3610
 * @param $batch_mode
3611
 *   Set to TRUE to process in 'batch' mode, spawning processing over several
3612
 *   HTTP requests (thus avoiding the risk of PHP timeout if the site has a
3613
 *   large number of nodes).
3614
 *   hook_update_N and any form submit handler are safe contexts to use the
3615
 *   'batch mode'. Less decidable cases (such as calls from hook_user,
3616
 *   hook_taxonomy, etc...) might consider using the non-batch mode.
3617
 */
3618
function node_access_rebuild($batch_mode = FALSE) {
3619
  db_delete('node_access')->execute();
3620
  // Only recalculate if the site is using a node_access module.
3621
  if (count(module_implements('node_grants'))) {
3622
    if ($batch_mode) {
3623
      $batch = array(
3624
        'title' => t('Rebuilding content access permissions'),
3625
        'operations' => array(
3626
          array('_node_access_rebuild_batch_operation', array()),
3627
        ),
3628
        'finished' => '_node_access_rebuild_batch_finished'
3629
      );
3630
      batch_set($batch);
3631
    }
3632
    else {
3633
      // Try to allocate enough time to rebuild node grants
3634
      drupal_set_time_limit(240);
3635

    
3636
      // Rebuild newest nodes first so that recent content becomes available quickly.
3637
      $nids = db_query("SELECT nid FROM {node} ORDER BY nid DESC")->fetchCol();
3638
      foreach ($nids as $nid) {
3639
        $node = node_load($nid, NULL, TRUE);
3640
        // To preserve database integrity, only acquire grants if the node
3641
        // loads successfully.
3642
        if (!empty($node)) {
3643
          node_access_acquire_grants($node);
3644
        }
3645
      }
3646
    }
3647
  }
3648
  else {
3649
    // Not using any node_access modules. Add the default grant.
3650
    db_insert('node_access')
3651
      ->fields(array(
3652
        'nid' => 0,
3653
        'realm' => 'all',
3654
        'gid' => 0,
3655
        'grant_view' => 1,
3656
        'grant_update' => 0,
3657
        'grant_delete' => 0,
3658
      ))
3659
      ->execute();
3660
  }
3661

    
3662
  if (!isset($batch)) {
3663
    drupal_set_message(t('Content permissions have been rebuilt.'));
3664
    node_access_needs_rebuild(FALSE);
3665
    cache_clear_all();
3666
  }
3667
}
3668

    
3669
/**
3670
 * Performs batch operation for node_access_rebuild().
3671
 *
3672
 * This is a multistep operation: we go through all nodes by packs of 20. The
3673
 * batch processing engine interrupts processing and sends progress feedback
3674
 * after 1 second execution time.
3675
 *
3676
 * @param array $context
3677
 *   An array of contextual key/value information for rebuild batch process.
3678
 */
3679
function _node_access_rebuild_batch_operation(&$context) {
3680
  if (empty($context['sandbox'])) {
3681
    // Initiate multistep processing.
3682
    $context['sandbox']['progress'] = 0;
3683
    $context['sandbox']['current_node'] = 0;
3684
    $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
3685
  }
3686

    
3687
  // Process the next 20 nodes.
3688
  $limit = 20;
3689
  $nids = db_query_range("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, array(':nid' => $context['sandbox']['current_node']))->fetchCol();
3690
  $nodes = node_load_multiple($nids, array(), TRUE);
3691
  foreach ($nodes as $nid => $node) {
3692
    // To preserve database integrity, only acquire grants if the node
3693
    // loads successfully.
3694
    if (!empty($node)) {
3695
      node_access_acquire_grants($node);
3696
    }
3697
    $context['sandbox']['progress']++;
3698
    $context['sandbox']['current_node'] = $nid;
3699
  }
3700

    
3701
  // Multistep processing : report progress.
3702
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
3703
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
3704
  }
3705
}
3706

    
3707
/**
3708
 * Performs post-processing for node_access_rebuild().
3709
 *
3710
 * @param bool $success
3711
 *   A boolean indicating whether the re-build process has completed.
3712
 * @param array $results
3713
 *   An array of results information.
3714
 * @param array $operations
3715
 *   An array of function calls (not used in this function).
3716
 */
3717
function _node_access_rebuild_batch_finished($success, $results, $operations) {
3718
  if ($success) {
3719
    drupal_set_message(t('The content access permissions have been rebuilt.'));
3720
    node_access_needs_rebuild(FALSE);
3721
  }
3722
  else {
3723
    drupal_set_message(t('The content access permissions have not been properly rebuilt.'), 'error');
3724
  }
3725
  cache_clear_all();
3726
}
3727

    
3728
/**
3729
 * @} End of "defgroup node_access".
3730
 */
3731

    
3732
/**
3733
 * @defgroup node_content Hook implementations for user-created content types
3734
 * @{
3735
 * Functions that implement hooks for user-created content types.
3736
 */
3737

    
3738
/**
3739
 * Implements hook_form().
3740
 */
3741
function node_content_form($node, $form_state) {
3742
  // It is impossible to define a content type without implementing hook_form()
3743
  // @todo: remove this requirement.
3744
  $form = array();
3745
  $type = node_type_get_type($node);
3746

    
3747
  if ($type->has_title) {
3748
    $form['title'] = array(
3749
      '#type' => 'textfield',
3750
      '#title' => check_plain($type->title_label),
3751
      '#required' => TRUE,
3752
      '#default_value' => $node->title,
3753
      '#maxlength' => 255,
3754
      '#weight' => -5,
3755
    );
3756
  }
3757

    
3758
  return $form;
3759
}
3760

    
3761
/**
3762
 * @} End of "defgroup node_content".
3763
 */
3764

    
3765
/**
3766
 * Implements hook_forms().
3767
 *
3768
 * All node forms share the same form handler.
3769
 */
3770
function node_forms() {
3771
  $forms = array();
3772
  if ($types = node_type_get_types()) {
3773
    foreach (array_keys($types) as $type) {
3774
      $forms[$type . '_node_form']['callback'] = 'node_form';
3775
    }
3776
  }
3777
  return $forms;
3778
}
3779

    
3780
/**
3781
 * Implements hook_action_info().
3782
 */
3783
function node_action_info() {
3784
  return array(
3785
    'node_publish_action' => array(
3786
      'type' => 'node',
3787
      'label' => t('Publish content'),
3788
      'configurable' => FALSE,
3789
      'behavior' => array('changes_property'),
3790
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3791
    ),
3792
    'node_unpublish_action' => array(
3793
      'type' => 'node',
3794
      'label' => t('Unpublish content'),
3795
      'configurable' => FALSE,
3796
      'behavior' => array('changes_property'),
3797
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3798
    ),
3799
    'node_make_sticky_action' => array(
3800
      'type' => 'node',
3801
      'label' => t('Make content sticky'),
3802
      'configurable' => FALSE,
3803
      'behavior' => array('changes_property'),
3804
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3805
    ),
3806
    'node_make_unsticky_action' => array(
3807
      'type' => 'node',
3808
      'label' => t('Make content unsticky'),
3809
      'configurable' => FALSE,
3810
      'behavior' => array('changes_property'),
3811
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3812
    ),
3813
    'node_promote_action' => array(
3814
      'type' => 'node',
3815
      'label' => t('Promote content to front page'),
3816
      'configurable' => FALSE,
3817
      'behavior' => array('changes_property'),
3818
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3819
    ),
3820
    'node_unpromote_action' => array(
3821
      'type' => 'node',
3822
      'label' => t('Remove content from front page'),
3823
      'configurable' => FALSE,
3824
      'behavior' => array('changes_property'),
3825
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3826
    ),
3827
    'node_assign_owner_action' => array(
3828
      'type' => 'node',
3829
      'label' => t('Change the author of content'),
3830
      'configurable' => TRUE,
3831
      'behavior' => array('changes_property'),
3832
      'triggers' => array('node_presave', 'comment_insert', 'comment_update', 'comment_delete'),
3833
    ),
3834
    'node_save_action' => array(
3835
      'type' => 'node',
3836
      'label' => t('Save content'),
3837
      'configurable' => FALSE,
3838
      'triggers' => array('comment_insert', 'comment_update', 'comment_delete'),
3839
    ),
3840
    'node_unpublish_by_keyword_action' => array(
3841
      'type' => 'node',
3842
      'label' => t('Unpublish content containing keyword(s)'),
3843
      'configurable' => TRUE,
3844
      'triggers' => array('node_presave', 'node_insert', 'node_update'),
3845
    ),
3846
  );
3847
}
3848

    
3849
/**
3850
 * Sets the status of a node to 1 (published).
3851
 *
3852
 * @param $node
3853
 *   A node object.
3854
 * @param $context
3855
 *   (optional) Array of additional information about what triggered the action.
3856
 *   Not used for this action.
3857
 *
3858
 * @ingroup actions
3859
 */
3860
function node_publish_action($node, $context = array()) {
3861
  $node->status = NODE_PUBLISHED;
3862
  watchdog('action', 'Set @type %title to published.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3863
}
3864

    
3865
/**
3866
 * Sets the status of a node to 0 (unpublished).
3867
 *
3868
 * @param $node
3869
 *   A node object.
3870
 * @param $context
3871
 *   (optional) Array of additional information about what triggered the action.
3872
 *   Not used for this action.
3873
 *
3874
 * @ingroup actions
3875
 */
3876
function node_unpublish_action($node, $context = array()) {
3877
  $node->status = NODE_NOT_PUBLISHED;
3878
  watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3879
}
3880

    
3881
/**
3882
 * Sets the sticky-at-top-of-list property of a node to 1.
3883
 *
3884
 * @param $node
3885
 *   A node object.
3886
 * @param $context
3887
 *   (optional) Array of additional information about what triggered the action.
3888
 *   Not used for this action.
3889
 *
3890
 * @ingroup actions
3891
 */
3892
function node_make_sticky_action($node, $context = array()) {
3893
  $node->sticky = NODE_STICKY;
3894
  watchdog('action', 'Set @type %title to sticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3895
}
3896

    
3897
/**
3898
 * Sets the sticky-at-top-of-list property of a node to 0.
3899
 *
3900
 * @param $node
3901
 *   A node object.
3902
 * @param $context
3903
 *   (optional) Array of additional information about what triggered the action.
3904
 *   Not used for this action.
3905
 *
3906
 * @ingroup actions
3907
 */
3908
function node_make_unsticky_action($node, $context = array()) {
3909
  $node->sticky = NODE_NOT_STICKY;
3910
  watchdog('action', 'Set @type %title to unsticky.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3911
}
3912

    
3913
/**
3914
 * Sets the promote property of a node to 1.
3915
 *
3916
 * @param $node
3917
 *   A node object.
3918
 * @param $context
3919
 *   (optional) Array of additional information about what triggered the action.
3920
 *   Not used for this action.
3921
 *
3922
 * @ingroup actions
3923
 */
3924
function node_promote_action($node, $context = array()) {
3925
  $node->promote = NODE_PROMOTED;
3926
  watchdog('action', 'Promoted @type %title to front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3927
}
3928

    
3929
/**
3930
 * Sets the promote property of a node to 0.
3931
 *
3932
 * @param $node
3933
 *   A node object.
3934
 * @param $context
3935
 *   (optional) Array of additional information about what triggered the action.
3936
 *   Not used for this action.
3937
 *
3938
 * @ingroup actions
3939
 */
3940
function node_unpromote_action($node, $context = array()) {
3941
  $node->promote = NODE_NOT_PROMOTED;
3942
  watchdog('action', 'Removed @type %title from front page.', array('@type' => node_type_get_name($node), '%title' => $node->title));
3943
}
3944

    
3945
/**
3946
 * Saves a node.
3947
 *
3948
 * @param $node
3949
 *   The node to be saved.
3950
 *
3951
 * @ingroup actions
3952
 */
3953
function node_save_action($node) {
3954
  node_save($node);
3955
  watchdog('action', 'Saved @type %title', array('@type' => node_type_get_name($node), '%title' => $node->title));
3956
}
3957

    
3958
/**
3959
 * Assigns ownership of a node to a user.
3960
 *
3961
 * @param $node
3962
 *   A node object to modify.
3963
 * @param $context
3964
 *   Array with the following elements:
3965
 *   - 'owner_uid': User ID to assign to the node.
3966
 *
3967
 * @see node_assign_owner_action_form()
3968
 * @see node_assign_owner_action_validate()
3969
 * @see node_assign_owner_action_submit()
3970
 * @ingroup actions
3971
 */
3972
function node_assign_owner_action($node, $context) {
3973
  $node->uid = $context['owner_uid'];
3974
  $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
3975
  watchdog('action', 'Changed owner of @type %title to uid %name.', array('@type' =>  node_type_get_name($node), '%title' => $node->title, '%name' => $owner_name));
3976
}
3977

    
3978
/**
3979
 * Generates the settings form for node_assign_owner_action().
3980
 *
3981
 * @param $context
3982
 *   Array of additional information about what triggered the action. Includes
3983
 *   the following elements:
3984
 *   - 'owner_uid': User ID to assign to the node.
3985
 *
3986
 * @see node_assign_owner_action_submit()
3987
 * @see node_assign_owner_action_validate()
3988
 *
3989
 * @ingroup forms
3990
 */
3991
function node_assign_owner_action_form($context) {
3992
  $description = t('The username of the user to which you would like to assign ownership.');
3993
  $count = db_query("SELECT COUNT(*) FROM {users}")->fetchField();
3994
  $owner_name = '';
3995
  if (isset($context['owner_uid'])) {
3996
    $owner_name = db_query("SELECT name FROM {users} WHERE uid = :uid", array(':uid' => $context['owner_uid']))->fetchField();
3997
  }
3998

    
3999
  // Use dropdown for fewer than 200 users; textbox for more than that.
4000
  if (intval($count) < 200) {
4001
    $options = array();
4002
    $result = db_query("SELECT uid, name FROM {users} WHERE uid > 0 ORDER BY name");
4003
    foreach ($result as $data) {
4004
      $options[$data->name] = $data->name;
4005
    }
4006
    $form['owner_name'] = array(
4007
      '#type' => 'select',
4008
      '#title' => t('Username'),
4009
      '#default_value' => $owner_name,
4010
      '#options' => $options,
4011
      '#description' => $description,
4012
    );
4013
  }
4014
  else {
4015
    $form['owner_name'] = array(
4016
      '#type' => 'textfield',
4017
      '#title' => t('Username'),
4018
      '#default_value' => $owner_name,
4019
      '#autocomplete_path' => 'user/autocomplete',
4020
      '#size' => '6',
4021
      '#maxlength' => '60',
4022
      '#description' => $description,
4023
    );
4024
  }
4025
  return $form;
4026
}
4027

    
4028
/**
4029
 * Validates settings form for node_assign_owner_action().
4030
 *
4031
 * @see node_assign_owner_action_submit()
4032
 */
4033
function node_assign_owner_action_validate($form, $form_state) {
4034
  $exists = (bool) db_query_range('SELECT 1 FROM {users} WHERE name = :name', 0, 1, array(':name' => $form_state['values']['owner_name']))->fetchField();
4035
  if (!$exists) {
4036
    form_set_error('owner_name', t('Enter a valid username.'));
4037
  }
4038
}
4039

    
4040
/**
4041
 * Saves settings form for node_assign_owner_action().
4042
 *
4043
 * @see node_assign_owner_action_validate()
4044
 */
4045
function node_assign_owner_action_submit($form, $form_state) {
4046
  // Username can change, so we need to store the ID, not the username.
4047
  $uid = db_query('SELECT uid from {users} WHERE name = :name', array(':name' => $form_state['values']['owner_name']))->fetchField();
4048
  return array('owner_uid' => $uid);
4049
}
4050

    
4051
/**
4052
 * Generates settings form for node_unpublish_by_keyword_action().
4053
 *
4054
 * @param array $context
4055
 *   Array of additional information about what triggered this action.
4056
 *
4057
 * @return array
4058
 *   A form array.
4059
 *
4060
 * @see node_unpublish_by_keyword_action_submit()
4061
 */
4062
function node_unpublish_by_keyword_action_form($context) {
4063
  $form['keywords'] = array(
4064
    '#title' => t('Keywords'),
4065
    '#type' => 'textarea',
4066
    '#description' => t('The content will be unpublished if it contains any of the phrases above. Use a case-sensitive, comma-separated list of phrases. Example: funny, bungee jumping, "Company, Inc."'),
4067
    '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
4068
  );
4069
  return $form;
4070
}
4071

    
4072
/**
4073
 * Saves settings form for node_unpublish_by_keyword_action().
4074
 */
4075
function node_unpublish_by_keyword_action_submit($form, $form_state) {
4076
  return array('keywords' => drupal_explode_tags($form_state['values']['keywords']));
4077
}
4078

    
4079
/**
4080
 * Unpublishes a node containing certain keywords.
4081
 *
4082
 * @param $node
4083
 *   A node object to modify.
4084
 * @param $context
4085
 *   Array with the following elements:
4086
 *   - 'keywords': Array of keywords. If any keyword is present in the rendered
4087
 *     node, the node's status flag is set to unpublished.
4088
 *
4089
 * @ingroup actions
4090
 */
4091
function node_unpublish_by_keyword_action($node, $context) {
4092
  foreach ($context['keywords'] as $keyword) {
4093
    $elements = node_view(clone $node);
4094
    if (strpos(drupal_render($elements), $keyword) !== FALSE || strpos($node->title, $keyword) !== FALSE) {
4095
      $node->status = NODE_NOT_PUBLISHED;
4096
      watchdog('action', 'Set @type %title to unpublished.', array('@type' => node_type_get_name($node), '%title' => $node->title));
4097
      break;
4098
    }
4099
  }
4100
}
4101

    
4102
/**
4103
 * Implements hook_requirements().
4104
 */
4105
function node_requirements($phase) {
4106
  $requirements = array();
4107
  if ($phase === 'runtime') {
4108
    // Only show rebuild button if there are either 0, or 2 or more, rows
4109
    // in the {node_access} table, or if there are modules that
4110
    // implement hook_node_grants().
4111
    $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
4112
    if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
4113
      $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
4114
    }
4115
    else {
4116
      $value = t('Disabled');
4117
    }
4118
    $description = t('If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache. Rebuilding will remove all privileges to content and replace them with permissions based on the current modules and settings. Rebuilding may take some time if there is a lot of content or complex permission settings. After rebuilding has completed, content will automatically use the new permissions.');
4119

    
4120
    $requirements['node_access'] = array(
4121
      'title' => t('Node Access Permissions'),
4122
      'value' => $value,
4123
      'description' => $description . ' ' . l(t('Rebuild permissions'), 'admin/reports/status/rebuild'),
4124
    );
4125
  }
4126
  return $requirements;
4127
}
4128

    
4129
/**
4130
 * Implements hook_modules_enabled().
4131
 */
4132
function node_modules_enabled($modules) {
4133
  // Check if any of the newly enabled modules require the node_access table to
4134
  // be rebuilt.
4135
  if (!node_access_needs_rebuild() && array_intersect($modules, module_implements('node_grants'))) {
4136
    node_access_needs_rebuild(TRUE);
4137
  }
4138
}
4139

    
4140
/**
4141
 * Controller class for nodes.
4142
 *
4143
 * This extends the DrupalDefaultEntityController class, adding required
4144
 * special handling for node objects.
4145
 */
4146
class NodeController extends DrupalDefaultEntityController {
4147

    
4148
  protected function attachLoad(&$nodes, $revision_id = FALSE) {
4149
    // Create an array of nodes for each content type and pass this to the
4150
    // object type specific callback.
4151
    $typed_nodes = array();
4152
    foreach ($nodes as $id => $entity) {
4153
      $typed_nodes[$entity->type][$id] = $entity;
4154
    }
4155

    
4156
    // Call object type specific callbacks on each typed array of nodes.
4157
    foreach ($typed_nodes as $node_type => $nodes_of_type) {
4158
      if (node_hook($node_type, 'load')) {
4159
        $function = node_type_get_base($node_type) . '_load';
4160
        $function($nodes_of_type);
4161
      }
4162
    }
4163
    // Besides the list of nodes, pass one additional argument to
4164
    // hook_node_load(), containing a list of node types that were loaded.
4165
    $argument = array_keys($typed_nodes);
4166
    $this->hookLoadArguments = array($argument);
4167
    parent::attachLoad($nodes, $revision_id);
4168
  }
4169

    
4170
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
4171
    // Ensure that uid is taken from the {node} table,
4172
    // alias timestamp to revision_timestamp and add revision_uid.
4173
    $query = parent::buildQuery($ids, $conditions, $revision_id);
4174
    $fields =& $query->getFields();
4175
    unset($fields['timestamp']);
4176
    $query->addField('revision', 'timestamp', 'revision_timestamp');
4177
    $fields['uid']['table'] = 'base';
4178
    $query->addField('revision', 'uid', 'revision_uid');
4179
    return $query;
4180
  }
4181
}
4182

    
4183
/**
4184
 * Implements hook_file_download_access().
4185
 */
4186
function node_file_download_access($field, $entity_type, $entity) {
4187
  if ($entity_type == 'node') {
4188
    return node_access('view', $entity);
4189
  }
4190
}