1

I used $nodes = node_load_multiple(NULL, array("title" => "Foo Bar")); to fetch nodes by titles. But after going through Drupal security standards, node_load_multiple is not the right way to load all nodes.

node_load_multiple() will load ALL nodes regardless of access, so that must not be used here.

Solution suggestion is:

Use an entity query instead. "When adding a node listing to your module, be sure to use an entity query, which will add a tag of "node_access". This will allow modules dealing with node access to ensure only nodes to which the user has access are retrieved"

But I'm not sure how to apply above statement programmaticly?

Is below query the right way that solves security issues?

\Drupal\node\Entity\Node::loadMultiple(NULL, array("title" => "Foo Bar"));

If not, please suggest an appropriate alternate of loading nodes by title that respects node access grants.

2

You can do it like this. First, query the NIDs, with a query that is tagged for node access, then load the nodes with the found NIDs.

$nids = db_select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('title', $my_title)
  // The node_access tag will check access rights.
  ->addTag('node_access')
  ->execute()
  ->fetchCol();

$nodes = Node::loadMultiple($nids);

Untested in D8, but it should work.

  • That won't work in D8 as there are multiple tables. You should use an entity query instead, which includes node access by default. Otherwise correct answer – Berdir Mar 24 '17 at 22:48
  • Oops - you're right. I updated the code to deal with that. As for entity query - I haven't done any benchmarking in D8, but in D7 it (EntityFieldQuery) was significantly heavier for queries, to a level that I never used it. I'll have to do some D8 benchmarking to see if it's improved. – Jaypan Mar 24 '17 at 23:43
  • It's definitely still slower, but that's not the point. It is the only supported API when querying entities. It is technically supported to alter the node entity type and make it non-translatable or non-revisionable, which changes the table structure – Berdir Mar 25 '17 at 20:51
0

You could get all the node titles with a SQL query like:

  $row = db_query('SELECT nid FROM {node} WHERE title = :mytitle',   array(':mytitle' => $myNewTitle))->fetchField();
   if(!isset($row['nid'])) {
//safe to continue
     } else {
//that title is already there and its in node with node id "nid"
 }

And if there are no results returned then you may assume you're good to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.