/[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.29 - (show annotations) (download) (as text)
Mon Jan 1 22:16:11 2007 UTC (2 years, 10 months ago) by killes
Branch: DRUPAL-4-7
Changes since 1.641.2.28: +1 -3 lines
File MIME type: text/x-php
#100399, remove phpdoc that does not apply, patch by Robert Douglass
1 <?php
2 // $Id: node.module,v 1.641.2.28 2007/01/01 18:28:34 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 * @return
260 * An array consisting ('#type' => name) pairs.
261 */
262 function node_get_types() {
263 return _node_names('list');
264 }
265
266 /**
267 * Determine whether a node hook exists.
268 *
269 * @param &$node
270 * Either a node object, node array, or a string containing the node type.
271 * @param $hook
272 * A string containing the name of the hook.
273 * @return
274 * TRUE iff the $hook exists in the node type of $node.
275 */
276 function node_hook(&$node, $hook) {
277 return module_hook(node_get_base($node), $hook);
278 }
279
280 /**
281 * Invoke a node hook.
282 *
283 * @param &$node
284 * Either a node object, node array, or a string containing the node type.
285 * @param $hook
286 * A string containing the name of the hook.
287 * @param $a2, $a3, $a4
288 * Arguments to pass on to the hook, after the $node argument.
289 * @return
290 * The returned value of the invoked hook.
291 */
292 function node_invoke(&$node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
293 if (node_hook($node, $hook)) {
294 $function = node_get_base($node) ."_$hook";
295 return ($function($node, $a2, $a3, $a4));
296 }
297 }
298
299 /**
300 * Invoke a hook_nodeapi() operation in all modules.
301 *
302 * @param &$node
303 * A node object.
304 * @param $op
305 * A string containing the name of the nodeapi operation.
306 * @param $a3, $a4
307 * Arguments to pass on to the hook, after the $node and $op arguments.
308 * @return
309 * The returned value of the invoked hooks.
310 */
311 function node_invoke_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
312 $return = array();
313 foreach (module_implements('nodeapi') as $name) {
314 $function = $name .'_nodeapi';
315 $result = $function($node, $op, $a3, $a4);
316 if (isset($result) && is_array($result)) {
317 $return = array_merge($return, $result);
318 }
319 else if (isset($result)) {
320 $return[] = $result;
321 }
322 }
323 return $return;
324 }
325
326 /**
327 * Load a node object from the database.
328 *
329 * @param $param
330 * Either the nid of the node or an array of conditions to match against in the database query
331 * @param $revision
332 * Which numbered revision to load. Defaults to the current version.
333 * @param $reset
334 * Whether to reset the internal node_load cache.
335 *
336 * @return
337 * A fully-populated node object.
338 */
339 function node_load($param = array(), $revision = NULL, $reset = NULL) {
340 static $nodes = array();
341
342 if ($reset) {
343 $nodes = array();
344 }
345
346 $cachable = ($revision == NULL);
347 $arguments = array();
348 if (is_numeric($param)) {
349 if ($cachable && isset($nodes[$param])) {
350 return is_object($nodes[$param]) ? drupal_clone($nodes[$param]) : $nodes[$param];
351 }
352 $cond = 'n.nid = %d';
353 $arguments[] = $param;
354 }
355 else {
356 // Turn the conditions into a query.
357 foreach ($param as $key => $value) {
358 $cond[] = 'n.'. db_escape_string($key) ." = '%s'";
359 $arguments[] = $value;
360 }
361 $cond = implode(' AND ', $cond);
362 }
363
364 // Retrieve the node.
365 // No db_rewrite_sql is applied so as to get complete indexing for search.
366 if ($revision) {
367 array_unshift($arguments, $revision);
368 $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));
369 }
370 else {
371 $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));
372 }
373
374 if ($node->nid) {
375 // Call the node specific callback (if any) and piggy-back the
376 // results to the node or overwrite some values.
377 if ($extra = node_invoke($node, 'load')) {
378 foreach ($extra as $key => $value) {
379 $node->$key = $value;
380 }
381 }
382
383 if ($extra = node_invoke_nodeapi($node, 'load')) {
384 foreach ($extra as $key => $value) {
385 $node->$key = $value;
386 }
387 }
388 if ($cachable) {
389 $nodes[$node->nid] = is_object($node) ? drupal_clone($node) : $node;
390 }
391 }
392
393 return $node;
394 }
395
396 /**
397 * Save a node object into the database.
398 */
399 function node_save(&$node) {
400 global $user;
401
402 $node->is_new = false;
403
404 // Apply filters to some default node fields:
405 if (empty($node->nid)) {
406 // Insert a new node.
407 $node->is_new = true;
408
409 $node->nid = db_next_id('{node}_nid');
410 $node->vid = db_next_id('{node_revisions}_vid');;
411 }
412 else {
413 // We need to ensure that all node fields are filled.
414 $node_current = node_load($node->nid);
415 foreach ($node as $field => $data) {
416 $node_current->$field = $data;
417 }
418 $node = $node_current;
419
420 if ($node->revision) {
421 $node->old_vid = $node->vid;
422 $node->vid = db_next_id('{node_revisions}_vid');
423 }
424 }
425
426 // Set some required fields:
427 if (empty($node->created)) {
428 $node->created = time();
429 }
430 // The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
431 $node->changed = time();
432
433 // Split off revisions data to another structure
434 $revisions_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
435 'title' => $node->title, 'body' => $node->body,
436 'teaser' => $node->teaser, 'log' => $node->log, 'timestamp' => $node->changed,
437 'uid' => $user->uid, 'format' => $node->format);
438 $revisions_table_types = array('nid' => '%d', 'vid' => '%d',
439 'title' => "'%s'", 'body' => "'%s'",
440 'teaser' => "'%s'", 'log' => "'%s'", 'timestamp' => '%d',
441 'uid' => '%d', 'format' => '%d');
442 $node_table_values = array('nid' => $node->nid, 'vid' => $node->vid,
443 'title' => $node->title, 'type' => $node->type, 'uid' => $node->uid,
444 'status' => $node->status, 'created' => $node->created,
445 'changed' => $node->changed, 'comment' => $node->comment,
446 'promote' => $node->promote, 'moderate' => $node->moderate,
447 'sticky' => $node->sticky);
448 $node_table_types = array('nid' => '%d', 'vid' => '%d',
449 'title' => "'%s'", 'type' => "'%s'", 'uid' => '%d',
450 'status' => '%d', 'created' => '%d',
451 'changed' => '%d', 'comment' => '%d',
452 'promote' => '%d', 'moderate' => '%d',
453 'sticky' => '%d');
454
455 //Generate the node table query and the
456 //the node_revisions table query
457 if ($node->is_new) {
458 $node_query = 'INSERT INTO {node} ('. implode(', ', array_keys($node_table_types)) .') VALUES ('. implode(', ', $node_table_types) .')';
459 $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
460 }
461 else {
462 $arr = array();
463 foreach ($node_table_types as $key => $value) {
464 $arr[] = $key .' = '. $value;
465 }
466 $node_table_values[] = $node->nid;
467 $node_query = 'UPDATE {node} SET '. implode(', ', $arr) .' WHERE nid = %d';
468 if ($node->revision) {
469 $revisions_query = 'INSERT INTO {node_revisions} ('. implode(', ', array_keys($revisions_table_types)) .') VALUES ('. implode(', ', $revisions_table_types) .')';
470 }
471 else {
472 $arr = array();
473 foreach ($revisions_table_types as $key => $value) {
474 $arr[] = $key .' = '. $value;
475 }
476 $revisions_table_values[] = $node->vid;
477 $revisions_query = 'UPDATE {node_revisions} SET '. implode(', ', $arr) .' WHERE vid = %d';
478 }
479 }
480
481 // Insert the node into the database:
482 db_query($node_query, $node_table_values);
483 db_query($revisions_query, $revisions_table_values);
484
485 // Call the node specific callback (if any):
486 if ($node->is_new) {
487 node_invoke($node, 'insert');
488 node_invoke_nodeapi($node, 'insert');
489 }
490 else {
491 node_invoke($node, 'update');
492 node_invoke_nodeapi($node, 'update');
493 }
494
495 // Clear the cache so an anonymous poster can see the node being added or updated.
496 cache_clear_all();
497 }
498
499 /**
500 * Generate a display of the given node.
501 *
502 * @param $node
503 * A node array or node object.
504 * @param $teaser
505 * Whether to display the teaser only, as on the main page.
506 * @param $page
507 * Whether the node is being displayed by itself as a page.
508 * @param $links
509 * Whether or not to display node links. Links are omitted for node previews.
510 *
511 * @return
512 * An HTML representation of the themed node.
513 */
514 function node_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE) {
515 $node = (object)$node;
516
517 // Remove the delimiter (if any) that separates the teaser from the body.
518 // TODO: this strips legitimate uses of '<!--break-->' also.
519 $node->body = str_replace('<!--break-->', '', $node->body);
520
521 if ($node->log != '' && !$teaser && $node->moderate) {
522 $node->body .= '<div class="log"><div class="title">'. t('Log') .':</div>'. filter_xss($node->log) .'</div>';
523 }
524
525 // The 'view' hook can be implemented to overwrite the default function
526 // to display nodes.
527 if (node_hook($node, 'view')) {
528 node_invoke($node, 'view', $teaser, $page);
529 }
530 else {
531 $node = node_prepare($node, $teaser);
532 }
533 // Allow modules to change $node->body before viewing.
534 node_invoke_nodeapi($node, 'view', $teaser, $page);
535 if ($links) {
536 $node->links = module_invoke_all('link', 'node', $node, !$page);
537 }
538 // unset unused $node part so that a bad theme can not open a security hole
539 if ($teaser) {
540 unset($node->body);
541 }
542 else {
543 unset($node->teaser);
544 }
545
546 return theme('node', $node, $teaser, $page);
547 }
548
549 /**
550 * Apply filters to a node in preparation for theming.
551 */
552 function node_prepare($node, $teaser = FALSE) {
553 $node->readmore = (strlen($node->teaser) < strlen($node->body));
554 if ($teaser == FALSE) {
555 $node->body = check_markup($node->body, $node->format, FALSE);
556 }
557 else {
558 $node->teaser = check_markup($node->teaser, $node->format, FALSE);
559 }
560 return $node;
561 }
562
563 /**
564 * Generate a page displaying a single node, along with its comments.
565 */
566 function node_show($node, $cid) {
567 $output = node_view($node, FALSE, TRUE);
568
569 if (function_exists('comment_render') && $node->comment) {
570 $output .= comment_render($node, $cid);
571 }
572
573 // Update the history table, stating that this user viewed this node.
574 node_tag_new($node->nid);
575
576 return $output;
577 }
578
579 /**
580 * Implementation of hook_perm().
581 */
582 function node_perm() {
583 return array('administer nodes', 'access content', 'view revisions', 'revert revisions');
584 }
585
586 /**
587 * Implementation of hook_search().
588 */
589 function node_search($op = 'search', $keys = null) {
590 switch ($op) {
591 case 'name':
592 return t('content');
593
594 case 'reset':
595 variable_del('node_cron_last');
596 variable_del('node_cron_last_nid');
597 return;
598
599 case 'status':
600 $last = variable_get('node_cron_last', 0);
601 $last_nid = variable_get('node_cron_last_nid', 0);
602 $total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1'));
603 $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));
604 return array('remaining' => $remaining, 'total' => $total);
605
606 case 'admin':
607 $form = array();
608 // Output form for defining rank factor weights.
609 $form['content_ranking'] = array('#type' => 'fieldset', '#title' => t('Content ranking'));
610 $form['content_ranking']['#theme'] = 'node_search_admin';
611 $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>');
612
613 $ranking = array('node_rank_relevance' => t('Keyword relevance'),
614 'node_rank_recent' => t('Recently posted'));
615 if (module_exist('comment')) {
616 $ranking['node_rank_comments'] = t('Number of comments');
617 }
618 if (module_exist('statistics') && variable_get('statistics_count_content_views', 0)) {
619 $ranking['node_rank_views'] = t('Number of views');
620 }
621
622 // Note: reversed to reflect that higher number = higher ranking.
623 $options = drupal_map_assoc(range(0, 10));
624 foreach ($ranking as $var => $title) {
625 $form['content_ranking']['factors'][$var] = array('#title' => $title, '#type' => 'select', '#options' => $options, '#default_value' => variable_get($var, 5));
626 }
627 return $form;
628
629 case 'search':
630 // Build matching conditions
631 list($join1, $where1) = _db_rewrite_sql();
632 $arguments1 = array();
633 $conditions1 = 'n.status = 1';
634
635 if ($type = search_query_extract($keys, 'type')) {
636 $types = array();
637 foreach (explode(',', $type) as $t) {
638 $types[] = "n.type = '%s'";
639 $arguments1[] = $t;
640 }
641 $conditions1 .= ' AND ('. implode(' OR ', $types) .')';
642 $keys = search_query_insert($keys, 'type');
643 }
644
645 if ($category = search_query_extract($keys, 'category')) {
646 $categories = array();
647 foreach (explode(',', $category) as $c) {
648 $categories[] = "tn.tid = %d";
649 $arguments1[] = $c;
650 }
651 $conditions1 .= ' AND ('. implode(' OR ', $categories) .')';
652 $join1 .= ' INNER JOIN {term_node} tn ON n.nid = tn.nid';
653 $keys = search_query_insert($keys, 'category');
654 }
655
656 // Build ranking expression (we try to map each parameter to a
657 // uniform distribution in the range 0..1).
658 $ranking = array();
659 $arguments2 = array();
660 $join2 = '';
661 $total = 0;
662 // Used to avoid joining on node_comment_statistics twice
663 $stats_join = false;
664 if ($weight = (int)variable_get('node_rank_relevance', 5)) {
665 // Average relevance values hover around 0.15
666 $ranking[] = '%d * i.relevance';
667 $arguments2[] = $weight;
668 $total += $weight;
669 }
670 if ($weight = (int)variable_get('node_rank_recent', 5)) {
671 // Exponential decay with half-life of 6 months, starting at last indexed node
672 $ranking[] = '%d * POW(2, (GREATEST(n.created, n.changed, c.last_comment_timestamp) - %d) * 6.43e-8)';
673 $arguments2[] = $weight;
674 $arguments2[] = (int)variable_get('node_cron_last', 0);
675 $join2 .= ' INNER JOIN {node} n ON n.nid = i.sid LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
676 $stats_join = true;
677 $total += $weight;
678 }
679 if (module_exist('comment') && $weight = (int)variable_get('node_rank_comments', 5)) {
680 // Inverse law that maps the highest reply count on the site to 1 and 0 to 0.
681 $scale = variable_get('node_cron_comments_scale', 0.0);
682 $ranking[] = '%d * (2.0 - 2.0 / (1.0 + c.comment_count * %f))';
683 $arguments2[] = $weight;
684 $arguments2[] = $scale;
685 if (!$stats_join) {
686 $join2 .= ' LEFT JOIN {node_comment_statistics} c ON c.nid = i.sid';
687 }
688 $total += $weight;
689 }
690 if (module_exist('statistics') && variable_get('statistics_count_content_views', 0) &&
691 $weight = (int)variable_get('node_rank_views', 5)) {
692 // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
693 $scale = variable_get('node_cron_views_scale', 0.0);
694 $ranking[] = '%d * (2.0 - 2.0 / (1.0 + nc.totalcount * %f))';
695 $arguments2[] = $weight;
696 $arguments2[] = $scale;
697 $join2 .= ' LEFT JOIN {node_counter} nc ON nc.nid = i.sid';
698 $total += $weight;
699 }
700 $select2 = (count($ranking) ? implode(' + ', $ranking) : 'i.relevance') . ' AS score';
701
702 // Do search
703 $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);
704
705 // Load results
706 $results = array();
707 foreach ($find as $item) {
708 $node = node_load($item->sid);
709
710 // Get node output (filtered and with module-specific fields).
711 if (node_hook($node, 'view')) {
712 node_invoke($node, 'view', false, false);
713 }
714 else {
715 $node = node_prepare($node, false);
716 }
717 // Allow modules to change $node->body before viewing.
718 node_invoke_nodeapi($node, 'view', false, false);
719
720 // Fetch comments for snippet
721 $node->body .= module_invoke('comment', 'nodeapi', $node, 'update index');
722 // Fetch terms for snippet
723 $node->body .= module_invoke('taxonomy', 'nodeapi', $node, 'update index');
724
725 $extra = node_invoke_nodeapi($node, 'search result');
726 $results[] = array('link' => url('node/'. $item->sid),
727 'type' => node_get_name($node),
728 'title' => $node->title,
729 'user' => theme('username', $node),
730 'date' => $node->changed,
731 'node' => $node,
732 'extra' => $extra,
733 'score' => $item->score / $total,
734 'snippet' => search_excerpt($keys, $node->body));
735 }
736 return $results;
737 }
738 }
739
740 /**
741 * Implementation of hook_user().
742 */
743 function node_user($op, &$edit, &$user) {
744 if ($op == 'delete') {
745 db_query('UPDATE {node} SET uid = 0 WHERE uid = %d', $user->uid);
746 db_query('UPDATE {node_revisions} SET uid = 0 WHERE uid = %d', $user->uid);
747 }
748 }
749
750 function theme_node_search_admin($form) {
751 $output = form_render($form['info']);
752
753 $header = array(t('Factor'), t('Weight'));
754 foreach (element_children($form['factors']) as $key) {
755 $row = array();
756 $row[] = $form['factors'][$key]['#title'];
757 unset($form['factors'][$key]['#title']);
758 $row[] = form_render($form['factors'][$key]);
759 $rows[] = $row;
760 }
761 $output .= theme('table', $header, $rows);
762
763 $output .= form_render($form);
764 return $output;
765 }
766
767 /**
768 * Menu callback; presents general node configuration options.
769 */
770 function node_configure() {
771
772 $form['default_nodes_main'] = array(
773 '#type' => 'select', '#title' => t('Number of posts on main page'), '#default_value' => variable_get('default_nodes_main', 10),
774 '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)),
775 '#description' => t('The default maximum number of posts to display per page on overview pages such as the main page.')
776 );
777
778 $form['teaser_length'] = array(
779 '#type' => 'select', '#title' => t('Length of trimmed posts'), '#default_value' => variable_get('teaser_length', 600),
780 '#options' => array(0 => t('Unlimited'), 200 => t('200 characters'), 400 => t('400 characters'), 600 => t('600 characters'),
781 800 => t('800 characters'), 1000 => t('1000 characters'), 1200 => t('1200 characters'), 1400 => t('1400 characters'),
782 1600 => t('1600 characters'), 1800 => t('1800 characters'), 2000 => t('2000 characters')),
783 '#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.")
784 );
785
786 $form['node_preview'] = array(
787 '#type' => 'radios', '#title' => t('Preview post'), '#default_value' => variable_get('node_preview', 0),
788 '#options' => array(t('Optional'), t('Required')), '#description' => t('Must users preview posts before submitting?')
789 );
790
791 return system_settings_form('node_configure', $form);
792 }
793
794 /**
795 * Retrieve the comment mode for the given node ID (none, read, or read/write).
796 */
797 function node_comment_mode($nid) {
798 static $comment_mode;
799 if (!isset($comment_mode[$nid])) {
800 $comment_mode[$nid] = db_result(db_query('SELECT comment FROM {node} WHERE nid = %d', $nid));
801 }
802 return $comment_mode[$nid];
803 }
804
805 /**
806 * Implementation of hook_link().
807 */
808 function node_link($type, $node = 0, $main = 0) {
809 $links = array();
810
811 if ($type == 'node') {
812 if ($main == 1 && $node->teaser && $node->readmore) {
813 $links[] = l(t('read more'), "node/$node->nid", array('title' => t('Read the rest of this posting.'), 'class' => 'read-more'));
814 }
815 }
816
817 return $links;
818 }
819
820 /**
821 * Implementation of hook_menu().
822 */
823 function node_menu($may_cache) {
824 $items = array();
825
826 if ($may_cache) {
827 $items[] = array('path' => 'admin/node', 'title' => t('content'),
828 'callback' => 'node_admin_nodes',
829 'access' => user_access('administer nodes'));
830 $items[] = array('path' => 'admin/node/overview', 'title' => t('list'),
831 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
832
833 if (module_exist('search')) {
834 $items[] = array('path' => 'admin/node/search', 'title' => t('search'),
835 'callback' => 'node_admin_search',
836 'access' => user_access('administer nodes'),
837 'type' => MENU_LOCAL_TASK);
838 }
839
840 $items[] = array('path' => 'admin/settings/node', 'title' => t('posts'),
841 'callback' => 'node_configure',
842 'access' => user_access('administer nodes'));
843 $items[] = array('path' => 'admin/settings/content-types', 'title' => t('content types'),
844 'callback' => 'node_types_configure',
845 'access' => user_access('administer nodes'));
846
847 $items[] = array('path' => 'node', 'title' => t('content'),
848 'callback' => 'node_page',
849 'access' => user_access('access content'),
850 'type' => MENU_MODIFIABLE_BY_ADMIN);
851 $items[] = array('path' => 'node/add', 'title' => t('create content'),
852 'callback' => 'node_page',
853 'access' => user_access('access content'),
854 'type' => MENU_ITEM_GROUPING,
855 'weight' => 1);
856 $items[] = array('path' => 'rss.xml', 'title' => t('rss feed'),
857 'callback' => 'node_feed',
858 'access' => user_access('access content'),
859 'type' => MENU_CALLBACK);
860 }
861 else {
862 if (arg(0) == 'node' && is_numeric(arg(1))) {
863 $node = node_load(arg(1));
864 if ($node->nid) {
865 $items[] = array('path' => 'node/'. arg(1), 'title' => t('view'),
866 'callback' => 'node_page',
867 'access' => node_access('view', $node),
868 'type' => MENU_CALLBACK);
869 $items[] = array('path' => 'node/'. arg(1) .'/view', 'title' => t('view'),
870 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
871 $items[] = array('path' => 'node/'. arg(1) .'/edit', 'title' => t('edit'),
872 'callback' => 'node_page',
873 'access' => node_access('update', $node),
874 'weight' => 1,
875 'type' => MENU_LOCAL_TASK);
876 $items[] = array('path' => 'node/'. arg(1) .'/delete', 'title' => t('delete'),
877 'callback' => 'node_delete_confirm',
878 'access' => node_access('delete', $node),
879 'weight' => 1,
880 'type' => MENU_CALLBACK);
881 $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);
882 $items[] = array('path' => 'node/'. arg(1) .'/revisions', 'title' => t('revisions'),
883 'callback' => 'node_revisions',
884 'access' => $revisions_access,
885 'weight' => 2,
886 'type' => MENU_LOCAL_TASK);
887 $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/delete',
888 'title' => t('revisions'),
889 'callback' => 'node_revisions',
890 'access' => $revisions_access,
891 'weight' => 2,
892 'type' => MENU_CALLBACK);
893 $items[] = array('path' => 'node/'. arg(1) .'/revisions/' . arg(3) . '/revert',
894 'title' => t('revisions'),
895 'callback' => 'node_revisions',
896 'access' => $revisions_access,
897 'weight' => 2,
898 'type' => MENU_CALLBACK);
899 }
900 }
901 else if (arg(0) == 'admin' && arg(1) == 'settings' && arg(2) == 'content-types' && is_string(arg(3))) {
902 $items[] = array('path' => 'admin/settings/content-types/'. arg(3),
903 'title' => t("'%name' content type", array('%name' => node_get_name(arg(3)))),
904 'type' => MENU_CALLBACK);
905 }
906 }
907
908 return $items;
909 }
910
911 function node_last_changed($nid) {
912 $node = db_fetch_object(db_query('SELECT changed FROM {node} WHERE nid = %d', $nid));
913 return ($node->changed);
914 }
915
916 /**
917 * List node administration operations that can be performed.
918 */
919 function node_operations() {
920 $operations = array(
921 'approve' => array(t('Approve the selected posts'), 'UPDATE {node} SET status = 1, moderate = 0 WHERE nid = %d'),
922 'promote' => array(t('Promote the selected posts'), 'UPDATE {node} SET status = 1, promote = 1, moderate = 0 WHERE nid = %d'),
923 'sticky' => array(t('Make the selected posts sticky'), 'UPDATE {node} SET status = 1, sticky = 1 WHERE nid = %d'),
924 'demote' => array(t('Demote the selected posts'), 'UPDATE {node} SET promote = 0 WHERE nid = %d'),
925 'unpublish' => array(t('Unpublish the selected posts'), 'UPDATE {node} SET status = 0 WHERE nid = %d'),
926 'delete' => array(t('Delete the selected posts'), '')
927 );
928 return $operations;
929 }
930
931 /**
932 * List node administration filters that can be applied.
933 */
934 function node_filters() {
935 // Regular filters
936 $filters['status'] = array('title' => t('status'),
937 'options' => array('status-1' => t('published'), 'status-0' => t('not published'),
938 'moderate-1' => t('in moderation'), 'moderate-0' => t('not in moderation'),
939 'promote-1' => t('promoted'), 'promote-0' => t('not promoted'),
940 'sticky-1' => t('sticky'), 'sticky-0' => t('not sticky')));
941 $filters['type'] = array('title' => t('type'), 'options' => node_get_types());
942 // The taxonomy filter
943 if ($taxonomy = module_invoke('taxonomy', 'form_all', 1)) {
944 $filters['category'] = array('title' => t('category'), 'options' => $taxonomy);
945 }
946
947 return $filters;
948 }
949
950 /**
951 * Build query for node administration filters based on session.
952 */
953 function node_build_filter_query() {
954 $filters = node_filters();
955
956 // Build query
957 $where = $args = array();
958 $join = '';
959 foreach ($_SESSION['node_overview_filter'] as $index => $filter) {
960 list($key, $value) = $filter;
961 switch($key) {
962 case 'status':
963 // Note: no exploitable hole as $key/$value have already been checked when submitted
964 list($key, $value) = explode('-', $value, 2);
965 $where[] = 'n.'. $key .' = %d';
966 break;
967 case 'category':
968 $table = "tn$index";
969 $where[] = "$table.tid = %d";
970 $join .= "INNER JOIN {term_node} $table ON n.nid = $table.nid ";
971 break;
972 case 'type':
973 $where[] = "n.type = '%s'";
974 }
975 $args[] = $value;
976 }
977 $where = count($where) ? 'WHERE '. implode(' AND ', $where) : '';
978
979 return array('where' => $where, 'join' => $join, 'args' => $args);
980 }
981
982 /**
983 * Return form for node administration filters.
984 */
985 function node_filter_form() {
986 $session = &$_SESSION['node_overview_filter'];
987 $session = is_array($session) ? $session : array();
988 $filters = node_filters();
989
990 $i = 0;
991 $form['filters'] = array('#type' => 'fieldset',
992 '#title' => t('Show only items where'),
993 '#theme' => 'node_filters',
994 );
995 foreach ($session as $filter) {
996 list($type, $value) = $filter;
997 if ($type == 'category') {
998 // Load term name from DB rather than search and parse options array.
999 $value = module_invoke('taxonomy', 'get_term', $value);
1000 $value = $value->name;
1001 }
1002 else {
1003 $value = $filters[$type]['options'][$value];
1004 }
1005 $string = ($i++ ? '<em>and</em> where <strong>%a</strong> is <strong>%b</strong>' : '<strong>%a</strong> is <strong>%b</strong>');
1006 $form['filters']['current'][] = array('#value' => t($string, array('%a' => $filters[$type]['title'] , '%b' => $value)));
1007 }
1008
1009 foreach ($filters as $key => $filter) {
1010 $names[$key] = $filter['title'];
1011 $form['filters']['status'][$key] = array('#type' => 'select', '#options' => $filter['options']);
1012 }
1013
1014 $form['filters']['filter'] = array('#type' => 'radios', '#options' => $names, '#default_value' => 'status');
1015 $form['filters']['buttons']['submit'] = array('#type' => 'submit', '#value' => (count($session) ? t('Refine') : t('Filter')));
1016 if (count($session)) {
1017 $form['filters']['buttons']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
1018 $form['filters']['buttons']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
1019 }
1020
1021 return drupal_get_form('node_filter_form', $form);
1022 }
1023
1024 /**
1025 * Theme node administration filter form.
1026 */
1027 function theme_node_filter_form(&$form) {
1028 $output .= '<div id="node-admin-filter">';
1029 $output .= form_render($form['filters']);
1030 $output .= '</div>';
1031 $output .= form_render($form);
1032 return $output;
1033 }
1034
1035 /**
1036 * Theme node administraton filter selector.
1037 */
1038 function theme_node_filters(&$form) {
1039 $output .= '<ul>';
1040 if (sizeof($form['current'])) {
1041 foreach (element_children($form['current']) as $key) {
1042 $output .= '<li>' . form_render($form['current'][$key]) . '</li>';
1043 }
1044 }
1045
1046 $output .= '<li><dl class="multiselect">' . (sizeof($form['current']) ? '<dt><em>'. t('and') .'</em> '. t('where') .'</dt>' : '') . '<dd class="a">';
1047 foreach (element_children($form['filter']) as $key) {
1048 $output .= form_render($form['filter'][$key]);
1049 }
1050 $output .= '</dd>';
1051
1052 $output .= '<dt>'. t('is') .'</dt>' . '<dd class="b">';
1053
1054 foreach (element_children($form['status']) as $key) {
1055 $output .= form_render(