drupal/modules/node.module

1897 lines
64 KiB
Plaintext
Raw Normal View History

<?php
// $Id$
/**
* @file
* The core that allows content to be submitted to the site.
*/
define('NODE_NEW_LIMIT', time() - 30 * 24 * 60 * 60);
/**
* Implementation of hook_help().
*/
function node_help($section) {
switch ($section) {
case 'admin/help#node':
$output = t("
<h3>Nodes</h3>
<p>The core of the Drupal system is the node. All of the contents of the system are placed in nodes, or extensions of nodes.
A base node contains:<dl>
<dt>A Title</dt><dd>Up to 128 characters of text that titles the node.</dd>
<dt>A Teaser</dt><dd>A small block of text that is meant to get you interested in the rest of node. Drupal will automatically pull a small amount of the body of the node to make the teaser (To configure how long the teaser will be <a href=\"%teaser\">click here</a>). The teaser can be changed if you don't like what Drupal grabs.</dd>
<dt>The Body</dt><dd>The main text that comprises your content.</dd>
<dt>A Type</dt><dd>What kind of node is this? Blog, book, forum, comment, unextended, etc.</dd>
<dt>An Author</dt><dd>The author's name. It will either be \"anonymous\" or a valid user. You <em>cannot</em> set it to an arbitrary value.</dd>
<dt>Authored on</dt><dd>The date the node was written.</dd>
<dt>Changed</dt><dd>The last time this node was changed.</dd>
<dt>Sticky at top of lists</dt><dd>In listings such as the frontpage or a taxonomy overview the teasers of a selected amount of nodes is displayed. If you want to force a node to appear on the top of such a listing, you must set it to 'sticky'. This way it will float to the top of a listing, and it will not be pushed down by newer content.
<dt>Allow user comments</dt><dd>A node can have comments. These comments can be written by other users (Read-write), or only by admins (Read-only).</dd>
<dt>Revisions</dt><dd>Drupal has a revision system so that you can \"roll back\" to an older version of a post if the new version is not what you want.</dd>
<dt>Promote to front page</dt><dd>To get people to look at the new stuff on your site you can choose to move it to the front page. The front page is configured to show the teasers from only a few of the total nodes you have on your site (To configure how many teasers <a href=\"%teaser\">click here</a>).</dd>
<dt>Published</dt><dd>When using Drupal's moderation system a node remains unpublished -- unavailable to non-moderators -- until it is marked Published.</dd></dl>
<p>Now that you know what is in a node, here are some of the types of nodes available.</p>", array("%teaser" => url("admin/node/configure/settings")));
foreach (node_list() as $type) {
$output .= '<h3>'. t('Node type: %module', array('%module' => node_invoke($type, 'node_name'))). '</h3>';
$output .= implode("\n", module_invoke_all('help', 'node/add#'. $type));
}
return $output;
case 'admin/modules#description':
return t('The core that allows content to be submitted to the site.');
case 'admin/node/configure':
case 'admin/node/configure/settings':
return t('<p>Settings for the core of Drupal. Almost everything is a node so these settings will affect most of the site.</p>');
case 'admin/node':
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>).<br />Clicking a title views the post, while clicking an author\'s name edits their user information.<br />Other post-related tasks are available from the menu.</p>', array('%comments' => url('admin/comment')));
case 'admin/node/search':
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>');
case 'admin/node/configure/defaults':
return t('<p>This page lets you set the defaults used during creation of nodes for all the different node types.<br /><em>comment:</em> Read/write setting for comments.<br /><em>publish:</em> Is this post publicly viewable, has it been published?<br /><em>promote:</em> Is this post to be promoted to the front page?<br /><em>moderate:</em> Does this post need approval before it can be viewed?<br /><em>sticky:</em> Is this post always visible at the top of lists?<br /><em>revision:</em> Will this post go into the revision system allowing multiple versions to be saved?</p>');
}
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'revisions') {
return t('The revisions let you track differences between multiple versions of a post.');
}
}
/**
* Implementation of hook_cron().
*/
function node_cron() {
db_query('DELETE FROM {history} WHERE timestamp < %d', NODE_NEW_LIMIT);
}
/**
* Gather a listing of links to nodes.
*
* @param $result
* 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.
* field to be set.
* @param $title
* A heading for the resulting list.
*
* @return
* An HTML list suitable as content for a block.
*/
function node_title_list($result, $title = NULL) {
while ($node = db_fetch_object($result)) {
$items[] = l($node->title, 'node/'. $node->nid, $node->comment_count ? array('title' => format_plural($node->comment_count, '1 comment', '%count comments')) : '');
}
return theme('node_list', $items, $title);
}
/**
* Format a listing of links to nodes.
*/
function theme_node_list($items, $title = NULL) {
return theme('item_list', $items, $title);
}
/**
* Update the 'last viewed' timestamp of the specified node for current user.
*/
function node_tag_new($nid) {
global $user;
if ($user->uid) {
if (node_last_viewed($nid)) {
db_query('UPDATE {history} SET timestamp = %d WHERE uid = %d AND nid = %d', time(), $user->uid, $nid);
}
else {
@db_query('INSERT INTO {history} (uid, nid, timestamp) VALUES (%d, %d, %d)', $user->uid, $nid, time());
}
}
}
/**
* Retrieves the timestamp at which the current user last viewed the
* specified node.
*/
function node_last_viewed($nid) {
global $user;
static $history;
if (!isset($history[$nid])) {
$history[$nid] = db_fetch_object(db_query("SELECT timestamp FROM {history} WHERE uid = '$user->uid' AND nid = %d", $nid));
}
return ($history[$nid]->timestamp ? $history[$nid]->timestamp : 0);
}
/**
* Determine whether the supplied timestamp is newer than the user's last view
* of a given node.
*
* @param $nid
* Node ID whose history supplies the "last viewed" timestamp.
* @param $timestamp
* Time which is compared against node's "last viewed" timestamp.
*/
function node_is_new($nid, $timestamp) {
global $user;
static $cache;
if (!isset($cache[$nid])) {
if ($user->uid) {
$cache[$nid] = node_last_viewed($nid);
}
else {
$cache[$nid] = time();
}
}
return ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT);
}
/**
* Automatically generate a teaser for the given body text.
*/
function node_teaser($body) {
$size = variable_get('teaser_length', 600);
// find where the delimiter is in the body
$delimiter = strpos($body, '<!--break-->');
// If the size is zero, and there is no delimiter, we return the entire body.
if ($size == 0 && $delimiter == 0) {
return $body;
}
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
// If the body contains PHP code, do not split it up to prevent parse errors.
if (strpos($body, '<?') != false) {
return $body;
}
// If a valid delimiter has been specified, use it to chop of the teaser.
if ($delimiter > 0) {
return substr($body, 0, $delimiter);
}
// If we have a short body, return the entire body.
if (strlen($body) < $size) {
return $body;
}
// In some cases, no delimiter has been specified (e.g. when posting using
// the Blogger API). In this case, we try to split at paragraph boundaries.
if ($length = strpos($body, '</p>', $size)) {
return substr($body, 0, $length + 4);
}
if ($length = strpos($body, '<br />', $size)) {
return substr($body, 0, $length);
}
if ($length = strpos($body, '<br>', $size)) {
return substr($body, 0, $length);
}
if ($length = strpos($body, "\n", $size)) {
return substr($body, 0, $length);
}
// When even the first paragraph is too long, try to split at the end of
// the next sentence.
if ($length = strpos($body, '. ', $size)) {
return substr($body, 0, $length + 1);
}
if ($length = strpos($body, '! ', $size)) {
return substr($body, 0, $length + 1);
}
if ($length = strpos($body, '? ', $size)) {
return substr($body, 0, $length + 1);
}
if ($length = strpos($body, '。', $size)) {
return substr($body, 0, $length + 1);
}
if ($length = strpos($body, '、', $size)) {
return substr($body, 0, $length + 1);
}
if ($length = strpos($body, '؟ ', $size)) {
return substr($body, 0, $length + 1);
}
// If all else fails, simply truncate the string.
return truncate_utf8($body, $size);
}
/**
* Determine the module that defines the node type of the given node.
*
* @param &$node
* Either a node object, a node array, or a string containing the node type.
* @return
* A string containing the name of the defining module.
*/
function node_get_module_name($node) {
if (is_array($node)) {
if ($pos = strpos($node['type'], '-')) {
return substr($node['type'], 0, $pos);
}
else {
return $node['type'];
}
}
else if (is_object($node)) {
if ($pos = strpos($node->type, '-')) {
return substr($node->type, 0, $pos);
}
else {
return $node->type;
}
}
else if (is_string($node)) {
if ($pos = strpos($node, '-')) {
return substr($node, 0, $pos);
}
else {
return $node;
}
}
}
/**
* Get a list of all the defined node types.
*
* @return
* A list of all node types.
*/
function node_list() {
$types = array();
foreach (module_list() as $module) {
if (module_hook($module, 'node_name')) {
$module_types = module_invoke($module, 'node_types');
if ($module_types) {
foreach ($module_types as $type) {
$types[] = $type;
}
}
else {
$types[] = $module;
}
}
}
return $types;
}
/**
* Determine whether a node hook exists.
*
* @param &$node
* Either a node object, node array, or a string containing the node type.
* @param $hook
* A string containing the name of the hook.
* @return
* TRUE iff the $hook exists in the node type of $node.
*/
function node_hook(&$node, $hook) {
$function = node_get_module_name($node) ."_$hook";
return function_exists($function);
}
/**
* Invoke a node hook.
*
* @param &$node
* Either a node object, node array, or a string containing the node type.
* @param $hook
* A string containing the name of the hook.
* @param $a2, $a3, $a4
* Arguments to pass on to the hook, after the $node argument.
* @return
* The returned value of the invoked hook.
*/
function node_invoke(&$node, $hook, $a2 = NULL, $a3 = NULL, $a4 = NULL) {
$function = node_get_module_name($node) ."_$hook";
if (function_exists($function)) {
return ($function($node, $a2, $a3, $a4));
}
}
/**
* Invoke a hook_nodeapi() operation in all modules.
*
* @param &$node
* Either a node object, node array, or a string containing the node type.
* @param $op
* A string containing the name of the nodeapi operation.
* @param $a3, $a4
* Arguments to pass on to the hook, after the $node and $op arguments.
* @return
* The returned value of the invoked hooks.
*/
function node_invoke_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
$return = array();
foreach (module_list() as $name) {
$function = $name .'_nodeapi';
if (function_exists($function)) {
$result = $function($node, $op, $a3, $a4);
if (is_array($result)) {
$return = array_merge($return, $result);
}
2004-08-23 00:44:02 +00:00
else if (isset($result)) {
$return[] = $result;
}
}
}
return $return;
}
/**
* Load a node object from the database.
*
* @param $conditions
* An array of conditions to match against in the database query. Most calls
* will simply use array('nid' => 52).
* @param $revision
* Which numbered revision to load. Defaults to the current version.
* @param $reset
* Whether to reset the internal node_load cache.
*
* @return
* A fully-populated node object.
*/
function node_load($conditions, $revision = NULL, $reset = NULL) {
static $nodes = array();
if ($reset) {
$nodes = array();
}
$cachable = (count($conditions) == 1 && isset($conditions['nid']) && $revision == NULL);
if ($cachable && isset($nodes[$conditions['nid']])) {
return $nodes[$conditions['nid']];
}
// Turn the conditions into a query.
foreach ($conditions as $key => $value) {
$cond[] = 'n.'. db_escape_string($key) ." = '". db_escape_string($value) ."'";
}
// Retrieve the node.
$node = db_fetch_object(db_query('SELECT n.*, u.uid, u.name, u.picture, u.data FROM {node} n INNER JOIN {users} u ON u.uid = n.uid WHERE '. implode(' AND ', $cond)));
$node = drupal_unpack($node);
// Unserialize the revisions and user data fields.
if ($node->revisions) {
$node->revisions = unserialize($node->revisions);
}
// Call the node specific callback (if any) and piggy-back the
// results to the node or overwrite some values.
if ($extra = node_invoke($node, 'load')) {
foreach ($extra as $key => $value) {
$node->$key = $value;
}
}
if ($extra = node_invoke_nodeapi($node, 'load')) {
foreach ($extra as $key => $value) {
$node->$key = $value;
}
}
// Return the desired revision.
if (!is_null($revision) && is_array($node->revisions[$revision])) {
$node = $node->revisions[$revision]['node'];
}
if ($cachable) {
$nodes[$conditions['nid']] = $node;
}
return $node;
}
/**
* Save a node object into the database.
*/
function node_save($node) {
// Fetch fields to save to node table:
$fields = node_invoke_nodeapi($node, 'fields');
// Serialize the revisions field:
if ($node->revisions) {
$node->revisions = serialize($node->revisions);
}
// Apply filters to some default node fields:
if (empty($node->nid)) {
// Insert a new node.
// Set some required fields:
2002-09-27 16:49:19 +00:00
if (!$node->created) {
$node->created = time();
}
if (!$node->changed) {
$node->changed = time();
}
$node->nid = db_next_id('{node}_nid');
// Prepare the query:
foreach ($node as $key => $value) {
if (in_array((string) $key, $fields)) {
$k[] = db_escape_string($key);
$v[] = $value;
$s[] = "'%s'";
}
}
$keysfmt = implode(', ', $s);
// We need to quote the placeholders for the values.
$valsfmt = "'". implode("', '", $s) ."'";
// Insert the node into the database:
db_query("INSERT INTO {node} (". implode(", ", $k) .") VALUES(". implode(", ", $s) .")", $v);
// Call the node specific callback (if any):
node_invoke($node, 'insert');
node_invoke_nodeapi($node, 'insert');
}
else {
// Update an existing node.
// Set some required fields:
$node->changed = time();
// Prepare the query:
foreach ($node as $key => $value) {
if (in_array($key, $fields)) {
$q[] = db_escape_string($key) ." = '%s'";
$v[] = $value;
}
}
// Update the node in the database:
db_query("UPDATE {node} SET ". implode(', ', $q) ." WHERE nid = '$node->nid'", $v);
// Call the node specific callback (if any):
node_invoke($node, 'update');
node_invoke_nodeapi($node, 'update');
}
// Clear the cache so an anonymous poster can see the node being added or updated.
cache_clear_all();
// Return the node ID:
return $node->nid;
}
/**
* Generate a display of the given node.
*
* @param $node
* A node array or node object.
* @param $teaser
* Whether to display only the teaser for the node.
* @param $page
* Whether the node is being displayed by itself as a page.
* @param $links
* Whether or not to display node links. Links are omitted for node previews.
*
* @return
* An HTML representation of the themed node.
*/
function node_view($node, $teaser = FALSE, $page = FALSE, $links = TRUE) {
- import.module: + Improved input filtering; this should make the news items look more consistent in terms of mark-up. + Quoted all array indices: converted all instances of $foo[bar] to $foo["bar"]. Made various other changes to make the import module compliant with the coding style. - theme.inc: + Fixed small XHTML glitch - comment system: + Made it possible for users to edit their comments (when certain criteria are matched). + Renamed the SQL table field "lid" to "nid" and updated the code to reflect this change: this is a rather /annoying/ change that has been asked for a few times. It will impact the contributed BBS/forum modules and requires a tiny SQL update: sql> ALTER TABLE comments CHANGE lid nid int(10) NOT NULL; + Moved most (all?) of the comment related logic from node.php to comment.module where it belongs. This also marks a first step towards removing/reducing "node.php". + Added a delete button to the comment admin form and made it so that Drupal prompts for confirmation prior to deleting a comment from the database. This behavior is similar to that of deleting nodes. + Disabled comment moderation for now. + Some of the above changes will make it easier to integrate the upcomcing mail-to-web and web-to-mail gateways. They are part of a bigger plan. ;) - node system: + Made it so that updating nodes (like for instance updating blog entries) won't trigger the submission rate throttle. + Fixed a small glitch where a node's title wasn't always passed to the $theme->header() function. + Made "node_array()" and "node_object()" more generic and named them "object2array()" and "array2object()". + Moved most (all?) of the comment related logic from node.php to comment.module where it belongs. This also marks a first step towards removing/reducing "node.php". - misc: + Applied three patches by Foxen. One to improve performance of the book module, and two other patches to fix small glitches in common.inc. Thanks Foxen!
2001-12-30 16:16:38 +00:00
$node = array2object($node);
// Remove the delimiter (if any) that separates the teaser from the body.
// TODO: this strips legitimate uses of '<!--break-->' also.
$node->body = str_replace('<!--break-->', '', $node->body);
// The 'view' hook can be implemented to overwrite the default function
// to display nodes.
if (node_hook($node, 'view')) {
- Patch #5347 by JonBob: Here's a new patch that unifies the node/52 and book/view/52 paths for nodes. It involves a small change to hook_view(), which is discussed first: Currently hook_view() expects node modules to return a themed node. However, each module does this the same way; they modify $node as necessary, then call theme('node', $node) and return the result. We can refactor this so that the calling function node_view() calls theme('node') instead. By doing this, it becomes possible for hook_nodeapi('view') to be called after hook_view() where the node contents are filtered, and before theme('node') where the body is enclosed in other HTML. This way the book module can insert its navigation into the body right before the theming. Advantages of this refactoring: - I can use it for book.module to remove the extra viewing path. - The function of hook_nodeapi('view') becomes more like hook_view(), as neither will expect a return value. - We more closely follow the flow of other nodeapi calls, which usually directly follow their corresponding specific node type hooks (instead of preceding them). - The attachment.module people could use it to append their attachments in a list after the node. - Gabor could use it instead of his filter perversion for his "articles in a series" module. - A little less code in each view hook. - The content hook is no longer needed, so that means even less code. Disadvantages: - Any modules written to use nodeapi('view') could be affected (but these would all be post-4.4 modules). - Implementations of hook_view() would need to be updated (but return values would be ignored, so most would work without updates anyway). Now the patch takes advantage of this API shift to inject its navigation at the end of all book nodes, regardless of the viewing path. In fact, since the paths become identical, I've removed the book/view handler entirely. We should probably provide an .htaccess rewrite for this (one is still needed for node/view/nn anyway). At the same time, there is a check in book_block() that shows the block appropriately on these pages.
2004-07-30 13:37:26 +00:00
node_invoke($node, 'view', $teaser, $page);
}
else {
- Patch #5347 by JonBob: Here's a new patch that unifies the node/52 and book/view/52 paths for nodes. It involves a small change to hook_view(), which is discussed first: Currently hook_view() expects node modules to return a themed node. However, each module does this the same way; they modify $node as necessary, then call theme('node', $node) and return the result. We can refactor this so that the calling function node_view() calls theme('node') instead. By doing this, it becomes possible for hook_nodeapi('view') to be called after hook_view() where the node contents are filtered, and before theme('node') where the body is enclosed in other HTML. This way the book module can insert its navigation into the body right before the theming. Advantages of this refactoring: - I can use it for book.module to remove the extra viewing path. - The function of hook_nodeapi('view') becomes more like hook_view(), as neither will expect a return value. - We more closely follow the flow of other nodeapi calls, which usually directly follow their corresponding specific node type hooks (instead of preceding them). - The attachment.module people could use it to append their attachments in a list after the node. - Gabor could use it instead of his filter perversion for his "articles in a series" module. - A little less code in each view hook. - The content hook is no longer needed, so that means even less code. Disadvantages: - Any modules written to use nodeapi('view') could be affected (but these would all be post-4.4 modules). - Implementations of hook_view() would need to be updated (but return values would be ignored, so most would work without updates anyway). Now the patch takes advantage of this API shift to inject its navigation at the end of all book nodes, regardless of the viewing path. In fact, since the paths become identical, I've removed the book/view handler entirely. We should probably provide an .htaccess rewrite for this (one is still needed for node/view/nn anyway). At the same time, there is a check in book_block() that shows the block appropriately on these pages.
2004-07-30 13:37:26 +00:00
$node = node_prepare($node, $teaser);
}
- Patch #5347 by JonBob: Here's a new patch that unifies the node/52 and book/view/52 paths for nodes. It involves a small change to hook_view(), which is discussed first: Currently hook_view() expects node modules to return a themed node. However, each module does this the same way; they modify $node as necessary, then call theme('node', $node) and return the result. We can refactor this so that the calling function node_view() calls theme('node') instead. By doing this, it becomes possible for hook_nodeapi('view') to be called after hook_view() where the node contents are filtered, and before theme('node') where the body is enclosed in other HTML. This way the book module can insert its navigation into the body right before the theming. Advantages of this refactoring: - I can use it for book.module to remove the extra viewing path. - The function of hook_nodeapi('view') becomes more like hook_view(), as neither will expect a return value. - We more closely follow the flow of other nodeapi calls, which usually directly follow their corresponding specific node type hooks (instead of preceding them). - The attachment.module people could use it to append their attachments in a list after the node. - Gabor could use it instead of his filter perversion for his "articles in a series" module. - A little less code in each view hook. - The content hook is no longer needed, so that means even less code. Disadvantages: - Any modules written to use nodeapi('view') could be affected (but these would all be post-4.4 modules). - Implementations of hook_view() would need to be updated (but return values would be ignored, so most would work without updates anyway). Now the patch takes advantage of this API shift to inject its navigation at the end of all book nodes, regardless of the viewing path. In fact, since the paths become identical, I've removed the book/view handler entirely. We should probably provide an .htaccess rewrite for this (one is still needed for node/view/nn anyway). At the same time, there is a check in book_block() that shows the block appropriately on these pages.
2004-07-30 13:37:26 +00:00
// Allow modules to change $node->body before viewing.
node_invoke_nodeapi($node, 'view', $teaser, $page);
if ($links) {
$node->links = module_invoke_all('link', 'node', $node, !$page);
}
- Patch #5347 by JonBob: Here's a new patch that unifies the node/52 and book/view/52 paths for nodes. It involves a small change to hook_view(), which is discussed first: Currently hook_view() expects node modules to return a themed node. However, each module does this the same way; they modify $node as necessary, then call theme('node', $node) and return the result. We can refactor this so that the calling function node_view() calls theme('node') instead. By doing this, it becomes possible for hook_nodeapi('view') to be called after hook_view() where the node contents are filtered, and before theme('node') where the body is enclosed in other HTML. This way the book module can insert its navigation into the body right before the theming. Advantages of this refactoring: - I can use it for book.module to remove the extra viewing path. - The function of hook_nodeapi('view') becomes more like hook_view(), as neither will expect a return value. - We more closely follow the flow of other nodeapi calls, which usually directly follow their corresponding specific node type hooks (instead of preceding them). - The attachment.module people could use it to append their attachments in a list after the node. - Gabor could use it instead of his filter perversion for his "articles in a series" module. - A little less code in each view hook. - The content hook is no longer needed, so that means even less code. Disadvantages: - Any modules written to use nodeapi('view') could be affected (but these would all be post-4.4 modules). - Implementations of hook_view() would need to be updated (but return values would be ignored, so most would work without updates anyway). Now the patch takes advantage of this API shift to inject its navigation at the end of all book nodes, regardless of the viewing path. In fact, since the paths become identical, I've removed the book/view handler entirely. We should probably provide an .htaccess rewrite for this (one is still needed for node/view/nn anyway). At the same time, there is a check in book_block() that shows the block appropriately on these pages.
2004-07-30 13:37:26 +00:00
return theme('node', $node, $teaser, $page);
}
/**
* Apply filters to a node in preparation for theming.
*/
function node_prepare($node, $teaser = FALSE) {
$node->readmore = (strlen($node->teaser) < strlen($node->body));
if ($teaser == FALSE) {
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
$node->body = check_output($node->body, $node->format);
}
else {
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
$node->teaser = check_output($node->teaser, $node->format);
}
return $node;
}
/**
* Generate a page displaying a single node, along with its comments.
*/
function node_show($node, $cid) {
$output = node_view($node, FALSE, TRUE);
2003-01-06 19:51:01 +00:00
if (function_exists('comment_render') && $node->comment) {
$output .= comment_render($node, $cid);
}
// Update the history table, stating that this user viewed this node.
node_tag_new($node->nid);
return $output;
}
/**
* Implementation of hook_perm().
*/
function node_perm() {
return array('administer nodes', 'access content');
}
/**
* Implementation of hook_search().
*/
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
function node_search($op = 'search', $keys = null) {
switch ($op) {
case 'name':
return t('content');
case 'reset':
variable_del('node_cron_last');
return;
case 'status':
$last = variable_get('node_cron_last', 0);
$total = db_result(db_query('SELECT COUNT(*) FROM {node} WHERE status = 1 AND moderate = 0'));
$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 n.moderate = 0 AND (n.created > %d OR n.changed > %d OR c.last_comment_timestamp > %d) ORDER BY GREATEST(n.created, n.changed, c.last_comment_timestamp) ASC', $last, $last, $last));
return array('remaining' => $remaining, 'total' => $total);
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
case 'search':
list($join, $where) = _node_rewrite_sql();
$find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid '. $join .' INNER JOIN {users} u ON n.uid = u.uid', 'n.status = 1 AND '. $where);
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
$results = array();
foreach ($find as $item) {
$node = node_load(array('nid' => $item));
$extra = node_invoke_nodeapi($node, 'search result');
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
$results[] = array('link' => url('node/'. $item),
'type' => node_invoke($node, 'node_name'),
'title' => $node->title,
'user' => format_name($node),
'date' => $node->changed,
'extra' => $extra,
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
'snippet' => search_excerpt($keys, check_output($node->body, $node->format)));
}
return $results;
}
}
/**
* Menu callback; presents general node configuration options.
*/
function node_configure() {
if ($_POST) {
system_settings_save();
}
$output .= form_select(t('Number of posts on main page'), 'default_nodes_main', variable_get('default_nodes_main', 10), drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)), t('The default maximum number of posts to display per page on overview pages such as the main page.'));
$output .= form_select(t('Length of trimmed posts'), 'teaser_length', variable_get('teaser_length', 600), array(0 => t('Unlimited'), 200 => t('200 characters'), 400 => t('400 characters'), 600 => t('600 characters'), 800 => t('800 characters'), 1000 => t('1000 characters'), 1200 => t('1200 characters'), 1400 => t('1400 characters'), 1600 => t('1600 characters'), 1800 => t('1800 characters'), 2000 => t('2000 characters')), 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."));
$output .= form_radios(t('Preview post'), 'node_preview', variable_get('node_preview', 0), array(t('Optional'), t('Required')), t('Must users preview posts before submitting?'));
print theme('page', system_settings_form($output));
}
/**
* Retrieve the comment mode for the given node ID (none, read, or read/write).
*/
function node_comment_mode($nid) {
static $comment_mode;
if (!isset($comment_mode[$nid])) {
$comment_mode[$nid] = db_result(db_query('SELECT comment FROM {node} WHERE nid = %d', $nid));
}
return $comment_mode[$nid];
}
/**
* Implementation of hook_link().
*/
function node_link($type, $node = 0, $main = 0) {
2003-04-21 14:55:03 +00:00
$links = array();
if ($type == 'node') {
if (array_key_exists('links', $node)) {
$links = $node->links;
}
if ($main == 1 && $node->teaser && $node->readmore) {
$links[] = l(t('read more'), "node/$node->nid", array('title' => t('Read the rest of this posting.'), 'class' => 'read-more'));
}
}
2003-04-21 14:55:03 +00:00
return $links;
Oops, a rather large commit: - Changed meta.module, node.module and index.php to use comma-seperated lists of attributes rather then "foo=a,bar=b" lists. This makes it a a lot easier to use both modules. In addition, error handling can be discarded as it can't be made any simpler, really ... It fits rather nicely in Drupal's design so I'm getting more and more happy with this meta.module (but we are not 100% there yet). - node.module, node.inc: + Improved the node-related admin interface so that navigating back and forth the administrative menus is made both easier and faster. + Removed some redundant database fields from the node table. See 2.00-to-x.xx.sql! + Added 2 news hooks called "node_insert" and "node_update". Just like this is the case with the existing hook "node_delete" these new hooks will automatically get called when a node has been inserted or udpated. Note that this is an optional call-back that only needs to be implemented when required. With the addition of these two hooks, the node mechanism (version 1) is pretty well completed. - watchdog.module: + Fixed bug whit the 'regular messages' query in the watchdog.module. - book.module: + Fixed bug in book.module: the 'parent' was not set properly when updating a book page. + Made it so that older versions of a book page are automatically reactived upon deletion of the most recent version, i.e. when doing a version roll-back. - comment.inc: + Undid Remco's patch to comment.inc; it does not work in some cases. - conf.module: + Fine-tuned some of the options in conf.module a bit. - marvin.theme: + Visual changes to make it look better on Windows browsers. Mind to give some feedback on this? + Fixed 3 HTML typos/bugs. + XHTML-ified the theme at a best effort basis; I didn't carry the XHTML specification with me. + Made use of the theme_slogan variable to display the site's slogan. + As soon we have at least one valid XHTML theme we can wonder on how to integrate other XML namespaces (cfr. MathML story at drop.org). - database.mysql: + Updated database.mysql so that it contains all the latest "database patches".
2001-06-17 18:31:25 +00:00
}
/**
* Implementation of hook_menu().
*/
function node_menu($may_cache) {
$items = array();
if ($may_cache) {
$items[] = array('path' => 'admin/node', 'title' => t('content'),
'callback' => 'node_admin',
'access' => user_access('administer nodes'));
$items[] = array('path' => 'admin/node/overview', 'title' => t('list'),
'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
$items[] = array('path' => 'admin/node/configure', 'title' => t('configure'),
'callback' => 'node_configure',
'access' => user_access('administer nodes'),
'type' => MENU_LOCAL_TASK);
$items[] = array('path' => 'admin/node/configure/settings', 'title' => t('settings'),
'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
$items[] = array('path' => 'admin/node/configure/defaults', 'title' => t('default workflow'),
'callback' => 'node_default_settings',
'access' => user_access('administer nodes'),
'type' => MENU_LOCAL_TASK);
if (module_exist('search')) {
$items[] = array('path' => 'admin/node/search', 'title' => t('search'),
'callback' => 'node_admin',
'access' => user_access('administer nodes'),
'type' => MENU_LOCAL_TASK);
}
$items[] = array('path' => 'node', 'title' => t('content'),
'callback' => 'node_page',
'access' => user_access('access content'),
'type' => MENU_SUGGESTED_ITEM);
$items[] = array('path' => 'node/add', 'title' => t('create content'),
'callback' => 'node_page',
'access' => user_access('access content'),
'type' => MENU_ITEM_GROUPING,
'weight' => 1);
}
else {
if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(array('nid' => arg(1)));
if ($node->nid) {
$items[] = array('path' => 'node/'. arg(1), 'title' => t('view'),
'callback' => 'node_page',
'access' => node_access('view', $node),
'type' => MENU_CALLBACK);
$items[] = array('path' => 'node/'. arg(1) .'/view', 'title' => t('view'),
'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
$items[] = array('path' => 'node/'. arg(1) .'/edit', 'title' => t('edit'),
'callback' => 'node_page',
'access' => node_access('update', $node),
'weight' => 1,
'type' => MENU_LOCAL_TASK);
if ($node->revisions) {
$items[] = array('path' => 'node/'. arg(1) .'/revisions', 'title' => t('revisions'),
'callback' => 'node_page',
'access' => user_access('administer nodes'),
'weight' => 2,
'type' => MENU_LOCAL_TASK);
}
}
}
}
return $items;
}
/**
* Generate the content administration overview.
*/
function node_admin_nodes() {
$filters = array(
array(t('View posts that are new or updated'), 'ORDER BY n.changed DESC'),
array(t('View posts that need approval'), 'WHERE n.status = 0 OR n.moderate = 1 ORDER BY n.changed DESC'),
array(t('View posts that are promoted'), 'WHERE n.status = 1 AND n.promote = 1 ORDER BY n.changed DESC'),
array(t('View posts that are not promoted'), 'WHERE n.status = 1 AND n.promote = 0 ORDER BY n.changed DESC'),
array(t('View posts that are sticky'), 'WHERE n.status = 1 AND n.sticky = 1 ORDER BY n.changed DESC'),
array(t('View posts that are unpublished'), 'WHERE n.status = 0 AND n.moderate = 0 ORDER BY n.changed DESC')
);
$operations = array(
array(t('Approve the selected posts'), 'UPDATE {node} SET status = 1, moderate = 0 WHERE nid = %d'),
array(t('Promote the selected posts'), 'UPDATE {node} SET status = 1, promote = 1 WHERE nid = %d'),
array(t('Make the selected posts sticky'), 'UPDATE {node} SET status = 1, sticky = 1 WHERE nid = %d'),
array(t('Demote the selected posts'), 'UPDATE {node} SET promote = 0 WHERE nid = %d'),
array(t('Unpublish the selected posts'), 'UPDATE {node} SET status = 0 WHERE nid = %d')
);
// Handle operations:
if (empty($_SESSION['node_overview_filter'])) {
$_SESSION['node_overview_filter'] = 0;
}
$op = $_POST['op'];
if ($op == t('Filter') && isset($_POST['edit']['filter'])) {
$_SESSION['node_overview_filter'] = $_POST['edit']['filter'];
}
if ($op == t('Update') && isset($_POST['edit']['operation']) && isset($_POST['edit']['status'])) {
$operation = $operations[$_POST['edit']['operation']][1];
foreach ($_POST['edit']['status'] as $nid => $value) {
if ($value) {
2003-08-26 07:13:08 +00:00
db_query($operation, $nid);
}
}
drupal_set_message(t('The update has been performed.'));
}
$filter = $_SESSION['node_overview_filter'];
// Render filter form:
$options = array();
foreach ($filters as $key => $value) {
$options[] = $value[0];
2005-01-17 00:41:35 +00:00
}
$form = form_select(NULL, 'filter', $filter, $options);
$form .= form_submit(t('Filter'));
$output .= '<h3>'. t('Filter options') .'</h3>';
$output .= "<div class=\"container-inline\">$form</div>";
// Render operations form:
$result = pager_query('SELECT n.*, u.name, u.uid FROM {node} n INNER JOIN {users} u ON n.uid = u.uid '. $filters[$filter][1], 50);
// Make sure the update controls are disabled if we don't have any rows to select from.
$disabled = !db_num_rows($result);
$options = array();
foreach ($operations as $key => $value) {
$options[] = $value[0];
}
$form = form_select(NULL, 'operation', 0, $options, NULL, ($disabled ? 'disabled="disabled"' : ''));
$form .= form_submit(t('Update'), 'op', ($disabled ? array('disabled' => 'disabled') : array()));
$output .= '<h3>'. t('Update options') .'</h3>';
$output .= "<div class=\"container-inline\">$form</div>";
// Overview table:
$header = array(NULL, t('Title'), t('Type'), t('Author'), t('Status'), array('data' => t('Operations'), 'colspan' => '2'));
while ($node = db_fetch_object($result)) {
$rows[] = array(form_checkbox(NULL, 'status]['. $node->nid, 1, 0), l($node->title, 'node/'. $node->nid) .' '. (node_is_new($node->nid, $node->changed) ? theme_mark() : ''), node_invoke($node, 'node_name'), format_name($node), ($node->status ? t('published') : t('not published')), l(t('edit'), 'node/'. $node->nid .'/edit'), l(t('delete'), 'admin/node/delete/'. $node->nid));
}
if ($pager = theme('pager', NULL, 50, 0)) {
$rows[] = array(array('data' => $pager, 'colspan' => '7'));
}
if (!$rows) {
$rows[] = array(array('data' => t('No posts available.'), 'colspan' => '7'));
2002-12-29 12:20:08 +00:00
}
$output .= '<h3>'. $filters[$filter][0] .'</h3>';
$output .= theme('table', $header, $rows);
return form($output);
}
/**
* Menu callback; presents the interface for setting node defaults.
*/
function node_default_settings() {
$op = $_POST['op'];
$edit = $_POST['edit'];
2003-03-09 17:21:22 +00:00
if ($op == t('Save configuration')) {
// Save the configuration options:
foreach ($edit as $name => $value) {
variable_set($name, $value);
}
drupal_set_message(t('The content settings have been saved.'));
}
if ($op == t('Reset to defaults')) {
// Reset the configuration options to their default value:
foreach ($edit as $name => $value) {
variable_del($name);
}
drupal_set_message(t('The content settings have been reset to their default values.'));
}
$header = array_merge(array(t('type')), array_keys(node_invoke_nodeapi($node, 'settings')));
foreach (node_list() as $type) {
$node = new StdClass();
$node->type = $type;
$cols = array();
foreach (node_invoke_nodeapi($node, 'settings') as $setting) {
$cols[] = array('data' => $setting, 'align' => 'center', 'width' => 55);
}
$rows[] = array_merge(array(node_invoke($node, 'node_name')), $cols);
}
2003-03-09 17:21:22 +00:00
$output .= theme('table', $header, $rows);
$output .= form_submit(t('Save configuration'));
$output .= form_submit(t('Reset to defaults'));
2003-03-09 17:21:22 +00:00
print theme('page', form($output));
}
/**
* Generate an overview table of older revisions of a node.
*/
function node_revision_overview($nid) {
if (user_access('administer nodes')) {
$node = node_load(array('nid' => $nid));
drupal_set_title($node->title);
if ($node->revisions) {
$header = array(t('Older revisions'), array('colspan' => '3', 'data' => t('Operations')));
foreach ($node->revisions as $key => $revision) {
$rows[] = array(t('revision #%r revised by %u on %d', array('%r' => $key, '%u' => format_name(user_load(array('uid' => $revision['uid']))), '%d' => format_date($revision['timestamp'], 'small'))) . ($revision['history'] ? '<br /><small>'. $revision['history'] .'</small>' : ''), l(t('view'), "node/$node->nid", array(), "revision=$key"), l(t('rollback'), "node/$node->nid/rollback-revision/$key"), l(t('delete'), "node/$node->nid/delete-revision/$key"));
}
$output .= theme('table', $header, $rows);
}
}
return $output;
}
/**
* Return the revision with the specified revision number.
*/
function node_revision_load($node, $revision) {
return $node->revisions[$revision]['node'];
}
/**
* Create and return a new revision of the given node.
*/
function node_revision_create($node) {
global $user;
// "Revision" is the name of the field used to indicate that we have to
// create a new revision of a node.
if ($node->nid && $node->revision) {
$prev = node_load(array('nid' => $node->nid));
$node->revisions = $prev->revisions;
unset($prev->revisions);
$node->revisions[] = array('uid' => $user->uid, 'timestamp' => time(), 'node' => $prev, 'history' => $node->history);
}
return $node;
}
/**
* Roll back to the revision with the specified revision number.
*/
function node_revision_rollback($nid, $revision) {
global $user;
if (user_access('administer nodes')) {
$node = node_load(array('nid' => $nid));
// Extract the specified revision:
$rev = $node->revisions[$revision]['node'];
// Inherit all the past revisions:
$rev->revisions = $node->revisions;
// Save the original/current node:
$rev->revisions[] = array('uid' => $user->uid, 'timestamp' => time(), 'node' => $node);
// Remove the specified revision:
unset($rev->revisions[$revision]);
// Save the node:
foreach ($node as $key => $value) {
$filter[] = $key;
}
node_save($rev, $filter);
drupal_set_message(t('Rolled back to revision %revision of %title', array('%revision' => "<em>#$revision</em>", '%title' => "<em>$node->title</em>")));
drupal_goto('node/'. $nid .'/revisions');
}
}
/**
* Delete the revision with specified revision number.
*/
function node_revision_delete($nid, $revision) {
if (user_access('administer nodes')) {
$node = node_load(array('nid' => $nid));
unset($node->revisions[$revision]);
node_save($node, array('nid', 'revisions'));
drupal_set_message(t('Deleted revision %revision of %title', array('%revision' => "<em>#$revision</em>", '%title' => "<em>$node->title</em>")));
drupal_goto('node/'. $nid . (count($node->revisions) ? '/revisions' : ''));
}
}
/**
* Return a list of all the existing revision numbers.
*/
function node_revision_list($node) {
if (is_array($node->revisions)) {
return array_keys($node->revisions);
}
else {
return array();
}
}
/**
* Menu callback; presents the content administration overview.
*/
function node_admin() {
$op = $_POST['op'];
$edit = $_POST['edit'];
if (empty($op)) {
$op = arg(2);
}
// Compile a list of the administrative links:
switch ($op) {
case 'search':
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
case t('Search'):
$output = search_form(url('admin/node/search'), $_POST['edit']['keys'], 'node') . search_data($_POST['edit']['keys'], 'node');
break;
case 'delete':
$output = node_delete(array('nid' => arg(3)));
break;
case t('Delete'):
$output = node_delete($edit);
break;
default:
$output = node_admin_nodes();
}
print theme('page', $output);
}
/**
* Implementation of hook_block().
*/
function node_block($op = 'list', $delta = 0) {
if ($op == 'list') {
$blocks[0]['info'] = t('Syndicate');
return $blocks;
}
else if ($op == 'view') {
$block['subject'] = t('Syndicate');
$block['content'] = theme('xml_icon', url('node/feed'));
return $block;
}
}
/**
* A generic function for generating RSS feeds from a set of nodes.
*
* @param $nodes
* An object as returned by db_query() which contains the nid field.
* @param $channel
* An associative array containing title, link, description and other keys.
* The link should be an absolute URL.
*/
function node_feed($nodes = 0, $channel = array()) {
global $base_url, $locale;
if (!$nodes) {
2005-01-17 19:00:03 +00:00
$nodes = db_query_range(node_rewrite_sql('SELECT n.nid FROM {node} n WHERE n.promote = 1 AND n.status = 1 ORDER BY n.created DESC'), 0, 15);
}
while ($node = db_fetch_object($nodes)) {
// Load the specified node:
$item = node_load(array('nid' => $node->nid));
$link = url("node/$node->nid", NULL, NULL, 1);
// Filter and prepare node teaser
if (node_hook($item, 'view')) {
node_invoke($item, 'view', TRUE, FALSE);
}
else {
$item = node_prepare($item, TRUE);
}
// Allow modules to change $node->body before viewing.
node_invoke_nodeapi($item, 'view', false, false);
$items .= format_rss_item($item->title, $link, $item->teaser, array('pubDate' => date('r', $item->changed)));
}
$channel_defaults = array(
'version' => '0.92',
'title' => variable_get('site_name', 'drupal') .' - '. variable_get('site_slogan', ''),
'link' => $base_url,
'description' => variable_get('site_mission', ''),
'language' => $locale
);
$channel = array_merge($channel_defaults, $channel);
$output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
2002-12-21 19:36:27 +00:00
$output .= "<!DOCTYPE rss [<!ENTITY % HTMLlat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent\">]>\n";
$output .= "<rss version=\"". $channel["version"] . "\" xml:base=\"". $base_url ."\">\n";
$output .= format_rss_channel($channel['title'], $channel['link'], $channel['description'], $items, $channel['language']);
$output .= "</rss>\n";
drupal_set_header('Content-Type: text/xml; charset=utf-8');
print $output;
}
/**
* Perform validation checks on the given node.
*/
function node_validate($node) {
global $user;
// Convert the node to an object, if necessary.
- import.module: + Improved input filtering; this should make the news items look more consistent in terms of mark-up. + Quoted all array indices: converted all instances of $foo[bar] to $foo["bar"]. Made various other changes to make the import module compliant with the coding style. - theme.inc: + Fixed small XHTML glitch - comment system: + Made it possible for users to edit their comments (when certain criteria are matched). + Renamed the SQL table field "lid" to "nid" and updated the code to reflect this change: this is a rather /annoying/ change that has been asked for a few times. It will impact the contributed BBS/forum modules and requires a tiny SQL update: sql> ALTER TABLE comments CHANGE lid nid int(10) NOT NULL; + Moved most (all?) of the comment related logic from node.php to comment.module where it belongs. This also marks a first step towards removing/reducing "node.php". + Added a delete button to the comment admin form and made it so that Drupal prompts for confirmation prior to deleting a comment from the database. This behavior is similar to that of deleting nodes. + Disabled comment moderation for now. + Some of the above changes will make it easier to integrate the upcomcing mail-to-web and web-to-mail gateways. They are part of a bigger plan. ;) - node system: + Made it so that updating nodes (like for instance updating blog entries) won't trigger the submission rate throttle. + Fixed a small glitch where a node's title wasn't always passed to the $theme->header() function. + Made "node_array()" and "node_object()" more generic and named them "object2array()" and "array2object()". + Moved most (all?) of the comment related logic from node.php to comment.module where it belongs. This also marks a first step towards removing/reducing "node.php". - misc: + Applied three patches by Foxen. One to improve performance of the book module, and two other patches to fix small glitches in common.inc. Thanks Foxen!
2001-12-30 16:16:38 +00:00
$node = array2object($node);
// Validate the title field.
2003-05-26 21:31:18 +00:00
if (isset($node->title)) {
$node->title = strip_tags($node->title);
if (!$node->title) {
form_set_error('title', t('You have to specify a valid title.'));
2003-05-26 21:31:18 +00:00
}
}
// Auto-generate the teaser, but only if it hasn't been set (e.g. by a
// module-provided 'teaser' form item).
if (!isset($node->teaser)) {
$node->teaser = node_teaser($node->body);
}
// Create a new revision when required.
$node = node_revision_create($node);
if (user_access('administer nodes')) {
// Set up default values, if required.
if (!$node->created) {
$node->created = time();
}
if (!$node->date) {
$node->date = format_date($node->created, 'custom', 'Y-m-d H:i O');
}
2003-03-09 17:21:22 +00:00
// Validate the "authored by" field.
if (empty($node->name)) {
// The use of empty() is mandatory in the context of usernames
// as the empty string denotes the anonymous user. In case we
// are dealing with an anonymous user we set the user ID to 0.
$node->uid = 0;
}
else if ($account = user_load(array('name' => $node->name))) {
$node->uid = $account->uid;
}
else {
form_set_error('name', t('The name %name does not exist.', array ('%name' => "<em>$node->name</em>")));
}
// Validate the "authored on" field.
if (strtotime($node->date) != -1) {
$node->created = strtotime($node->date);
}
else {
form_set_error('date', t('You have to specify a valid date.'));
}
}
else {
// Validate for normal users:
$node->uid = $user->uid ? $user->uid : 0;
// Force defaults in case people modify the form:
2003-03-11 08:43:59 +00:00
$node->status = variable_get("node_status_$node->type", 1);
$node->promote = variable_get("node_promote_$node->type", 1);
$node->moderate = variable_get("node_moderate_$node->type", 0);
$node->sticky = variable_get("node_sticky_$node->type", 0);
2003-03-11 08:43:59 +00:00
$node->revision = variable_get("node_revision_$node->type", 0);
unset($node->created);
}
// Do node-type-specific validation checks.
node_invoke($node, 'validate');
node_invoke_nodeapi($node, 'validate');
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
// Check input format access
if (array_key_exists('format', $node) && !filter_access($node->format)) {
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
form_set_error('format', t('The supplied input format is invalid.'));
}
$node->validated = TRUE;
return $node;
}
/**
* Generate the node editing form.
*/
function node_form($edit) {
// Validate the node if we don't already know the errors.
if (!$edit->validated) {
$edit = node_validate($edit);
}
// Prepend extra node form elements.
$form = implode('', node_invoke_nodeapi($edit, 'form pre'));
// Get the node-specific bits.
// We can't use node_invoke() because $param must be passed by reference.
$function = node_get_module_name($edit) .'_form';
$param = array();
if (function_exists($function)) {
$form .= $function($edit, $param);
}
2003-03-09 17:21:22 +00:00
// Append extra node form elements.
$form .= implode('', node_invoke_nodeapi($edit, 'form post'));
$output .= '<div class="node-form">';
// Add hidden 'op' variable, which specifies the default operation (Preview).
$output .= '<input type="hidden" name="op" value="'. check_form(t('Preview')) ."\" />\n";
// Add the admin-specific parts.
if (user_access('administer nodes')) {
$output .= '<div class="admin">';
$author = form_textfield(t('Authored by'), 'name', $edit->name, 20, 60);
$author .= form_textfield(t('Authored on'), 'date', $edit->date, 20, 25, NULL, NULL, TRUE);
$output .= '<div class="authored">';
$output .= form_group(t('Authoring information'), $author);
$output .= "</div>\n";
$options .= form_checkbox(t('Published'), 'status', 1, isset($edit->status) ? $edit->status : variable_get('node_status_'. $edit->type, 1));
$options .= form_checkbox(t('In moderation queue'), 'moderate', 1, isset($edit->moderate) ? $edit->moderate : variable_get('node_moderate_'. $edit->type, 0));
$options .= form_checkbox(t('Promoted to front page'), 'promote', 1, isset($edit->promote) ? $edit->promote : variable_get('node_promote_'. $edit->type, 1));
$options .= form_checkbox(t('Sticky at top of lists'), 'sticky', 1, isset($edit->sticky) ? $edit->sticky : variable_get('node_sticky_'. $edit->type, 0));
$options .= form_checkbox(t('Create new revision'), 'revision', 1, isset($edit->revision) ? $edit->revision : variable_get('node_revision_'. $edit->type, 0));
$output .= '<div class="options">';
$output .= form_group(t('Options'), $options);
$output .= "</div>\n";
$extras .= implode('</div><div class="extra">', node_invoke_nodeapi($edit, 'form admin'));
$output .= $extras ? '<div class="extra">'. $extras .'</div></div>' : '</div>';
}
// Add the default fields.
$output .= '<div class="standard">';
$output .= form_textfield(t('Title'), 'title', $edit->title, 60, 128, NULL, NULL, TRUE);
// Add the node-type-specific fields.
$output .= $form;
// Add the hidden fields.
if ($edit->nid) {
$output .= form_hidden('nid', $edit->nid);
}
if (isset($edit->uid)) {
// The use of isset() is mandatory in the context of user IDs, because
// user ID 0 denotes the anonymous user.
$output .= form_hidden('uid', $edit->uid);
}
if ($edit->created) {
$output .= form_hidden('created', $edit->created);
}
$output .= form_hidden('type', $edit->type);
// Add the buttons.
$output .= form_submit(t('Preview'));
if (!form_get_errors()) {
if ($edit->title && $edit->type) {
$output .= form_submit(t('Submit'));
}
elseif (!variable_get('node_preview', 0)) {
$output .= form_submit(t('Submit'));
}
}
if ($edit->nid && node_access('delete', $edit)) {
$output .= form_submit(t('Delete'));
}
$output .= '</div></div>';
$extra = node_invoke_nodeapi($edit, 'form param');
foreach ($extra as $key => $value) {
if (is_array($value)) {
if (isset($param[$key])) {
$param[$key] = array_merge($param[$key], $value);
}
else {
$param[$key] = $value;
}
}
else {
$param[$key] = $value;
}
}
$attributes = array('id' => 'node-form');
if (is_array($param['options'])) {
$attributes = array_merge($param['options'], $attributes);
}
return form($output, ($param['method'] ? $param['method'] : 'post'), $param['action'], $attributes);
}
/**
* Present a node submission form or a set of links to such forms.
*/
function node_add($type) {
global $user;
$edit = $_POST['edit'];
// If a node type has been specified, validate its existence.
if (in_array($type, node_list()) && node_access('create', $type)) {
// Initialize settings:
$node = array('uid' => $user->uid, 'name' => $user->name, 'type' => $type);
// Allow the following fields to be initialized via $_GET (e.g. for use
// with a "blog it" bookmarklet):
foreach (array('title', 'teaser', 'body') as $field) {
if ($_GET['edit'][$field]) {
$node[$field] = $_GET['edit'][$field];
}
}
$output = node_form($node);
drupal_set_title(t('Submit %name', array('%name' => node_invoke($node, 'node_name'))));
}
else {
// If no (valid) node type has been provided, display a node type overview.
foreach (node_list() as $type) {
if (node_access('create', $type)) {
$out = '<li>';
$out .= ' '. l(node_invoke($type, 'node_name'), "node/add/$type", array('title' => t('Add a new %s.', array('%s' => node_invoke($type, 'node_name')))));
$out .= " <div style=\"margin-left: 20px;\">". implode("\n", module_invoke_all('help', 'node/add#'. $type)) .'</div>';
$out .= '</li>';
$item[node_invoke($type, 'node_name')] = $out;
}
}
if (isset($item)) {
ksort($item);
$output = t('Choose the appropriate item from the list:') .'<ul>'. implode('', $item) .'</ul>';
}
else {
$output = message_access();
}
}
return $output;
}
/**
* Present a node editing form.
*/
function node_edit($id) {
global $user;
$node = node_load(array('nid' => $id));
drupal_set_title($node->title);
$output = node_form($node);
return $output;
}
/**
* Generate a node preview, including a form for further edits.
*/
function node_preview($node) {
// Convert the array to an object:
- import.module: + Improved input filtering; this should make the news items look more consistent in terms of mark-up. + Quoted all array indices: converted all instances of $foo[bar] to $foo["bar"]. Made various other changes to make the import module compliant with the coding style. - theme.inc: + Fixed small XHTML glitch - comment system: + Made it possible for users to edit their comments (when certain criteria are matched). + Renamed the SQL table field "lid" to "nid" and updated the code to reflect this change: this is a rather /annoying/ change that has been asked for a few times. It will impact the contributed BBS/forum modules and requires a tiny SQL update: sql> ALTER TABLE comments CHANGE lid nid int(10) NOT NULL; + Moved most (all?) of the comment related logic from node.php to comment.module where it belongs. This also marks a first step towards removing/reducing "node.php". + Added a delete button to the comment admin form and made it so that Drupal prompts for confirmation prior to deleting a comment from the database. This behavior is similar to that of deleting nodes. + Disabled comment moderation for now. + Some of the above changes will make it easier to integrate the upcomcing mail-to-web and web-to-mail gateways. They are part of a bigger plan. ;) - node system: + Made it so that updating nodes (like for instance updating blog entries) won't trigger the submission rate throttle. + Fixed a small glitch where a node's title wasn't always passed to the $theme->header() function. + Made "node_array()" and "node_object()" more generic and named them "object2array()" and "array2object()". + Moved most (all?) of the comment related logic from node.php to comment.module where it belongs. This also marks a first step towards removing/reducing "node.php". - misc: + Applied three patches by Foxen. One to improve performance of the book module, and two other patches to fix small glitches in common.inc. Thanks Foxen!
2001-12-30 16:16:38 +00:00
$node = array2object($node);
if (node_access('create', $node) || node_access('update', $node)) {
// Load the user's name when needed:
if (isset($node->name)) {
// The use of isset() is mandatory in the context of user IDs, because
// user ID 0 denotes the anonymous user.
if ($user = user_load(array('name' => $node->name))) {
$node->uid = $user->uid;
}
else {
$node->uid = 0; // anonymous user
}
}
else if ($node->uid) {
$user = user_load(array('uid' => $node->uid));
$node->name = $user->name;
}
// Set the created time when needed:
if (empty($node->created)) {
$node->created = time();
}
$node->changed = time();
// Extract a teaser, if it hasn't been set (e.g. by a module-provided
// 'teaser' form item).
if (!isset($node->teaser)) {
$node->teaser = node_teaser($node->body);
}
// Display a preview of the node:
if ($node->teaser && $node->teaser != $node->body) {
$output = '<h3>'. t('Preview trimmed version') .'</h3>';
$output .= node_view($node, 1, FALSE, 0);
$output .= '<p><em>'. t('The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "&lt;!--break--&gt;" (without the quotes) to fine-tune where your post gets split.') .'</em></p>';
$output .= '<h3>'. t('Preview full version') .'</h3>';
$output .= node_view($node, 0, FALSE, 0);
}
else {
$output .= node_view($node, 0, FALSE, 0);
}
$output .= node_form($node);
$name = node_invoke($node, 'node_name');
drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('create content'), 'node/add'), l(t('Submit %name', array('%name' => $name)), 'node/add/'. $node->type)));
return $output;
}
}
/**
* Accepts a submission of new or changed node content.
*
* @param $node
* A node array or node object.
*
* @return
* If the node is successfully saved the node ID is returned. If the node
* is not saved, 0 is returned.
*/
function node_submit(&$node) {
global $user;
// Fix up the node when required:
$node = node_validate($node);
// If something went wrong, go back to the preview form.
if (form_get_errors()) {
return false;
}
// Prepare the node's body:
if ($node->nid) {
// Check whether the current user has the proper access rights to
// perform this operation:
if (node_access('update', $node)) {
$node->nid = node_save($node);
2005-01-09 12:58:53 +00:00
watchdog('content', t('%type: updated %title.', array('%type' => '<em>'. t($node->type) .'</em>', '%title' => "<em>$node->title</em>")), WATCHDOG_NOTICE, l(t('view'), 'node/'. $node->nid));
$msg = t('The %post was updated.', array ('%post' => node_invoke($node, 'node_name')));
}
}
else {
// Check whether the current user has the proper access rights to
// perform this operation:
if (node_access('create', $node)) {
$node->nid = node_save($node);
2005-01-09 12:58:53 +00:00
watchdog('content', t('%type: added %title.', array('%type' => '<em>'. t($node->type) .'</em>', '%title' => "<em>$node->title</em>")), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
$msg = t('Your %post was created.', array ('%post' => node_invoke($node, 'node_name')));
}
}
drupal_set_message($msg);
return $node->nid;
}
/**
* Ask for confirmation, and delete the node.
*/
function node_delete($edit) {
$node = node_load(array('nid' => $edit['nid']));
if (node_access('delete', $node)) {
if ($edit['confirm']) {
// Delete the specified node:
db_query('DELETE FROM {node} WHERE nid = %d', $node->nid);
// Call the node-specific callback (if any):
node_invoke($node, 'delete');
node_invoke_nodeapi($node, 'delete');
// Clear the cache so an anonymous poster can see the node being deleted.
cache_clear_all();
// Remove this node from the search index if needed.
if (function_exists('search_wipe')) {
search_wipe($node->nid, 'node');
}
watchdog('content', t('%type: deleted %title.', array('%type' => '<em>'. t($node->type) .'</em>', '%title' => "<em>$node->title</em>")));
$output = t('The node has been deleted.');
}
else {
$output .= form_item(t('Confirm deletion'), $node->title);
$output .= form_hidden('nid', $node->nid);
$output .= form_hidden('confirm', 1);
$output .= form_submit(t('Delete'));
$output = form($output);
}
}
return $output;
}
/**
* Generate a listing of promoted nodes.
*/
function node_page_default() {
$result = pager_query(node_rewrite_sql('SELECT n.nid, n.sticky, n.created FROM {node} n WHERE n.promote = 1 AND n.status = 1 ORDER BY n.sticky DESC, n.created DESC'), variable_get('default_nodes_main', 10));
if (db_num_rows($result)) {
drupal_set_html_head('<link rel="alternate" type="application/rss+xml" title="RSS" href="'. url('node/feed', NULL, NULL, TRUE) .'" />');
$output = '';
while ($node = db_fetch_object($result)) {
$output .= node_view(node_load(array('nid' => $node->nid)), 1);
}
$output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
}
else {
$output = t("
2004-02-09 00:56:23 +00:00
<p>Welcome to your new <a href=\"%drupal\">Drupal</a>-powered website. This message will guide you through your first steps with Drupal, and will disappear once you have posted your first piece of content.</p>
<p>The first thing you will need to do is <a href=\"%register\">create the first account</a>. This account will have full administration rights and will allow you to configure your website. Once logged in, you can visit the <a href=\"%admin\">administration section</a> and <a href=\"%config\">set up your site's configuration</a>.</p>
<p>Drupal comes with various modules, each of which contains a specific piece of functionality. You should visit the <a href=\"%modules\">module list</a> and enable those modules which suit your website's needs.</p>
<p><a href=\"%themes\">Themes</a> handle the presentation of your website. You can use one of the existing themes, modify them or create your own from scratch.</p>
<p>We suggest you look around the administration section and explore the various options Drupal offers you. For more information, you can refer to the <a href=\"%handbook\">Drupal handbook online</a>.</p>", array('%drupal' => 'http://www.drupal.org/', '%register' => url('user/register'), '%admin' => url('admin'), '%config' => url('admin'), '%modules' => url('admin/modules'), '%themes' => url('admin/themes'), '%handbook' => 'http://www.drupal.org/handbook'));
}
return $output;
}
/**
* Menu callback; dispatches control to the appropriate operation handler.
*/
function node_page() {
$op = $_POST['op'] ? $_POST['op'] : arg(1);
$edit = $_POST['edit'];
if (is_numeric($op)) {
$op = (arg(2) && !is_numeric(arg(2))) ? arg(2) : 'view';
}
switch ($op) {
case 'feed':
node_feed();
return;
case 'add':
print theme('page', node_add(arg(2)));
break;
case 'edit':
print theme('page', node_edit(arg(1)));
break;
case 'revisions':
print theme('page', node_revision_overview(arg(1)));
break;
case 'rollback-revision':
node_revision_rollback(arg(1), arg(3));
break;
case 'delete-revision':
node_revision_delete(arg(1), arg(3));
break;
case 'view':
if (is_numeric(arg(1))) {
$node = node_load(array('nid' => arg(1)), $_GET['revision']);
if ($node->nid) {
drupal_set_title($node->title);
print theme('page', node_show($node, arg(2)));
}
else {
drupal_not_found();
}
}
break;
case t('Preview'):
$edit = node_validate($edit);
drupal_set_title(t('Preview'));
print theme('page', node_preview($edit));
break;
case t('Submit'):
if (node_submit($edit)) {
if (node_access('view', $edit)) {
drupal_goto('node/'. $edit->nid);
}
else {
drupal_goto();
}
}
else {
drupal_set_title(t('Submit'));
print theme('page', node_preview($edit));
}
break;
case t('Delete'):
drupal_set_title(t('Delete'));
print theme('page', node_delete($edit));
break;
default:
drupal_set_title('');
print theme('page', node_page_default());
}
}
/**
* Implementation of hook_update_index().
*/
function node_update_index() {
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
$last = variable_get('node_cron_last', 0);
$limit = (int)variable_get('search_cron_limit', 100);
$result = db_query_range('SELECT n.nid, c.last_comment_timestamp FROM {node} n LEFT JOIN {node_comment_statistics} c ON n.nid = c.nid WHERE n.status = 1 AND n.moderate = 0 AND (n.created > %d OR n.changed > %d OR c.last_comment_timestamp > %d) ORDER BY GREATEST(n.created, n.changed, c.last_comment_timestamp) ASC', $last, $last, $last, 0, $limit);
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
while ($node = db_fetch_object($result)) {
$last_comment = $node->last_comment_timestamp;
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
$node = node_load(array('nid' => $node->nid));
// We update this variable per node in case cron times out, or if the node
// cannot be indexed (PHP nodes which call drupal_goto, for example).
// In rare cases this can mean a node is only partially indexed, but the
// chances of this happening are very small.
variable_set('node_cron_last', max($last_comment, $node->changed, $node->created));
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
// Get node output (filtered and with module-specific fields).
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
if (node_hook($node, 'view')) {
node_invoke($node, 'view', false, false);
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
}
else {
$node = node_prepare($node, false);
}
// Allow modules to change $node->body before viewing.
node_invoke_nodeapi($node, 'view', false, false);
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
$text = '<h1>'. drupal_specialchars($node->title) .'</h1>'. $node->body;
// Fetch extra data normally not visible
$extra = node_invoke_nodeapi($node, 'update index');
foreach ($extra as $t) {
$text .= $t;
- Patch #12232 by Steven/UnConed: search module improvements. 1) Clean up the text analyser: make it handle UTF-8 and all sorts of characters. The word splitter now does intelligent splitting into words and supports all Unicode characters. It has smart handling of acronyms, URLs, dates, ... 2) It now indexes the filtered output, which means it can take advantage of HTML tags. Meaningful tags (headers, strong, em, ...) are analysed and used to boost certain words scores. This has the side-effect of allowing the indexing of PHP nodes. 3) Link analyser for node links. The HTML analyser also checks for links. If they point to a node on the current site (handles path aliases) then the link's words are counted as part of the target node. This helps bring out commonly linked FAQs and answers to the top of the results. 4) Index comments along with the node. This means that the search can make a difference between a single node/comment about 'X' and a whole thread about 'X'. It also makes the search results much shorter and more relevant (before this patch, comments were even shown first). 5) We now keep track of total counts as well as a per item count for a word. This allows us to divide the word score by the total before adding up the scores for different words, and automatically makes noisewords have less influence than rare words. This dramatically improves the relevancy of multiword searches. This also makes the disadvantage of now using OR searching instead of AND searching less problematic. 6) Includes support for text preprocessors through a hook. This is required to index Chinese and Japanese, because these languages do not use spaces between words. An external utility can be used to split these into words through a simple wrapper module. Other uses could be spell checking (although it would have no UI). 7) Indexing is now regulated: only a certain amount of items will be indexed per cron run. This prevents PHP from running out of memory or timing out. This also makes the reindexing required for this patch automatic. I also added an index coverage estimate to the search admin screen. 8) Code cleanup! Moved all the search stuff from common.inc into search.module, rewired some hooks and simplified the functions used. The search form and results now also use valid XHTML and form_ functions. The search admin was moved from search/configure to admin/search for consistency. 9) Improved search output: we also show much more info per item: date, author, node type, amount of comments and a cool dynamic excerpt à la Google. The search form is now much more simpler and the help is only displayed as tips when no search results are found. 10) By moving all search logic to SQL, I was able to add a pager to the search results. This improves usability and performance dramatically.
2004-10-31 03:03:27 +00:00
}
// Update index
search_index($node->nid, 'node', $text);
}
}
/**
* Implementation of hook_nodeapi().
*/
function node_nodeapi(&$node, $op, $arg = 0) {
switch ($op) {
case 'settings':
$output[t('publish')] = form_checkbox('', "node_status_$node->type", 1, variable_get("node_status_$node->type", 1));
$output[t('promote')] = form_checkbox('', "node_promote_$node->type", 1, variable_get("node_promote_$node->type", 1));
$output[t('moderate')] = form_checkbox('', "node_moderate_$node->type", 1, variable_get("node_moderate_$node->type", 0));
$output[t('sticky')] = form_checkbox('', "node_sticky_$node->type", 1, variable_get("node_sticky_$node->type", 0));
$output[t('revision')] = form_checkbox('', "node_revision_$node->type", 1, variable_get("node_revision_$node->type", 0));
return $output;
case 'fields':
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
return array('nid', 'uid', 'type', 'title', 'teaser', 'body', 'revisions', 'status', 'promote', 'moderate', 'sticky', 'created', 'changed', 'format');
}
}
/**
* @defgroup node_access Node access rights
* @{
* The node access system determines who can do what to which nodes.
*
* In determining access rights for a node, node_access() first checks
* whether the user has the "administer nodes" permission. Such users have
* unrestricted access to all nodes. Then the node module's hook_access()
* is called, and a TRUE or FALSE return value will grant or deny access.
* This allows, for example, the blog module to always grant access to the
* blog author, and for the book module to always deny editing access to
* PHP pages.
*
* If node module does not intervene (returns NULL), then the
* node_access table is used to determine access. All node access
* modules are queried using hook_node_grants() to assemble a list of
* "grant IDs" for the user. This list is compared against the table.
* If any row contains the node ID in question (or 0, which stands for "all
* nodes"), one of the grant IDs returned, and a value of TRUE for the
* operation in question, then access is granted. Note that this table is a
* list of grants; any matching row is sufficient to grant access to the
* node.
*
* In node listings, the process above is followed except that
* hook_access() is not called on each node for performance reasons and for
* proper functioning of the pager system. When adding a node listing to your
* module, be sure to use node_access_join_sql() and node_access_where_sql() to add
* the appropriate clauses to your query for access checks.
*
* To see how to write a node access module of your own, see
* node_access_example.module.
*/
/**
* Determine whether the current user may perform the given operation on the
* specified node.
*
* @param $op
* The operation to be performed on the node. Possible values are:
* - "view"
* - "update"
* - "delete"
* @param $node
* The node object (or node array) on which the operation is to be performed.
* @param $uid
* The user ID on which the operation is to be performed.
* @return
* TRUE if the operation may be performed.
*/
function node_access($op, $node = NULL, $uid = NULL) {
The Input formats - filter patch has landed. I still need to make update instructions for modules and update the hook docs. Here's an overview of the changes: 1) Multiple Input formats: they are complete filter configurations (what filters to use, in what order and with which settings). Input formats are admin-definable, and usage of them is role-dependant. For example, you can set it up so that regular users can only use limited HTML, while admins can free HTML without any tag limitations. The input format can be chosen per content item (nodes, comments, blocks, ...) when you add/edit them. If only a single format is available, there is no choice, and nothing changes with before. The default install (and the upgrade) contains a basic set of formats which should satisfy the average user's needs. 2) Filters have toggles Because now you might want to enable a filter only on some input formats, an explicit toggle is provided by the filter system. Modules do not need to worry about it and filters that still have their own on/off switch should get rid of it. 3) Multiple filters per module This was necessary to accomodate the next change, and it's also a logical extension of the filter system. 4) Embedded PHP is now a filter Thanks to the multiple input formats, I was able to move the 'embedded PHP' feature from block.module, page.module and book.module into a simple filter which executes PHP code. This filter is part of filter.module, and by default there is an input format 'PHP', restricted to the administrator only, which contains this filter. This change means that block.module now passes custom block contents through the filter system. As well as from reducing code duplication and avoiding two type selectors for page/book nodes, you can now combine PHP code with other filters. 5) User-supplied PHP code now requires <?php ?> tags. This is required for teasers to work with PHP code. Because PHP evaluation is now just another step in the filter process, we can't do this. Also, because teasers are generated before filtering, this would result in errors when the teaser generation would cut off a piece of PHP code. Also, regular PHP syntax explicitly includes the <?php ?> tags for PHP files, so it makes sense to use the same convention for embedded PHP in Drupal. 6) Filter caching was added. Benchmarking shows that even for a simple setup (basic html filtering + legacy URL rewriting), filtercache can offer speedups. Unlike the old filtercache, this uses the normal cache table. 7) Filtertips were moved from help into a hook_filter_tips(). This was required to accomodate the fact that there are multiple filters per module, and that filter settings are format dependant. Shoehorning filter tips into _help was ugly and silly. The display of the filter tips is done through the input format selector, so filter_tips_short() no longer exists. 8) A more intelligent linebreak convertor was added, which doesn't stop working if you use block-level tags and which adds <p> tags.
2004-08-10 18:34:29 +00:00
// Convert the node to an object if necessary:
$node = array2object($node);
// If the node is in a restricted format, disallow editing.
if ($op == 'update' && !filter_access($node->format)) {
return FALSE;
}
if (user_access('administer nodes')) {
return TRUE;
}
if (!user_access('access content')) {
return FALSE;
}
// Can't use node_invoke(), because the access hook takes the $op parameter
// before the $node parameter.
$access = module_invoke(node_get_module_name($node), 'access', $op, $node);
if (!is_null($access)) {
return $access;
}
// If the module did not override the access rights, use those set in the
// node_access table.
if ($node->nid && $node->status) {
$sql = 'SELECT COUNT(*) FROM {node_access} WHERE (nid = 0 OR nid = %d) AND CONCAT(realm, gid) IN (';
$grants = array();
foreach (node_access_grants($op, $uid) as $realm => $gids) {
foreach ($gids as $gid) {
$grants[] = "'". $realm . $gid ."'";
}
}
$sql .= implode(',', $grants) .') AND grant_'. $op .' = 1';
$result = db_query($sql, $node->nid);
return (db_result($result));
}
return FALSE;
}
/**
* Generate an SQL join clause for use in fetching a node listing.
*
* @param $node_alias
* If the node table has been given an SQL alias other than the default
* "n", that must be passed here.
* @param $node_access_alias
* If the node_access table has been given an SQL alias other than the default
* "na", that must be passed here.
* @return
* An SQL join clause.
*/
function node_access_join_sql($node_alias = 'n', $node_access_alias = 'na') {
if (!module_implements('node_grants') || user_access('administer nodes')) {
return '';
}
$sql = 'INNER JOIN {node_access} '. $node_access_alias;
$sql .= ' ON ('. $node_access_alias .'.nid = 0 OR '. $node_access_alias .'.nid = '. $node_alias .'.nid)';
return $sql;
}
/**
* Generate an SQL where clause for use in fetching a node listing.
*
* @param $op
* The operation that must be allowed to return a node.
* @param $node_access_alias
* If the node_access table has been given an SQL alias other than the default
* "na", that must be passed here.
* @return
* An SQL where clause.
*/
function node_access_where_sql($op = 'view', $node_access_alias = 'na', $uid = NULL) {
if (!module_implements('node_grants') || user_access('administer nodes')) {
// This number is being used in a SQL query as a boolean.
// It is "'1'" instead of "1" for database compatibility, as both
// PostgreSQL and MySQL treat it as boolean in this case.
return "'1'";
}
$sql = $node_access_alias .'.grant_'. $op .' = 1 AND CONCAT('. $node_access_alias .'.realm, '. $node_access_alias .'.gid) IN (';
$grants = array();
foreach (node_access_grants($op, $uid) as $realm => $gids) {
foreach ($gids as $gid) {
$grants[] = "'". $realm . $gid ."'";
}
}
$sql .= implode(',', $grants) .')';
return $sql;
}
/**
* Fetch an array of permission IDs granted to the given user ID.
*
* The implementation here provides only the universal "all" grant. A node
* access module should implement hook_node_grants() to provide a grant
* list for the user.
*
* @param $op
* The operation that the user is trying to perform.
* @param $uid
* The user ID performing the operation. If omitted, the current user is used.
* @return
* An associative array in which the keys are realms, and the values are
* arrays of grants for those realms.
*/
function node_access_grants($op, $uid = NULL) {
global $user;
if (isset($uid)) {
$user_object = user_load(array('uid' => $uid));
}
else {
$user_object = $user;
}
return array_merge(array('all' => array(0)), module_invoke_all('node_grants', $user_object, $op));
}
/**
* @} End of "defgroup node_access".
*/
/**
* Implementation of hook_node_rewrite_sql
*/
2005-01-17 19:00:03 +00:00
function node_node_rewrite_sql() {
$return['join'] = node_access_join_sql();
$return['where'] = node_access_where_sql();
$return['distinct'] = !empty($return['join']);
return $return;
}
2005-01-17 19:00:03 +00:00
/**
* Helper function for node_rewrite_sql.
*
* Collects JOIN and WHERE statements via hook_sql.
* Decides whether to select nid or DISTINCT(nid)
*
* @param $query
* query to be rewritten
* @param $nid_alias
* Alias of the table which has the nid field for this query. Defaults to 'n'.
* @param $args
* array of additional args
* @return
* An associative array: join => join statements, where => where statements, nid_to_select => nid or DISTINCT(nid)
*/
function _node_rewrite_sql($query = '', $nid_alias = 'n', $args = array()) {
$where = array();
$join = array();
$distinct = FALSE;
foreach (module_implements('node_rewrite_sql') as $module) {
$result = module_invoke($module, 'node_rewrite_sql', $query, $nid_alias, $args);
if (is_array($result)) {
if (isset($result['where'])) {
$where[] .= $result['where'];
}
if (isset($result['join'])) {
$join[] .= $result['join'];
}
if (isset($result['distinct']) && $result['distinct']) {
$distinct = TRUE;
}
}
elseif (isset($result)) {
$where[] .= $result;
}
}
2005-01-17 19:00:03 +00:00
$where = empty($where) ? '' : '('. implode(') AND (',$where).')';
$join = empty($join) ? '' : implode(' ',$join);
2005-01-17 19:00:03 +00:00
return array($join, $where, $distinct ? 'DISTINCT('. $nid_alias .'.nid)' : $nid_alias .'.nid');
}
2005-01-17 19:00:03 +00:00
/**
* Rewrites node queries.
*
* @param $query
* query to be rewritten
* @param $nid_alias
* Alias of the table which has the nid field for this query. Defaults to 'n'.
* @param $args
* an array of arguments, passed to the implementations of hook_node_rewrite_sql
* @return
* The original query with JOIN and WHERE statements inserted from hook_node_rewrite_sql implementations. nid is rewritten if needed.
*/
function node_rewrite_sql($query, $nid_alias = 'n', $args = array()) {
list($join, $where, $nid_to_select) = _node_rewrite_sql($query, $nid_alias, $args);
2005-01-22 22:33:20 +00:00
// (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
$query = preg_replace('/(SELECT.*)('. $nid_alias .'\.)?(?<!DISTINCT\()(?<!DISTINCT\('. $nid_alias .'\.)nid(.*FROM)/AUsi', '\1'. $nid_to_select .'\3', $query);
2005-01-19 01:51:58 +00:00
$query = preg_replace('|FROM[^[:upper:]/,]+|','\0 '. $join .' ', $query);
if (strpos($query, 'WHERE')) {
$replace = 'WHERE';
$add = 'AND';
}
elseif (strpos($query, 'GROUP')) {
$replace = 'GROUP';
$add = 'GROUP';
}
elseif (strpos($query, 'ORDER')) {
$replace = 'ORDER';
$add = 'ORDER';
}
elseif (strpos($query, 'LIMIT')) {
$replace = 'LIMIT';
$add = 'LIMIT';
}
2005-01-17 19:00:03 +00:00
else {
$query .= ' WHERE '. $where;
2005-01-17 19:00:03 +00:00
}
if (isset($replace)) {
2005-01-17 19:00:03 +00:00
$query = str_replace($replace, 'WHERE '. $where .' '. $add .' ', $query);
}
return $query;
}
?>