Skip to content

Instantly share code, notes, and snippets.

@ajankovic
Created April 25, 2012 16:32
Show Gist options
  • Select an option

  • Save ajankovic/2491104 to your computer and use it in GitHub Desktop.

Select an option

Save ajankovic/2491104 to your computer and use it in GitHub Desktop.
Get current viewed node if available
<?php
/**
* Used to get the current viewed node (works when viewed in page mode).
* @param array $node_types[optional] A filter on the type of node you want to see.
* @return object The node or null if not successfull.
*/
function helper_get_current_node($node_types = array()) {
// Store the current node id, to avoid doing the URL testing
// on every call to this function. I didn't store the node itself
// because I was afraid of data changes during page processing.
// Normally node_load() already does some static caching and I think
// it handles cache updates correctly.
static $nid;
if (!isset($nid)) {
$arg = arg(); // Get URL splitted.
// What type of URL is it?
switch ($arg[0]) {
// Viewing a node or a revision of a node :
case 'node':
// If the node id is missing, null or not numeric
if (!isset($arg[1]) || is_null($arg[1]) || !is_numeric($arg[1])) {
$nid = false;
}
// Look at the 3rd part of the URL ('edit', 'view', 'revisions', ...)
if (isset($arg[2])) {
switch ($arg[2]) {
case 'view':
break;
case 'revisions':
// If we are not viewing a revision
if (!isset($arg[4]) || $arg[4] != 'view') {
$nid = false;
}
break;
default: // 'edit', 'delete', etc...
$nid = false;
}
}
// If $nid has not been set, it means we where viewing a node.
if (!isset($nid)) {
$nid = $arg[1];
}
break;
// Commenting a node :
case 'comment':
// If the URL just has /comment, or if the node id is missing or not numeric
if (!isset($arg[1]) || !isset($arg[2]) || !is_numeric($arg[2])) {
$nid = false;
}
// If $nid has not been set to false, it means we should be commenting a node.
if (!isset($nid)) {
$nid = $arg[2];
}
break;
// URL doesn't start with something relative to node viewing
default:
$nid = false;
}
} // end if $nid is not set.
// Return null if we are not viewing a node.
if (!$nid) return null;
// Load the node.
$viewedNode = node_load($nid);
// return null, if node not loaded, if node isn't the desired type
// or if the user isn't allowed to see this node.
if (!$viewedNode ||
!node_access('view', $viewedNode) ||
(count($node_types) > 0 && array_search($viewedNode->type, $node_types) === false)) {
return null;
}
return $viewedNode;
}
?>
@ajankovic
Copy link
Author

Pasted from http://drupal.org/node/160921#comment-2938906 for continence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment