/[drupal]/drupal/modules/node.module
ViewVC logotype

Contents of /drupal/modules/node.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.641.2.27 - (show annotations) (download) (as text)
Thu Dec 21 23:47:33 2006 UTC (2 years, 11 months ago) by killes
Branch: DRUPAL-4-7
Changes since 1.641.2.26: +5 -7 lines
File MIME type: text/x-php
#104618 by robertDouglas and jvandyk: fixed node caching., backport
1 <?php
2 // $Id: node.module,v 1.641.2.26 2006/12/21 19:22:58 killes Exp $
3
4 /**
5 * @file
6 * The core that allows content to be submitted to the site.
7 */
8
9 define('NODE_NEW_LIMIT', time() - 30 * 24 * 60 * 60);
10
11 /**
12 * Implementation of hook_help().
13 */
14 function node_help($section) {
15 switch ($section) {
16 case 'admin/help#node':
17 $output = '<p>'. t('All content in a website is stored and treated as <b>nodes</b>. Therefore nodes are any postings such as blogs, stories, polls and forums. The node module manages these content types and is one of the strengths of Drupal over other content management systems.') .'</p>';
18 $output .= '<p>'. t('Treating all content as nodes allows the flexibility of creating new types of content. It also allows you to painlessly apply new features or changes to all content. Comments are not stored as nodes but are always associated with a node.') .'</p>';
19 $output .= t('<p>Node module features</p>
20 <ul>
21 <li>The list tab provides an interface to search and sort all content on your site.</li>
22 <li>The configure settings tab has basic settings for content on your site.</li>
23 <li>The configure content types tab lists all content types for your site and lets you configure their default workflow.</li>
24 <li>The search tab lets you search all content on your site</li>
25 </ul>
26 ');
27 $output .= t('<p>You can</p>
28 <ul>
29 <li>search for content at <a href="%search">search</a>.</li>
30 <li>administer nodes at <a href="%admin-settings-content-types">administer &gt;&gt; settings &gt;&gt; content types</a>.</li>
31 </ul>
32 ', array('%search' => url('search'), '%admin-settings-content-types' => url('admin/settings/content-types')));
33 $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%node">Node page</a>.', array('%node' => 'http://drupal.org/handbook/modules/node/')) .'</p>';
34 return $output;
35 case 'admin/modules#description':
36 return t('Allows content to be submitted to the site and displayed on pages.');
37 case 'admin/node/configure':
38 case 'admin/node/configure/settings':
39 return t('<p>Settings for the core of Drupal. Almost everything is a node so these settings will affect most of the site.</p>');
40 case 'admin/node':
41 return t('<p>Below is a list of all of the posts on your site. Other forms of content are listed elsewhere (e.g. <a href="%comments">comments</a>).</p><p>Clicking a title views the post, while clicking an author\'s name views their user information.</p>', array('%comments' => url('admin/comment')));
42 case 'admin/node/search':
43 return t('<p>Enter a simple pattern to search for a post. This can include the wildcard character *.<br />For example, a search for "br*" might return "bread bakers", "our daily bread" and "brenda".</p>');
44 }
45
46 if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions' && !arg(3)) {
47 return t('The revisions let you track differences between multiple versions of a post.');
48 }
49
50 if (arg(0) == 'node' && arg(1) == 'add' && $type = arg(2)) {
51 return filter_xss_admin(variable_get($type .'_help', ''));
52 }
53 }
54
55 /**
56 * Implementation of hook_cron().
57 */
58 function node_cron() {
59 db_query('DELETE FROM {history} WHERE timestamp < %d', NODE_NEW_LIMIT);
60 }
61
62 /**
63 * Gather a listing of links to nodes.
64 *
65 * @param $result
66 * A DB result object from a query to fetch node objects. If your query joins the <code>node_comment_statistics</code> table so that the <code>comment_count</code> field is available, a title attribute will be added to show the number of comments.
67 * @param $title
68 * A heading for the resulting list.
69 *
70 * @return
71 * An HTML list suitable as content for a block.
72 */
73 function node_title_list($result, $title = NULL) {
74 while ($node = db_fetch_object($result)) {
75 $items[] = l($node->title, 'node/'. $node->nid, $node->comment_count ? array('title' => format_plural($node->comment_count, '1 comment', '%count comments')) : '');
76 }
77
78 return theme('node_list', $items, $title);
79 }
80
81 /**
82 * Format a listing of links to nodes.
83 */
84 function theme_node_list($items, $title = NULL) {
85 return theme('item_list', $items, $title);
86 }
87
88 /**
89 * Update the 'last viewed' timestamp of the specified node for current user.
90 */
91 function node_tag_new($nid) {
92 global $user;
93
94 if ($user->uid) {
95 if (node_last_viewed($nid)) {
96 db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
97 }
98 else {
99 @db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
100 }
101 }
102 }
103
104 /**
105 * Retrieves the timestamp at which the current user last viewed the
106 * specified node.
107 */
108 function node_last_viewed($nid) {
109 global $user;
110 static $history;
111
112 if (!isset($history[$nid])) {
113 $history[$nid] = db_fetch_object(db_query("SELECT timestamp FROM {history} WHERE uid = '$user->uid' AND nid = %d", $nid));
114 }
115
116 return (isset($history[$nid]->timestamp) ? $history[$nid]->timestamp : 0);
117 }
118
119 /**
120 * Decide on the type of marker to be displayed for a given node.
121 *
122 * @param $nid
123 * Node ID whose history supplies the "last viewed" timestamp.
124 * @param $timestamp
125 * Time which is compared against node's "last viewed" timestamp.
126 * @return
127 * One of the MARK constants.
128 */
129 function node_mark($nid, $timestamp) {
130 global $user;
131 static $cache;
132
133 if (!$user->uid) {
134 return MARK_READ;
135 }
136 if (!isset($cache[$nid])) {
137 $cache[$nid] = node_last_viewed($nid);
138 }
139 if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
140 return MARK_NEW;
141 }
142 elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
143 return MARK_UPDATED;
144 }
145 return MARK_READ;
146 }
147
148 /**
149 * Automatically generate a teaser for a node body in a given format.
150 */
151 function node_teaser($body, $format = NULL) {
152
153 $size = variable_get('teaser_length', 600);
154
155 // find where the delimiter is in the body
156 $delimiter = strpos($body, '<!--break-->');
157
158 // If the size is zero, and there is no delimiter, the entire body is the teaser.
159 if ($size == 0 && $delimiter === FALSE) {
160 return $body;
161 }
162
163 // If a valid delimiter has been specified, use it to chop off the teaser.
164 if ($delimiter !== FALSE) {
165 return substr($body, 0, $delimiter);
166 }
167
168 // We check for the presence of the PHP evaluator filter in the current
169 // format. If the body contains PHP code, we do not split it up to prevent
170 // parse errors.
171 if (isset($format)) {
172 $filters = filter_list_format($format);
173 if (isset($filters['filter/1']) && strpos($body, '<?') !== FALSE) {
174 return $body;
175 }
176 }
177
178 // If we have a short body, the entire body is the teaser.
179 if (strlen($body) < $size) {
180 return $body;
181 }
182
183 // In some cases, no delimiter has been specified (e.g. when posting using
184 // the Blogger API). In this case, we try to split at paragraph boundaries.
185 // When even the first paragraph is too long, we try to split at the end of
186 // the next sentence.
187 $breakpoints = array('</p>' => 4, '<br />' => 0, '<br>' => 0, "\n" => 0, '. ' => 1, '! ' => 1, '? ' => 1, '。' => 3, '؟ ' => 1);
188 foreach ($breakpoints as $point => $charnum) {
189 if ($length = strpos($body, $point, $size)) {
190 return substr($body, 0, $length + $charnum);
191 }
192 }
193
194 // If all else fails, we simply truncate the string.
195 return truncate_utf8($body, $size);
196 }
197
198 function _node_names($op = '', $node = NULL) {
199 static $node_names = array();
200 static $node_list = array();
201
202 if (empty($node_names)) {
203 $node_names = module_invoke_all('node_info');
204 foreach ($node_names as $type => $value) {
205 $node_list[$type] = $value['name'];
206 }
207 }
208 if ($node) {
209 if (is_array($node)) {
210 $type = $node['type'];
211 }
212 elseif (is_object($node)) {
213 $type = $node->type;
214 }
215 elseif (is_string($node)) {
216 $type = $node;
217 }
218 if (!isset($node_names[$type])) {
219 return FALSE;
220 }
221 }
222 switch ($op) {
223 case 'base':
224 return $node_names[$type]['base'];
225 case 'list':
226 return $node_list;
227 case 'name':
228 return $node_list[$type];
229 }
230 }
231
232 /**
233 * Determine the basename for hook_load etc.
234 *
235 * @param $node
236 * Either a node object, a node array, or a string containing the node type.
237 * @return
238 * The basename for hook_load, hook_nodeapi etc.
239 */
240 function node_get_base($node) {
241 return _node_names('base', $node);
242 }
243
244 /**
245 * Determine the human readable name for a given type.
246 *
247 * @param $node
248 * Either a node object, a node array, or a string containing the node type.
249 * @return
250 * The human readable name of the node type.
251 */
252 function node_get_name($node) {
253 return _node_names('name', $node);
254 }
255
256 /**
257 * Return the list of available node types.
258 *
259 * @param $node
260 * Either a node object, a node array, or a string containing the node type.
261 * @return
262 * An array consisting ('#type' => name) pairs.
263 */
264 function node_get_types() {
265 return _node_names('list');
266 }
267
268 /**
269 * Determine whether a node hook exists.
270 *
271 * @param &$node
272 * Either a node object, node array, or a string containing the node type.
273 * @param $hook
274 * A string containing the name of the hook.
275 * @return
276 * TRUE iff the $hook exists in the node type of $node.
277 */
278 function node_hook(&$node, $hook) {
279 return module_hook(node_get_base($node), $hook);
280 }
281
282 /**
283 * Invoke a node hook.
284 *
285 * @param &$node
286 * Either a node object, node array, or a string containing the node type.
287 * @param $hook
288 * A string containing the name of the hook.
289 * @param $a2, $a3, $a4
290 * Arguments to pass on to the hook, after the $node argument.
291 * @return
292 * The returned value of the invoked hook.
293 */
294 function node_invoke(&$node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
295 if (node_hook($node, $hook)) {
296 $function = node_get_base($node) ."_$hook";
297 return ($function($node, $a2, $a3, $a4));
298 }
299 }
300
301 /**
302 * Invoke a hook_nodeapi() operation in all modules.
303 *
304 * @param &$node
305 * A node object.
306 * @param $op
307 * A string containing the name of the nodeapi operation.
308 * @param $a3, $a4
309 * Arguments to pass on to the hook, after the $node and $op arguments.
310 * @return
311 * The returned value of the invoked hooks.
312 */
313 function node_invoke_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
314 $return = array();
315 foreach (module_implements('nodeapi') as $name) {
316 $function = $name .'_nodeapi';
317 $result = $function($node, $op, $a3, $a4);
318 if (isset($result) && is_array($result)) {
319 $return = array_merge($return, $result);
320 }
321 else if (isset($result)) {
322 $return[] = $result;
323 }
324 }
325 return $return;
326 }
327
328 /**
329 * Load a node object from the database.
330 *
331 * @param $param
332 * Either the nid of the node or an array of conditions to match against in the database query
333 * @param $revision
334 * Which numbered revision to load. Defaults to the current version.
335 * @param $reset
336 * Whether to reset the internal node_load cache.
337 *
338 * @return
339 * A fully-populated node object.
340 */
341 function node_load($param = array(), $revision = NULL, $reset = NULL) {
342 static $nodes = array();
343
344 if ($reset) {
345 $nodes = array();
346 }
347
348 $cachable = ($revision == NULL);
349 $arguments = array();
350 if (is_numeric($param)) {
351 if ($cachable && isset($nodes[$param])) {
352 return is_object($nodes[$param]) ? drupal_clone($nodes[$param]) : $nodes[$param];
353 }
354 $cond = 'n.nid = %d';
355 $arguments[] = $param;
356 }
357 else {
358 // Turn the conditions into a query.
359 foreach ($param as $key => $value) {
360 $cond[] = 'n.'. db_escape_string($key) ." = '%s'";
361 $arguments[] = $value;
362 }
363 $cond = implode(' AND ', $cond);
364 }
365
366 // Retrieve the node.
367 // No db_rewrite_sql is applied so as to get complete indexing for search.
368 if ($revision) {
369 array_unshift($arguments, $revision);
370 $node = db_fetch_object(db_query('SELECT n.nid, r.vid, n.type, n.status, n.created, n.changed, n.comment, n.promote, n.moderate, n.sticky, r.timestamp AS revision_timestamp, r.title, r.body, r.teaser, r.log, r.format, u.uid, u.name, u.picture, u.data FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.nid = n.nid AND r.vid = %d WHERE '. $cond, $arguments));
371 }
372 else {
373 $node = db_fetch_object(db_query('SELECT n.nid, n.vid, n.type, n.status, n.created, n.changed, n.comment, n.promote, n.moderate, n.sticky, r.timestamp AS revision_timestamp, r.title, r.body, r.teaser, r.log, r.format, u.uid, u.name, u.picture, u.data FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE '. $cond, $arguments));
374 }
375
376 if ($node->nid) {
377 // Call the node specific callback (if any) and piggy-back the
378 // results to the node or overwrite some values.
379 if ($extra = node_invoke($node, 'load')) {
380 foreach ($extra as $key => $value) {
381 $node->$key = $value;
382 }
383 }
384
385 if ($extra = node_invoke_nodeapi($node, 'load')) {
386 foreach ($extra as $key => $value) {
387 $node->$key = $value;
388 }
389 }
390 if ($cachable) {
391 $nodes[$node->nid] = is_object($node) ? drupal_clone($node) : $node;
392 }
393 }
394
395 return $node;
396 }
397
398 /**
399 * Save a node object into the database.
400 */
401 function node_save(&$node) {
402 global $user;
403
404 $node->is_new = false;
405
406 // Apply filters to some default node fields:
407 if (empty($node->nid)) {
408 // Insert a new node.
409 $node->is_new = true;
410
411 $node->nid = db_next_id('{node}_nid');
412 $node->vid = db_next_id('{node_revisions}_vid');;
413 }
414 else {
415 // We need to ensure that all node fields are filled.
416 $node_current = node_load($node->nid);
417 foreach ($node as $field => $data) {
418 $node_current->$field = $data;
419 }
420 $node = $node_current;
421
422 if ($node->revision) {
423 $node->old_vid = $node->vid;
424 $node->vid = db_next_id('{node_revisions}_vid');
425 }
426 }
427
428 // Set some required fields:
429 if (empty($node->created)) {
430 $node->created = time();
431 }
432 // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
433 $node->changed = time();
434
435 // Split off revisions data to another structure
436 $revisions_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
437 'title' => $node->title, 'body' => $node->body,
438 'teaser' => $node->teaser, 'log' => $node->log, 'timestamp' => $node->changed,
439 'uid' => $user->uid, 'format' => $node->format);
440 $revisions_table_types = array('nid' => '%d', 'vid' => '%d',
441 'title' => "'%s'", 'body' => "'%s'",
442 'teaser' => "'%s'", 'log' => "'%s'", 'timestamp' => '%d',
443 'uid' => '%d', 'format' => '%d');
444 $node_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
445 'title' => $node->title, 'type' => $node->type, 'uid' => $node->uid,
446 'status' => $node->status, 'created' => $node->created,
447 'changed' => $node->changed, 'comment' => $node->comment,
448 'promote' => $node->promote, 'moderate' => $node->moderate,
449 'sticky' => $node->sticky);
450 $node_table_types = array('nid' => '%d', 'vid' => '%d',
451 'title' => "'%s'", 'type' => "'%s'", 'uid' => '%d',
452 'status' => '%d', 'created' => '%d',
453 'changed' => '%d', 'comment' => '%d',
454 'promote' => '%d', 'moderate' => '%d',
455 'sticky' => '%d');
456
457 //Generate the node table query and the
458 //the node_revisions table query
459 if ($node->is_new) {
460 $node_query = 'INSERT INTO {node} ('. implode(', ', array_keys($node_table_types)) .') VALUES ('. implode(', ', $node_table_types) .')';
461 $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
462 }
463 else {
464 $arr = array();
465 foreach ($node_table_types as $key => $value) {
466 $arr[] = $key .' = '. $value;
467 }
468 $node_table_values[] = $node->nid;
469 $node_query = 'UPDATE {node} SET '. implode(', ', $arr) .' WHERE nid = %d';
470 if ($node->revision) {
471 $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
472 }
473 else {
474 $arr = array();
475 foreach ($revisions_table_types as $key => $value) {
476 $arr[] = $key .' = '. $value;
477 }
478 $revisions_table_values[] = $node->vid;
479 $revisions_query = 'UPDATE {node_revisions} SET '. implode(', ', $arr) .' WHERE vid = %d';
480 }
481 }
482
483 // Insert the node into the database:
484 db_query($node_query, $node_table_values);
485 db_query($revisions_query, $revisions_table_values);
486
487 // Call the node specific callback (if any):
488 if ($node->is_new) {
489 node_invoke($node, 'insert');
490 node_invoke_nodeapi($node, 'insert');
491 }
492 else {
493 node_invoke($node, 'update');
494 node_invoke_nodeapi($node, 'update');
495 }
496
497 // Clear the cache so an anonymous poster can see the node being added or updated.
498 cache_clear_all();
499 }
500
501 /**
502 * Generate a display of the given node.
503 *
504 * @param $node
505 * A node array or node object.
506 * @param $teaser
507 * Whether to display the teaser only, as on the main page.
508 * @param $page
509 * Whether the node is being displayed by itself as a page.
510 * @param $links
511 * Whether or not to display node links. Links are omitted for node previews.
512 *
513 * @return
514 * An HTML representation of the themed node.
515 */
516 function node_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE) {
517 $node = (object)$node;
518
519 // Remove the delimiter (if any) that separates the teaser from the body.
520 // TODO: this strips legitimate uses of '<!--break-->' also.
521 $node->body = str_replace('<!--break-->', '', $node->body);
522
523 if ($node->log != '' && !$teaser && $node->moderate) {
524 $node->body .= '<div class="log"><div class="title">'. t('Log') .':</div>'. filter_xss($node->log) .'</div>';
525 }
526
527 // The 'view' hook can be implemented to overwrite the default function
528 // to display nodes.
529 if (node_hook($node, 'view')) {
530 node_invoke($node, 'view', $teaser, $page);
531 }
532 else {
533 $node = node_prepare($node, $teaser);
534 }
535 // Allow modules to change $node->body before viewing.
536 node_invoke_nodeapi($node, 'view', $teaser, $page);
537 if ($links) {
538 $node->links = module_invoke_all('link', 'node', $node, !$page);
539 }
540 // unset unused $node part so that a bad theme can not open a security hole
541 if ($teaser) {
542 unset($node->body);
543 }
544 else {
545 unset($node->teaser);
546 }
547
548 return theme('node', $node, $teaser, $page);
549 }
550
551 /**
552 * Apply filters to a node in preparation for theming.
553 */
554 function node_prepare($node, $teaser = FALSE) {
555 $node->readmore = (strlen($node->teaser) < strlen($node->body));
556 if ($teaser == FALSE) {
557 $node->body = check_markup($node->body, $node->format, FALSE);
558 }
559 else {
560 $node->teaser = check_markup($node->teaser, $node->format, FALSE);
561 }
562 return $node;
563 }
564
565 /**
566 * Generate a page displaying a single node, along with its comments.
567 */
568 function node_show($node, $cid) {
569 $output = node_view($node, FALSE, TRUE);
570
571 if (function_exists('comment_render') && $node->comment) {
572 $output .= comment_render($node, $cid);
573 }
574
575 // Update the history table, stating that this user viewed this node.
576 node_tag_new($node->nid);
577
578 return $output;
579 }
580
581 /**
582 * Implementation of hook_perm().
583 */
584 function node_perm() {
585 return array('administer nodes', 'access content', 'view revisions', 'revert revisions');
586 }
587
588 /**
589 * Implementation of hook_search().
590 */
591 function node_search($op = 'search', $keys = null) {
592 switch ($op) {
593 case 'name':
594 return t('content');
595
596 case 'reset':
597 variable_del('node_cron_last');
598 variable_del('node_cron_last_nid');
599 return;
600
601 case 'status':
602 $last = variable_get('node_cron_last', 0);
603 $last_nid = variable_get('node_cron_last_nid', 0);
604 $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
605 $remaining = db_result(db_query('SELECT COUNT(*) FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND ((GREATEST(n.created, n.changed, c.last_comment_timestamp) = %d AND n.nid > %d ) OR (n.created > %d OR n.changed > %d OR c.last_comment_timestamp > %d))', $last, $last_nid, $last, $last, $last));
606 return array('remaining' => $remaining, 'total' => $total);
607
608 case 'admin':
609 $form = array();
610 // Output form for defining rank factor weights.
611 $form['content_ranking'] = array('#type' => 'fieldset', '#title' => t('Content ranking'));
612 $form['content_ranking']['#theme'] = 'node_search_admin';
613 $form['content_ranking']['info'] = array('#type' => 'markup', '#value' => '<em>'. t('The following numbers control which properties the content search should favor when ordering the results. Higher numbers mean more influence, zero means the property is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') .'</em>');
614
615 $ranking = array('node_rank_relevance' => t('Keyword relevance'),
616 'node_rank_recent' => t('Recently posted'));
617 if (module_exist('comment')) {
618 $ranking['node_rank_comments'] = t('Number of comments');
619 }
620 if (module_exist('statistics') && variable_get('statistics_count_content_views', 0)) {
621 $ranking['node_rank_views'] = t('Number of views');
622 }
623
624 // Note: reversed to reflect that higher number = higher ranking.
625 $options = drupal_map_assoc(range(0, 10));
626 foreach ($ranking as $var => $title) {
627 $form['content_ranking']['factors'][$var] = array('#title' => $title, '#type' => 'select', '#options' => $options, '#default_value' => variable_get($var, 5));
628 }
629 return $form;
630
631 case 'search':
632 // Build matching conditions
633 list($join1, $where1) = _db_rewrite_sql();
634 $arguments1 = array();
635 $conditions1 = 'n.status = 1';
636
637 if ($type = search_query_extract($keys, 'type')) {
638 $types = array();
639 foreach (explode(',', $type) as $t) {
640 $types[] = "n.type = '%s'";
641 $arguments1[] = $t;
642 }
643 $conditions1 .= ' AND ('. implode(' OR ', $types) .')';
644 $keys = search_query_insert($keys, 'type');
645 }
646
647 if ($category = search_query_extract($keys, 'category')) {
648 $categories = array();
649 foreach (explode(',', $category) as $c) {
650 $categories[] = "tn.tid = %d";
651 $arguments1[] = $c;
652 }
653 $conditions1 .= ' AND ('. implode(' OR ', $categories) .')';
654 $join1 .= ' INNER JOIN {term_node} tn ON n.nid = tn.nid';
655 $keys = search_query_insert($keys, 'category');
656 }
657
658 // Build ranking expression (we try to map each parameter to a
659 // uniform distribution in the range 0..1).
660 $ranking = array();
661 $arguments2 = array();
662 $join2 = '';
663 $total = 0;
664 // Used to avoid joining on node_comment_statistics twice
665 $stats_join = false;
666 if ($weight = (int)variable_get('node_rank_relevance', 5)) {
667 // Average relevance values hover around 0.15
668 $ranking[] = '%d * i.relevance';
669 $arguments2[] = $weight;
670 $total += $weight;
671 }
672 if ($weight = (int)variable_get('node_rank_recent', 5)) {
673 // Exponential decay with half-life of 6 months, starting at last indexed node
674 $ranking[] = '%d * POW(2, (GREATEST(n.created, n.changed, c.last_comment_timestamp) - %d) * 6.43e-8)';
675 $arguments2[] = $weight;
676 $arguments2[] = (int)variable_get('node_cron_last', 0);
677 $join2 .= ' INNER JOIN {node} n ON n.nid = i.sid LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
678 $stats_join = true;
679 $total += $weight;
680 }
681 if (module_exist('comment') && $weight = (int)variable_get('node_rank_comments', 5)) {
682 // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
683 $scale = variable_get('node_cron_comments_scale', 0.0);
684 $ranking[] = '%d * (2.0 - 2.0 / (1.0 + c.comment_count * %f))';
685 $arguments2[] = $weight;
686 $arguments2[] = $scale;
687 if (!$stats_join) {
688 $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
689 }
690 $total += $weight;
691 }
692 if (module_exist('statistics') && variable_get('statistics_count_content_views', 0) &&
693 $weight = (int)variable_get('node_rank_views', 5)) {
694 // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
695 $scale = variable_get('node_cron_views_scale', 0.0);
696 $ranking[] = '%d * (2.0 - 2.0 / (1.0 + nc.totalcount * %f))';
697 $arguments2[] = $weight;
698 $arguments2[] = $scale;
699 $join2 .= ' LEFT JOIN {node_counter} nc ON nc.nid = i.sid';
700 $total += $weight;
701 }
702 $select2 = (count($ranking) ? implode(' + ', $ranking) : 'i.relevance') . ' AS score';
703
704 // Do search
705 $find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid '. $join1 .' INNER JOIN {users} u ON n.uid = u.uid', $conditions1 . (empty($where1) ? '' : ' AND '. $where1), $arguments1, $select2, $join2, $arguments2);
706
707 // Load results
708 $results = array();
709 foreach ($find as $item) {
710 $node = node_load($item->sid);
711
712 // Get node output (filtered and with module-specific fields).
713 if (node_hook($node, 'view')) {
714 node_invoke($node, 'view', false, false);
715 }
716 else {
717 $node = node_prepare($node, false);
718 }
719 // Allow modules to change $node->body before viewing.
720 node_invoke_nodeapi($node, 'view', false, false);
721
722 // Fetch comments for snippet
723 $node->body .= module_invoke('comment', 'nodeapi', $node, 'update index');
724 // Fetch terms for snippet
725 $node->body .= module_invoke('taxonomy', 'nodeapi', $node, 'update index');
726
727 $extra = node_invoke_nodeapi($node, 'search result');
728 $results[] = array('link' => url('node/'. $item->sid),
729 'type' => node_get_name($node),
730 'title' => $node->title,
731 'user' => theme('username', $node),
732 'date' => $node->changed,
733 'node' => $node,
734 'extra' => $extra,
735 'score' => $item->score / $total,
736 'snippet' => search_excerpt($keys, $node->body));
737 }
738 return $results;
739 }
740 }
741
742 /**
743 * Implementation of hook_user().
744 */
745 function node_user($op, &$edit, &$user) {
746 if ($op == 'delete') {
747 db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
748 db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
749 }
750 }
751
752 function theme_node_search_admin($form) {
753 $output = form_render($form['info']);
754
755 $header = array(t('Factor'), t('Weight'));
756 foreach (element_children($form['factors']) as $key) {
757 $row = array();
758 $row[] = $form['factors'][$key]['#title'];
759 unset($form['factors'][$key]['#title']);
760 $row[] = form_render($form['factors'][$key]);
761 $rows[] = $row;
762 }
763 $output .= theme('table', $header, $rows);
764
765 $output .= form_render($form);
766 return $output;
767 }
768
769 /**
770 * Menu callback; presents general node configuration options.
771 */
772 function node_configure() {
773
774 $form['default_nodes_main'] = array(
775 '#type' => 'select', '#title' => t('Number of posts on main page'), '#default_value' => variable_get('default_nodes_main', 10),
776 '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
777 '#description' => t('The default maximum number of posts to display per page on overview pages such as the main page.')
778 );
779
780 $form['teaser_length'] = array(
781 '#type' => 'select', '#title' => t('Length of trimmed posts'), '#default_value' => variable_get('teaser_length', 600),
782 '#options' => array(0 => t('Unlimited'), 200 => t('200 characters'), 400 => t('400 characters'), 600 => t('600 characters'),
783 800 => t('800 characters'), 1000 => t('1000 characters'), 1200 => t('1200 characters'), 1400 => t('1400 characters'),
784 1600 => t('1600 characters'), 1800 => t('1800 characters'), 2000 => t('2000 characters')),
785 '#description' => t("The maximum number of characters used in the trimmed version of a post. Drupal will use this setting to determine at which offset long posts should be trimmed. The trimmed version of a post is typically used as a teaser when displaying the post on the main page, in XML feeds, etc. To disable teasers, set to 'Unlimited'. Note that this setting will only affect new or updated content and will not affect existing teasers.")
786 );
787
788 $form['node_preview'] = array(
789 '#type' => 'radios', '#title' => t('Preview post'), '#default_value' => variable_get('node_preview', 0),
790 '#options' => array(t('Optional'), t('Required')), '#description' => t('Must users preview posts before submitting?')
791 );
792
793 return system_settings_form('node_configure', $form);
794 }
795
796 /**
797 * Retrieve the comment mode for the given node ID (none, read, or read/write).
798 */
799 function node_comment_mode($nid) {
800 static $comment_mode;
801 if (!isset($comment_mode[$nid])) {
802 $comment_mode[$nid] = db_result(db_query('SELECT comment FROM {node} WHERE nid = %d', $nid));
803 }
804 return $comment_mode[$nid];
805 }
806
807 /**
808 * Implementation of hook_link().
809 */
810 function node_link($type, $node = 0, $main = 0) {
811 $links = array();
812
813 if ($type == 'node') {
814 if ($main == 1 && $node->teaser && $node->readmore) {
815 $links[] = l(t('read more'), "node/$node->nid", array('title' => t('Read the rest of this posting.'), 'class' => 'read-more'));
816 }
817 }
818
819 return $links;
820 }
821
822 /**
823 * Implementation of hook_menu().
824 */
825 function node_menu($may_cache) {
826 $items = array();
827
828 if ($may_cache) {
829 $items[] = array('path' => 'admin/node', 'title' => t('content'),
830 'callback' => 'node_admin_nodes',
831 'access' => user_access('administer nodes'));
832 $items[] = array('path' => 'admin/node/overview', 'title' => t('list'),
833 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
834
835 if (module_exist('search')) {
836 $items[] = array('path' => 'admin/node/search', 'title' => t('search'),
837 'callback' => 'node_admin_search',
838 'access' => user_access('administer nodes'),
839 'type' => MENU_LOCAL_TASK);
840 }
841
842 $items[] = array('path' => 'admin/settings/node', 'title' => t('posts'),
843 'callback' => 'node_configure',
844 'access' => user_access('administer nodes'));
845 $items[] = array('path' => 'admin/settings/content-types', 'title' => t('content types'),
846 'callback' => 'node_types_configure',
847 'access' => user_access('administer nodes'));
848
849 $items[] = array('path' => 'node', 'title' => t('content'),
850 'callback' => 'node_page',
851 'access' => user_access('access content'),
852 'type' => MENU_MODIFIABLE_BY_ADMIN);
853 $items[] = array('path' => 'node/add', 'title' => t('create content'),
854 'callback' => 'node_page',
855 'access' => user_access('access content'),
856 'type' => MENU_ITEM_GROUPING,
857 'weight' => 1);
858 $items[] = array('path' => 'rss.xml', 'title' => t('rss feed'),
859 'callback' => 'node_feed',
860 'access' => user_access('access content'),
861 'type' => MENU_CALLBACK);
862 }
863 else {
864 if (arg(0) == 'node' && is_numeric(arg(1))) {
865 $node = node_load(arg(1));
866 if ($node->nid) {
867 $items[] = array('path' => 'node/'. arg(1), 'title' => t('view'),
868 'callback' => 'node_page',
869 'access' => node_access('view', $node),
870 'type' => MENU_CALLBACK);
871 $items[] = array('path' => 'node/'. arg(1) .'/view', 'title' => t('view'),
872 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
873 $items[] = array('path' => 'node/'. arg(1) .'/edit', 'title' => t('edit'),
874 'callback' => 'node_page',
875 'access' => node_access('update', $node),
876 'weight' => 1,
877 'type' => MENU_LOCAL_TASK);
878 $items[] = array('path' => 'node/'. arg(1) .'/delete', 'title' => t('delete'),
879 'callback' => 'node_delete_confirm',
880 'access' => node_access('delete', $node),
881 'weight' => 1,
882 'type' => MENU_CALLBACK);
883 $revisions_access = ((user_access('view revisions') || user_access('administer nodes')) && node_access('view', $node) && db_result(db_query('SELECT COUNT(vid) FROM {node_revisions} WHERE nid = %d', arg(1))) > 1);
884 $items[] = array('path' => 'node/'. arg(1) .'/revisions', 'title' => t('revisions'),
885 'callback' => 'node_revisions',
886 'access' => $revisions_access,
887 'weight' => 2,
888 'type' => MENU_LOCAL_TASK);
889 $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/delete',
890 'title' => t('revisions'),
891 'callback' => 'node_revisions',
892 'access' => $revisions_access,
893 'weight' => 2,
894 'type' => MENU_CALLBACK);
895 $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/revert',
896 'title' => t('revisions'),
897 'callback' => 'node_revisions',
898 'access' => $revisions_access,
899 'weight' => 2,
900 'type' => MENU_CALLBACK);
901 }
902 }
903 else if (arg(0) == 'admin' && arg(1) == 'settings' && arg(2) == 'content-types' && is_string(arg(3))) {
904 $items[] = array('path' => 'admin/settings/content-types/'. arg(3),
905 'title' => t("'%name' content type", array('%name' => node_get_name(arg(3)))),
906 'type' => MENU_CALLBACK);
907 }
908 }
909
910 return $items;
911 }
912
913 function node_last_changed($nid) {
914 $node = db_fetch_object(db_query('SELECT changed FROM {node} WHERE nid = %d', $nid));
915 return ($node->changed);
916 }
917
918 /**
919 * List node administration operations that can be performed.
920 */
921 function node_operations() {
922 $operations = array(
923 'approve' => array(t('Approve the selected posts'), 'UPDATE {node} SET status = 1, moderate = 0 WHERE nid = %d'),
924 'promote' => array(t('Promote the selected posts'), 'UPDATE {node} SET status = 1, promote = 1, moderate = 0 WHERE nid = %d'),
925 'sticky' => array(t('Make the selected posts sticky'), 'UPDATE {node} SET status = 1, sticky = 1 WHERE nid = %d'),
926 'demote' => array(t('Demote the selected posts'), 'UPDATE {node} SET promote = 0 WHERE nid = %d'),
927 'unpublish' => array(t('Unpublish the selected posts'), 'UPDATE {node} SET status = 0 WHERE nid = %d'),
928 'delete' => array(t('Delete the selected posts'), '')
929 );
930 return $operations;
931 }
932
933 /**
934 * List node administration filters that can be applied.
935 */
936 function node_filters() {
937 // Regular filters
938 $filters['status'] = array('title' => t('status'),
939 'options' => array('status-1' => t('published'), 'status-0' => t('not published'),
940 'moderate-1' => t('in moderation'), 'moderate-0' => t('not in moderation'),
941 'promote-1' => t('promoted'), 'promote-0' => t('not promoted'),
942 'sticky-1' => t('sticky'), 'sticky-0' => t('not sticky')));
943 $filters['type'] = array('title' => t('type'), 'options' => node_get_types());
944 // The taxonomy filter
945 if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
946 $filters['category'] = array('title' => t('category'), 'options' => $taxonomy);
947 }
948
949 return $filters;
950 }
951
952 /**
953 * Build query for node administration filters based on session.
954 */
955 function node_build_filter_query() {
956 $filters = node_filters();
957
958 // Build query
959 $where = $args = array();
960 $join = '';
961 foreach ($_SESSION['node_overview_filter'] as $index => $filter) {
962 list($key, $value) = $filter;
963 switch($key) {
964 case 'status':
965 // Note: no exploitable hole as $key/$value have already been checked when submitted
966 list($key, $value) = explode('-', $value, 2);
967 $where[] = 'n.'. $key .' = %d';
968 break;
969 case 'category':
970 $table = "tn$index";
971 $where[] = "$table.tid = %d";
972 $join .= "INNER JOIN {term_node} $table ON n.nid = $table.nid ";
973 break;
974 case 'type':
975 $where[] = "n.type = '%s'";
976 }
977 $args[] = $value;
978 }
979 $where = count($where) ? 'WHERE '. implode(' AND ', $where) : '';
980
981 return array('where' => $where, 'join' => $join, 'args' => $args);
982 }
983
984 /**
985 * Return form for node administration filters.
986 */
987 function node_filter_form() {
988 $session = &$_SESSION['node_overview_filter'];
989 $session = is_array($session) ? $session : array();
990 $filters = node_filters();
991
992 $i = 0;
993 $form['filters'] = array('#type' => 'fieldset',
994 '#title' => t('Show only items where'),
995 '#theme' => 'node_filters',
996 );
997 foreach ($session as $filter) {
998 list($type, $value) = $filter;
999 if ($type == 'category') {
1000 // Load term name from DB rather than search and parse options array.
1001 $value = module_invoke('taxonomy', 'get_term', $value);
1002 $value = $value->name;
1003 }
1004 else {
1005 $value = $filters[$type]['options'][$value];
1006 }
1007 $string = ($i++ ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');
1008 $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $value)));
1009 }
1010
1011 foreach ($filters as $key => $filter) {
1012 $names[$key] = $filter['title'];
1013 $form['filters']['status'][$key] = array('#type' => 'select', '#options' => $filter['options']);
1014 }
1015
1016 $form['filters']['filter'] = array('#type' => 'radios', '#options' => $names, '#default_value' => 'status');
1017 $form['filters']['buttons']['submit'] = array('#type' => 'submit', '#value' => (count($session) ? t('Refine') : t('Filter')));
1018 if (count($session)) {
1019 $form['filters']['buttons']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
1020 $form['filters']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
1021 }
1022
1023 return drupal_get_form('node_filter_form', $form);
1024 }
1025
1026 /**
1027 * Theme node administration filter form.
1028 */
1029 function theme_node_filter_form(&$form) {
1030 $output .= '<div id="node-admin-filter">';
1031 $output .= form_render($form['filters']);
1032 $output .= '</div>';
1033 $output .= form_render($form);
1034 return $output;
1035 }
1036
1037 /**
1038 * Theme node administraton filter selector.
1039 */
1040 function theme_node_filters(&$form) {
1041 $output .= '<ul>';
1042 if (sizeof($form['current'])) {
1043 foreach (element_children($form['current']) as $key) {
1044 $output .= '<li>' . form_render($form['current'][$key]) . '</li>';
1045 }
1046 }
1047
1048 $output .= '<li><dl class="multiselect">' . (sizeof($form['current']) ? '<dt><em>'. t('and') .'</em> '. t('where') .'</dt>' : '') . '<dd class="a">';
1049 foreach (element_children($form['filter']) as $key) {
1050 $output .= form_render($form['filter'][$key]);
1051 }
1052 $output .= '</dd>';
1053
1054 $output .= '<dt>'. t('is') .'</dt>' . '<dd class="b">';
1055
1056 foreach (element_children($form['status']) as $key)<