Projet

Général

Profil

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

root / drupal7 / modules / node / node.module @ b4adf10d

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. Currently not used in any way.
510
 *   - locked: TRUE or FALSE indicating whether the administrator can change the
511
 *     machine name of this type.
512
 *   - disabled: TRUE or FALSE indicating whether this type has been disabled.
513
 *   - has_title: TRUE or FALSE indicating whether this type uses the node title
514
 *     field.
515
 *   - title_label: A string containing the label for the title.
516
 *   - module: A string giving the module defining this type of node.
517
 *   - orig_type: A string giving the original machine-readable name of this
518
 *     node type. This may be different from the current type name if the
519
 *     'locked' key is FALSE.
520
 *
521
 * @return int
522
 *   A status flag indicating the outcome of the operation, either SAVED_NEW or
523
 *   SAVED_UPDATED.
524
 */
525
function node_type_save($info) {
526
  $existing_type = !empty($info->old_type) ? $info->old_type : $info->type;
527
  $is_existing = (bool) db_query_range('SELECT 1 FROM {node_type} WHERE type = :type', 0, 1, array(':type' => $existing_type))->fetchField();
528
  $type = node_type_set_defaults($info);
529

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

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

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

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

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

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

    
572
  return $status;
573
}
574

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

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

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

    
642
  return $extra;
643
}
644

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

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

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

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

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

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

    
721
  foreach (module_implements('node_info') as $module) {
722
    $info_array = module_invoke($module, 'node_info');
723
    foreach ($info_array as $type => $info) {
724
      $info['type'] = $type;
725
      $_node_types->types[$type] = node_type_set_defaults($info);
726
      $_node_types->types[$type]->module = $module;
727
      $_node_types->names[$type] = $info['name'];
728
    }
729
  }
730
  $query = db_select('node_type', 'nt')
731
    ->addTag('translatable')
732
    ->addTag('node_type_access')
733
    ->fields('nt')
734
    ->orderBy('nt.type', 'ASC');
735
  if (!$rebuild) {
736
    $query->condition('disabled', 0);
737
  }
738
  foreach ($query->execute() as $type_object) {
739
    $type_db = $type_object->type;
740
    // Original disabled value.
741
    $disabled = $type_object->disabled;
742
    // Check for node types from disabled modules and mark their types for removal.
743
    // Types defined by the node module in the database (rather than by a separate
744
    // module using hook_node_info) have a base value of 'node_content'. The isset()
745
    // check prevents errors on old (pre-Drupal 7) databases.
746
    if (isset($type_object->base) && $type_object->base != 'node_content' && empty($_node_types->types[$type_db])) {
747
      $type_object->disabled = TRUE;
748
    }
749
    if (isset($_node_types->types[$type_db])) {
750
      $type_object->disabled = FALSE;
751
    }
752
    if (!isset($_node_types->types[$type_db]) || $type_object->modified) {
753
      $_node_types->types[$type_db] = $type_object;
754
      $_node_types->names[$type_db] = $type_object->name;
755

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

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

    
773
  asort($_node_types->names);
774

    
775
  cache_set($cid, $_node_types);
776

    
777
  return $_node_types;
778
}
779

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

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

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

    
832
  return $new_type;
833
}
834

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

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

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

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

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

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

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

    
1005
/**
1006
 * Implements hook_validate().
1007
 *
1008
 * Performs validation checks on the given node.
1009
 */
1010
function node_validate($node, $form, &$form_state) {
1011
  if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
1012
    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.'));
1013
  }
1014

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

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

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

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

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

    
1066
  return $node;
1067
}
1068

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1360
  return $build;
1361
}
1362

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

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

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

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

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

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

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

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

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

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

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

    
1470
  return $nodes;
1471
}
1472

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

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

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

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

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

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

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

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

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

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

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

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

    
1609
  return $perms;
1610
}
1611

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

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

    
1644
/**
1645
 * Implements hook_search_access().
1646
 */
1647
function node_search_access() {
1648
  return user_access('access content');
1649
}
1650

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

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

    
1670
/**
1671
 * Implements hook_search_admin().
1672
 */
1673
function node_search_admin() {
1674
  // Output form for defining rank factor weights.
1675
  $form['content_ranking'] = array(
1676
    '#type' => 'fieldset',
1677
    '#title' => t('Content ranking'),
1678
  );
1679
  $form['content_ranking']['#theme'] = 'node_search_admin';
1680
  $form['content_ranking']['info'] = array(
1681
    '#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>'
1682
  );
1683

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

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

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

    
1720
  // Add the ranking expressions.
1721
  _node_rankings($query);
1722

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

    
1735
    // Fetch comments for snippet.
1736
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
1737

    
1738
    $extra = module_invoke_all('node_search_result', $node);
1739

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

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

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

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

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

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

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

    
1866
  $output = drupal_render($form['info']);
1867

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

    
1878
  $output .= drupal_render_children($form);
1879
  return $output;
1880
}
1881

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

    
1901
  $map = array(
1902
    'view' => 'view revisions',
1903
    'update' => 'revert revisions',
1904
    'delete' => 'delete revisions',
1905
  );
1906

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

    
1913
  if (!isset($account)) {
1914
    $account = $GLOBALS['user'];
1915
  }
1916

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

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

    
1926
    $node_current_revision = node_load($node->nid);
1927
    $is_current_revision = $node_current_revision->vid == $node->vid;
1928

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

    
1947
  return $access[$cid];
1948
}
1949

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

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

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

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

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

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

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

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

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

    
2217
/**
2218
 * Returns a list of all the existing revision numbers.
2219
 *
2220
 * @param $node
2221
 *   The node object.
2222
 *
2223
 * @return
2224
 *   An associative array keyed by node revision number.
2225
 */
2226
function node_revision_list($node) {
2227
  $revisions = array();
2228
  $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));
2229
  foreach ($result as $revision) {
2230
    $revisions[$revision->vid] = $revision;
2231
  }
2232

    
2233
  return $revisions;
2234
}
2235

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

    
2244
  $blocks['recent']['info'] = t('Recent content');
2245
  $blocks['recent']['properties']['administrative'] = TRUE;
2246

    
2247
  return $blocks;
2248
}
2249

    
2250
/**
2251
 * Implements hook_block_view().
2252
 */
2253
function node_block_view($delta = '') {
2254
  $block = array();
2255

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

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

    
2278
/**
2279
 * Implements hook_block_configure().
2280
 */
2281
function node_block_configure($delta = '') {
2282
  $form = array();
2283
  if ($delta == 'recent') {
2284
    $form['node_recent_block_count'] = array(
2285
      '#type' => 'select',
2286
      '#title' => t('Number of recent content items to display'),
2287
      '#default_value' => variable_get('node_recent_block_count', 10),
2288
      '#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)),
2289
    );
2290
  }
2291
  return $form;
2292
}
2293

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

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

    
2316
  if (!user_access('bypass node access')) {
2317
    // If the user is able to view their own unpublished nodes, allow them to
2318
    // see these in addition to published nodes. Check that they actually have
2319
    // some unpublished nodes to view before adding the condition.
2320
    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()) {
2321
      $query->condition(db_or()
2322
        ->condition('n.status', NODE_PUBLISHED)
2323
        ->condition('n.nid', $own_unpublished, 'IN')
2324
      );
2325
    }
2326
    else {
2327
      // If not, restrict the query to published nodes.
2328
      $query->condition('n.status', NODE_PUBLISHED);
2329
    }
2330
  }
2331
  $nids = $query
2332
    ->fields('n', array('nid'))
2333
    ->orderBy('n.changed', 'DESC')
2334
    ->range(0, $number)
2335
    ->addTag('node_access')
2336
    ->execute()
2337
    ->fetchCol();
2338

    
2339
  $nodes = node_load_multiple($nids);
2340

    
2341
  return $nodes ? $nodes : array();
2342
}
2343

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

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

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

    
2382
  return $output;
2383
}
2384

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

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

    
2404
  return $output;
2405
}
2406

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

    
2418
/**
2419
 * Implements hook_form_FORMID_alter().
2420
 *
2421
 * Adds node-type specific visibility options to block configuration form.
2422
 *
2423
 * @see block_admin_configure()
2424
 */
2425
function node_form_block_admin_configure_alter(&$form, &$form_state) {
2426
  $default_type_options = db_query("SELECT type FROM {block_node_type} WHERE module = :module AND delta = :delta", array(
2427
    ':module' => $form['module']['#value'],
2428
    ':delta' => $form['delta']['#value'],
2429
  ))->fetchCol();
2430
  $form['visibility']['node_type'] = array(
2431
    '#type' => 'fieldset',
2432
    '#title' => t('Content types'),
2433
    '#collapsible' => TRUE,
2434
    '#collapsed' => TRUE,
2435
    '#group' => 'visibility',
2436
    '#weight' => 5,
2437
  );
2438
  $form['visibility']['node_type']['types'] = array(
2439
    '#type' => 'checkboxes',
2440
    '#title' => t('Show block for specific content types'),
2441
    '#default_value' => $default_type_options,
2442
    '#options' => node_type_get_names(),
2443
    '#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.'),
2444
  );
2445
  $form['#submit'][] = 'node_form_block_admin_configure_submit';
2446
}
2447

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2614
    if (!empty($node->rss_namespaces)) {
2615
      $namespaces = array_merge($namespaces, $node->rss_namespaces);
2616
    }
2617

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

    
2624
    $items .= format_rss_item($node->title, $node->link, $item_text, $node->rss_elements);
2625
  }
2626

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

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

    
2642
  drupal_add_http_header('Content-Type', 'application/rss+xml; charset=utf-8');
2643
  print $output;
2644
}
2645

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

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

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

    
2683
  return $build;
2684
}
2685

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

    
2705
  $nids = $select->execute()->fetchCol();
2706

    
2707
  if (!empty($nids)) {
2708
    $nodes = node_load_multiple($nids);
2709
    $build = node_view_multiple($nodes);
2710

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

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

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

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

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

    
2765
/**
2766
 * Implements hook_update_index().
2767
 */
2768
function node_update_index() {
2769
  $limit = (int)variable_get('search_cron_limit', 100);
2770

    
2771
  $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'));
2772

    
2773
  foreach ($result as $node) {
2774
    _node_index_node($node);
2775
  }
2776
}
2777

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

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

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

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

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

    
2804
  // Update index
2805
  search_index($node->nid, 'node', $text);
2806
}
2807

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

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

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

    
2878
    $form['#validate'][] = 'node_search_validate';
2879
  }
2880
}
2881

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

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

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

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

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

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

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

    
3004
  $cid = is_object($node) ? $node->nid : $node;
3005

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

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

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

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

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

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

    
3082
  return FALSE;
3083
}
3084

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

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

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

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

    
3109
  return NODE_ACCESS_IGNORE;
3110
}
3111

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

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

    
3143
  return $perms;
3144
}
3145

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

    
3162
  $configured_types = array();
3163

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

    
3170
  return $configured_types;
3171
}
3172

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

    
3196
  if (!isset($account)) {
3197
    $account = $GLOBALS['user'];
3198
  }
3199

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

    
3205
  return array_merge(array('all' => array(0)), $grants);
3206
}
3207

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

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

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

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

    
3270
  return $access[$account->uid];
3271
}
3272

    
3273

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

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

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

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

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

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

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

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

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

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

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

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

    
3473
}
3474

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

    
3510
  node_access_write_grants($node, $grants, NULL, $delete);
3511
}
3512

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

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

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

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

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

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

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

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

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

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

    
3731
/**
3732
 * @} End of "defgroup node_access".
3733
 */
3734

    
3735
/**
3736
 * @defgroup node_content Hook implementations for user-created content types
3737
 * @{
3738
 * Functions that implement hooks for user-created content types.
3739
 */
3740

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

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

    
3761
  return $form;
3762
}
3763

    
3764
/**
3765
 * @} End of "defgroup node_content".
3766
 */
3767

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4054
/**
4055
 * Generates settings form for node_unpublish_by_keyword_action().
4056
 *
4057
 * @param array $context
4058
 *   Array of additional information about what triggered this action.
4059
 *
4060
 * @return array
4061
 *   A form array.
4062
 *
4063
 * @see node_unpublish_by_keyword_action_submit()
4064
 */
4065
function node_unpublish_by_keyword_action_form($context) {
4066
  $form['keywords'] = array(
4067
    '#title' => t('Keywords'),
4068
    '#type' => 'textarea',
4069
    '#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."'),
4070
    '#default_value' => isset($context['keywords']) ? drupal_implode_tags($context['keywords']) : '',
4071
  );
4072
  return $form;
4073
}
4074

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

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

    
4105
/**
4106
 * Implements hook_requirements().
4107
 */
4108
function node_requirements($phase) {
4109
  $requirements = array();
4110
  if ($phase === 'runtime') {
4111
    // Only show rebuild button if there are either 0, or 2 or more, rows
4112
    // in the {node_access} table, or if there are modules that
4113
    // implement hook_node_grants().
4114
    $grant_count = db_query('SELECT COUNT(*) FROM {node_access}')->fetchField();
4115
    if ($grant_count != 1 || count(module_implements('node_grants')) > 0) {
4116
      $value = format_plural($grant_count, 'One permission in use', '@count permissions in use', array('@count' => $grant_count));
4117
    }
4118
    else {
4119
      $value = t('Disabled');
4120
    }
4121
    $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.');
4122

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

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

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

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

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

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

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