diff --git a/protected_node.fork.inc b/protected_node.fork.inc
index a716c5a..345b439 100644
--- a/protected_node.fork.inc
+++ b/protected_node.fork.inc
@@ -13,8 +13,7 @@
  *
  * @return The array of nids.
  */
-function protected_node_password_nids()
-{
+function protected_node_password_nids() {
   $nids = array();
   $nids_list = explode(',', $_GET['protected_pages']);
   foreach ($nids_list as $nid) {
@@ -93,7 +92,7 @@ function protected_node_enter_any_password() {
   }
 
   // some variable initialization
-  $types = node_get_types();
+  $types = node_type_get_types();
   $node_type = $types[$node->type];
   $has_token = module_exists('token');
 
@@ -123,7 +122,7 @@ function protected_node_enter_any_password() {
     // TODO: this needs to move to {protected_node} and be loaded along the other information
     // in this case we assume the user may not have the token module
     // so we do conversions of the node type and title "by hand"
-    $node_title = variable_get('protected_node-'. $node->nid .'-show_title', FALSE);
+    $node_title = variable_get('protected_node-' . $node->nid . '-show_title', FALSE);
     if ($node_title) {
       // embellish the title with double quotes
       $node_title = '"' . $node_title . '"';
@@ -138,7 +137,7 @@ function protected_node_enter_any_password() {
   $form['protected_node_enterpassword'] = array(
     '#type' => 'fieldset',
     '#description' => $description,
-    '#collapsible' => FALSE
+    '#collapsible' => FALSE,
   );
 
   // create the password widget
@@ -153,7 +152,7 @@ function protected_node_enter_any_password() {
   $form['protected_node_enterpassword']['password'] = array(
     '#type' => 'password',
     '#title' => $label,
-    '#size' => 20
+    '#size' => 20,
   );
 
   // the node we're working on
@@ -205,7 +204,8 @@ function protected_node_enter_any_password_validate($form, &$form_state) {
   $sql = "SELECT nid FROM {protected_nodes} WHERE protected_node_passwd = '%s'"
         . " AND nid IN (" . db_placeholders($nids, 'int') . ")";
   $passwd = sha1($form['#post']['password']);
-  $nid = db_result(db_query_range($sql, array_merge(array($passwd), $nids), 0, 1));
+  // TODO Please convert this statement to the D7 database API syntax.
+  $nid = db_query_range($sql, array_merge(array($passwd), $nids))->fetchField();
   if (empty($nid)) {
     // note that global password cannot work here since we wouldn't know where
     // to send the user otherwise
@@ -225,7 +225,7 @@ function protected_node_enter_any_password_submit($form, &$form_state) {
   $nid = $form_state['values']['protected_node_selected_nid'];
   foreach ($nids as $n) {
     if ($n == $nid) {
-      $_SESSION['_protected_node']['passwords'][$n] = time();
+      $_SESSION['_protected_node']['passwords'][$n] = REQUEST_TIME;
     }
     else {
       unset($_SESSION['_protected_node']['passwords'][$n]);
diff --git a/protected_node.info b/protected_node.info
index 692c4c2..1d3e96c 100644
--- a/protected_node.info
+++ b/protected_node.info
@@ -1,6 +1,7 @@
 name = Protected Node
 description = Controls whether selected nodes are protected with a password. Works even better with the Token module.
-core = 6.x
+core = 7.x
+version = 7.x-dev
 package = Access
 recommends[] = tokens
 recommends[] = upload
diff --git a/protected_node.install b/protected_node.install
index af0691d..1a26e81 100644
--- a/protected_node.install
+++ b/protected_node.install
@@ -1,15 +1,15 @@
 <?php
-/*
+/**
  * @file
- * Protected node module: install the protected nodes schema.
+ * Install, update and uninstall functions for the protected_node module.
  */
 
 /**
- * Implementation of hook_requirements().
+ * Implements hook_requirements().
  *
  * Checks whether any role has access to protected nodes.
  *
- * @link http://api.drupal.org/api/function/hook_requirements/6
+ * @link http://api.drupal.org/api/function/hook_requirements/7
  *
  * @param string $phase  The current phase.
  */
@@ -21,14 +21,15 @@ function protected_node_requirements($phase) {
 
     // Note: since this is the runtime phase we do not have to force a
     //       load of the .module file.
-    $perms = protected_node_perm();
+    /*$perms = protected_node_perm();
 
     $likes = array();
     foreach ($perms as $perm) {
       $likes[] = "perm LIKE '%%%s%%'";
     }
     $sql = "SELECT COUNT(rid) FROM {permission} WHERE " . implode(' OR ', $likes);
-    $roles = db_result(db_query($sql, $perms));
+    // TODO Please convert this statement to the D7 database API syntax.
+    $roles = db_query($sql, $perms)->fetchField();
     if ($roles) {
       $reqs['protected_node_rights'] = array(
         'title' => t('Protected nodes access rights'),
@@ -37,7 +38,7 @@ function protected_node_requirements($phase) {
               array('!edit' => l('edit permissions',
                                'admin/user/permissions',
                                array('fragment' => 'module-protected_node')))),
-        'severity' => REQUIREMENT_OK
+        'severity' => REQUIREMENT_OK,
       );
     }
     else {
@@ -46,15 +47,16 @@ function protected_node_requirements($phase) {
         'value' => t('None of the existing roles has !access',
           array('!access' => l('permission to access protected nodes',
                                'admin/user/permissions',
-                               array('fragment' => 'module-protected_node'))
-          )
+                               array('fragment' => 'module-protected_node')))
+
         ),
         'description' => t('Without giving access to at least one role, no-one other than the administrator (UID=1) can created protected nodes or view protected nodes'),
-        'severity' => REQUIREMENT_ERROR
+        'severity' => REQUIREMENT_ERROR,
       );
-    }
+    }*/
 
     // File attachment are not currently protected
+    /**
     switch (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)) {
     case FILE_DOWNLOADS_PRIVATE:
       if (!module_exists('upload')) {
@@ -85,17 +87,18 @@ function protected_node_requirements($phase) {
       break;
 
     }
+    **/
   }
 
   return $reqs;
 }
 
 /**
- * Implementation of hook_schema().
+ * Implements hook_schema().
  */
 function protected_node_schema() {
   $schema['protected_nodes'] = array(
-    'description' => t('The table to store the node - password hash pairs.'),
+    'description' => 'The table to store the node - password hash pairs.',
     'fields' => array(
       'nid' => array(
         'description' => t('The primary identifier for a node'),
@@ -104,34 +107,34 @@ function protected_node_schema() {
         'not null' => TRUE,
       ),
       'protected_node_is_protected' => array(
-        'description' => t('Whether this node is currently protected.'),
+        'description' => 'Whether this node is currently protected.',
         'type' => 'int',
         'size' => 'small',
         'not null' => TRUE,
         'default' => 0,
       ),
       'protected_node_passwd' => array(
-        'description' => t('The sha1 hashed password for the given node.'),
+        'description' => 'The sha1 hashed password for the given node.',
         'type' => 'char',
         'length' => 40,
         'not null' => TRUE,
         'default' => '',
       ),
       'protected_node_passwd_changed' => array(
-        'description' => t('Date when the password was last changed'),
+        'description' => 'Date when the password was last changed',
         'type' => 'int',
         'not null' => TRUE,
         'default' => 0,
       ),
       'protected_node_show_title' => array(
-        'description' => t('Whether the title of the node should also be protected.'),
+        'description' => 'Whether the title of the node should also be protected.',
         'type' => 'int',
         'size' => 'small',
         'not null' => TRUE,
         'default' => 0,
       ),
       'protected_node_hint' => array(
-        'description' => t('A hint about the password on this node.'),
+        'description' => 'A hint about the password on this node.',
         'type' => 'text',
       ),
     ),
@@ -146,207 +149,23 @@ function protected_node_schema() {
 }
 
 /**
- * Implementation of hook_install().
+ * Implements hook_install().
  */
 function protected_node_install() {
-  drupal_install_schema('protected_node');
-  db_query("UPDATE {system} SET weight = 80 WHERE name = 'protected_node' AND type = 'module'");
+  db_update('system')
+    ->fields(array(
+      'weight' => 80,
+    ))
+    ->condition('name', 'protected_node')
+    ->condition('type', 'module')
+    ->execute();
 }
 
 /**
- * Implementation of hook_uninstall().
+ * Implements hook_uninstall().
  */
 function protected_node_uninstall() {
-  drupal_uninstall_schema('protected_node');
-  db_query("DELETE FROM {variable} WHERE name LIKE 'protected_node_%%'");
-}
-
-/**
- * Implementation of hook_update_N().
- *
- * We don't need a variable length column just 40 char one for the sha1 hash
- */
-function protected_node_update_3( ) {
-  $ret = array();
-
-  db_change_field($ret, 'protected_nodes', 'passwd', 'passwd', array(
-    'type' => 'char',
-    'length' => 40,
-    'not null' => TRUE
-  ));
-
-  return $ret;
-}
-
-/**
- * Implementation of hook_update-N()
- *
- * Altering node weight from 100 to 80
- * fixing issue #296685
- *
- */
-function protected_node_update_4() {
-  $ret = array();
-  $ret[] = update_sql("UPDATE {system} SET weight = 80 WHERE name = 'protected_node' AND type = 'module'");
-
-  return $ret;
+  db_delete('variable')
+    ->condition('name', 'protected_node_%%', 'LIKE')
+    ->execute();
 }
-
-/**
- * Implementation of hook_update_N().
- */
-function protected_node_update_6000() {
-  global $db_type;
-
-  $ret = array();
-
-  // we want an is_protected field so we can load it easily and
-  // we can keep the other parameters even when we unprotect
-  // a node (although it's not that important right now.)
-  $field = array(
-    'type' => 'int',
-    'size' => 'small',
-    'not null' => TRUE,
-    'default' => 0,
-  );
-  db_add_field($ret, 'protected_nodes', 'protected_node_is_protected', $field);
-  db_add_index($ret, 'protected_nodes', 'protected_is_protected', array('protected_node_is_protected'));
-
-  // at this time all the protected node entries meant that the
-  // nodes were protected; yet, we don't want the default to be 1
-  $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = 1";
-  $ret[] = update_sql($sql);
-
-  // rename the password so we can directly append to the $node object
-  // without too much potential for clashes
-  //$field = array(
-  //  'description' => t('The sha1 hashed password for the given node.'),
-  //  'type' => 'char',
-  //  'length' => 40,
-  //  'not null' => TRUE,
-  //  'default' => '',
-  //);
-  //db_change_field($ret, 'protected_nodes', 'passwd', 'protected_node_passwd', $field);
-  //
-  // Core destroys the data in this case because it uses a CAST(passwd AS char) instead
-  // of CHAR(40). (at least that breaks under PostgreSQL.)
-  // And of course MySQL does not support the RENAME COLUMN feature...
-  switch ($db_type) {
-  case 'mysql':
-  case 'mysqli':
-    $sql = "ALTER TABLE {protected_nodes} CHANGE passwd protected_node_passwd CHAR(40) NOT NULL";
-    break;
-
-  case 'pgsql': // also works in Oracle9i+
-    $sql = "ALTER TABLE {protected_nodes} RENAME COLUMN passwd TO protected_node_passwd";
-    break;
-
-  }
-  $ret[] = update_sql($sql);
-
-  // create a column for the show title flag
-  // then copy the flag status from the {variable} table
-  $field = array(
-    'description' => t('Whether the title of the node should also be protected.'),
-    'type' => 'int',
-    'size' => 'small',
-    'not null' => TRUE,
-    'default' => 0,
-  );
-  db_add_field($ret, 'protected_nodes', 'protected_node_show_title', $field);
-
-  // the variable value is TRUE, no need to read it
-  $sql_var = "SELECT name FROM {variable} WHERE name LIKE 'protected_node-%-show_title'";
-  $sql_update = "UPDATE {protected_nodes} SET protected_node_show_title = 1 WHERE nid = %d";
-  $result = db_query($sql_var);
-  $ret[] = array('success' => $result !== FALSE, 'query' => check_plain($sql_var));
-  while ($row = db_fetch_array($result)) {
-    // get the node identifier
-    preg_match('/protected_node-([0-9]+)-show_title/', $row['name'], $match);
-    // the update may do nothing if the node was deleted
-    $r = db_query($sql_update, $match[1]);
-    if ($r === FALSE) {
-      // only record failures otherwise we could get thousands of entries...
-      $ret[] = array('success' => FALSE, 'query' => check_plain($sql_update));
-    }
-    // remove the variable
-    variable_del($row['name']);
-  }
-
-  $field = array(
-    'description' => t('Date when the password was last changed'),
-    'type' => 'int',
-    'not null' => TRUE,
-    'default' => 0,
-  );
-  db_add_field($ret, 'protected_nodes', 'protected_node_passwd_changed', $field);
-
-  // request for a rebuild of the node access table
-  //node_access_needs_rebuild(TRUE);
-
-  return $ret;
-}
-
-/**
- * Implementation of hook_update_N().
- */
-function protected_node_update_6001() {
-  $ret = array();
-
-  // we want an is_protected field so we can load it easily and
-  // we can keep the other parameters even when we unprotect
-  // a node (although it's not that important right now.)
-  $field = array(
-    'description' => t('A hint about the password on this node.'),
-    'type' => 'text',
-  );
-  db_add_field($ret, 'protected_nodes', 'protected_node_hint', $field);
-
-  $result = db_query('SELECT rid, perm FROM {permission}');
-  while ($row = db_fetch_object($result)) {
-    if (strpos($row->perm, 'edit protected ') !== FALSE) {
-      $updated_perm = str_replace('edit protected content', 'edit any password', $row->perm);
-      $updated_perm = preg_replace('/edit protected ([^,]+)/', 'edit \1 password', $updated_perm);
-      $sql = "UPDATE {permission} SET perm = '%s' WHERE rid = %d";
-      $r = db_query($sql, $updated_perm, $row->rid);
-      $ret[] = array('success' => $r !== FALSE, 'query' => check_plain($sql));
-    }
-  }
-
-  return $ret;
-}
-
-/**
- * Implementation of hook_update_N().
- */
-function protected_node_update_6002() {
-  $ret = array();
-
-  // change the nid field from a serial to an int
-  $field = array(
-    'description' => t('The primary identifier for a node'),
-    'type' => 'int',
-    'unsigned' => TRUE,
-    'not null' => TRUE,
-  );
-  db_change_field($ret, 'protected_nodes', 'nid', 'nid', $field);
-
-  return $ret;
-}
-
-/**
- * Implementation of hook_update_N().
- *
- * Make sure the global password isn't saved in clear.
- * (unfortunately this doesn't fix it in backups...)
- */
-function protected_node_update_6003() {
-  $ret = array();
-
-  variable_del('protected_node_global_password_field');
-  drupal_set_message('Please, change your global Protected node password as it may have been compromised.', 'warning');
-
-  return $ret;
-}
-
-// vim: ts=2 sw=2 et syntax=php
diff --git a/protected_node.mail.inc b/protected_node.mail.inc
index 5c1ad6f..1513ed0 100644
--- a/protected_node.mail.inc
+++ b/protected_node.mail.inc
@@ -35,7 +35,7 @@ function protected_node_send_mail($node) {
 }
 
 /**
- * Implementation of hook_mail().
+ * Implements hook_mail().
  *
  * This is the function that builds the actual message body.
  */
@@ -66,5 +66,3 @@ function protected_node_mail($key, &$message, $params) {
 
   }
 }
-
-// vim: ts=2 sw=2 et syntax=php
diff --git a/protected_node.module b/protected_node.module
index ddfec7d..535538d 100644
--- a/protected_node.module
+++ b/protected_node.module
@@ -61,8 +61,8 @@ define('PROTECTED_NODE_PROTECTION_ALWAYS', 3);
 
 
 /**
- * Implementation of hook_help().
- * @link http://api.drupal.org/api/function/hook_help/6
+ * Implements hook_help().
+ * @link http://api.drupal.org/api/function/hook_help/7
  */
 function protected_node_help($path, $arg) {
   switch ($path) {
@@ -73,26 +73,41 @@ function protected_node_help($path, $arg) {
 }
 
 /**
- * Implementation of hook_perm().
- * @link http://api.drupal.org/api/function/hook_perm/6
+ * Implements hook_permission().
+ * @link http://api.drupal.org/api/function/hook_permission/7
  */
-function protected_node_perm() {
+function protected_node_permission() {
   $perms = array(
-    'access protected content',
-    'bypass password protection',
-    'edit any password',
-    'view protected content',
+    'access protected content' => array(
+      'title' => t('access protected content'),
+      'description' => t('Access password screen for protected content. Without this permission user will be denied access completely.'),
+    ),
+    'bypass password protection' => array(
+      'title' => t('bypass password protection'),
+      'description' => t('Bypass password protection'),
+    ),
+    'edit any password' => array(
+      'title' => t('edit any password'),
+      'description' => t('Edit any password'),
+    ),
+    'view protected content' => array(
+      'title' => t('view protected content'),
+      'description' => t('View potected content'),
+    ),
   );
-  foreach (array_keys(node_get_types()) as $type) {
-    $perms[] = 'edit ' . $type . ' password';
+  foreach (node_type_get_types() as $key => $type) {
+    $perms['edit ' . $key . ' password'] = array(
+      'title' => t('edit ' . $key . ' password'),
+      'description' => t('Edit password for ' . $type->name . ' nodes'),
+    );
   }
 
   return $perms;
 }
 
 /**
- * Implementation of hook_menu().
- * @link http://api.drupal.org/api/function/hook_menu/6
+ * Implements hook_menu().
+ * @link http://api.drupal.org/api/function/hook_menu/7
  */
 function protected_node_menu() {
   module_load_include('settings.inc', 'protected_node');
@@ -131,7 +146,7 @@ function protected_node_access_callback() {
         return FALSE;
       }
     }
-    else if(substr($_GET['destination'], -7) == '/delete') {
+    elseif (substr($_GET['destination'], -7) == '/delete') {
       if (!node_access('delete', $node)) {
         return FALSE;
       }
@@ -142,8 +157,8 @@ function protected_node_access_callback() {
 }
 
 /**
- * Implementation of hook_init().
- * @link http://api.drupal.org/api/function/hook_init/6
+ * Implements hook_init().
+ * @link http://api.drupal.org/api/function/hook_init/7
  */
 function protected_node_init() {
   global $user;
@@ -154,6 +169,10 @@ function protected_node_init() {
     return;
   }
 
+  if (variable_get('protected_node_use_global_password', PROTECTED_NODE_PER_NODE_PASSWORD) == PROTECTED_NODE_GLOBAL_PASSWORD && $_SESSION['has_entered_global_password']) {
+      return;
+  }
+
   $nid = FALSE;
   $param2 = arg(2);
   if (arg(0) == 'node' && is_numeric(arg(1))) {
@@ -185,11 +204,11 @@ function protected_node_init() {
   if ($nid) {
     $query = drupal_get_destination();
     if (!empty($_SERVER['HTTP_REFERER'])) {
-      $query .= '&back=' . urlencode($_SERVER['HTTP_REFERER']);
+      $query['back'] = urlencode($_SERVER['HTTP_REFERER']);
     }
-    $query .= '&protected_page=' . $nid;
+    $query['protected_page'] = $nid;
 
-    drupal_goto('protected-node', $query);
+    drupal_goto('protected-node', array('query' => $query));
   }
 }
 
@@ -205,6 +224,8 @@ function protected_node_init() {
  *         to unlock this protected node by entering the password.
  */
 function protected_node_is_locked($nid, $op = 'access') {
+  global $user;
+
   // get the node
   $node = node_load($nid);
 
@@ -218,9 +239,9 @@ function protected_node_is_locked($nid, $op = 'access') {
     // do not cache anything for anonymous users as that could make
     // the content of the page available to people who never enter
     // the password (especially with aggressive caching.)
-    if (variable_get('cache', CACHE_DISABLED)) {
+    if (variable_get('cache', 1)) {
       // prevent caching (do NOT use variable_set() since this is temporary for this session.)
-      $GLOBALS['conf']['cache'] = CACHE_DISABLED;
+      $GLOBALS['conf']['cache'] = 0;
     }
   }
   else {
@@ -267,7 +288,7 @@ function protected_node_is_locked($nid, $op = 'access') {
   if (isset($_SESSION['_protected_node']['passwords'][$nid])) {
     $when = $_SESSION['_protected_node']['passwords'][$nid];
     if ($when > variable_get('protected_node_session_timelimit', 0) // global reset time
-     && $when > $node->protected_node_passwd_changed) {  // this page reset time
+     && $when > $node->protected_node_passwd_changed) { // this page reset time
       return FALSE;
     }
     // the session is out of date, we can as well get rid of it now
@@ -299,7 +320,8 @@ function protected_node_and_attachment($filename) {
         . " FROM {files} f, {upload} u, {protected_nodes} pn, {node} n"
         . " WHERE pn.nid = u.nid AND u.nid = n.nid AND f.filename = '%s' AND u.fid = f.fid"
             . " AND pn.protected_node_is_protected = 1";
-  $file_info = db_fetch_array(db_query($sql, $filename));
+  // TODO Please convert this statement to the D7 database API syntax.
+  $file_info = db_query($sql, $filename)->fetchAssoc();
   if ($file_info === FALSE  // row doesn't exist, it's not protected
    || ($user->uid && $user->uid == $file_info['uid'])) { // $user is the author
     return FALSE;
@@ -347,13 +369,13 @@ function protected_node_and_attachment($filename) {
  */
 function protected_node_invoke($hook, &$param) {
   foreach (module_implements($hook) as $module) {
-    call_user_func($module .'_'. $hook, $param);
+    call_user_func($module . '_' . $hook, $param);
   }
 }
 
 /**
- * Implementation of hook_form_alter().
- * @link http://api.drupal.org/api/function/hook_form_alter/6
+ * Implements hook_form_alter().
+ * @link http://api.drupal.org/api/function/hook_form_alter/7
  *
  * Add the protected node form widgets assuming the user editing this
  * node as permission to do so on this type of node.
@@ -366,11 +388,11 @@ function protected_node_invoke($hook, &$param) {
  * @param[in] $form_id  The name of the form being modified
  */
 function protected_node_form_alter(&$form, &$form_state, $form_id) {
-  if ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
+  if ($form_id == 'node_type_form' && isset($form['#node_type'])) {
     module_load_include('settings.inc', 'protected_node');
     protected_node_node_type_form_alter($form);
   }
-  elseif (isset($form['type']['#value']) && $form['#id'] == 'node-form'
+  elseif (isset($form['type']['#value']) &&  substr($form['#id'], -9) == 'node-form'
   && (user_access('edit any password') || user_access('edit ' . $form['type']['#value'] . ' password'))) {
     module_load_include('settings.inc', 'protected_node');
     protected_node_node_form_alter($form);
@@ -378,158 +400,190 @@ function protected_node_form_alter(&$form, &$form_state, $form_id) {
 }
 
 /**
- * Implementation of hook_nodeapi().
- * @link http://api.drupal.org/api/function/hook_nodeapi/6
+ * Implements hook_node_load().
  */
-function protected_node_nodeapi(&$node, $op, $arg = 0, $page = 0) {
-  global $user;
-  // ugly but we want to keep some variables between the validation and insert/update
-  global $_protected_node_emails;
-  global $_protected_node_random_passwd;
-
-  switch ($op) {
-  case 'load':
-    return protected_node_load($node);
+function protected_node_node_load($node, $types) {
+  return protected_node_load($node);
+}
 
-  case 'validate':
-    $_protected_node_emails = '';
-    $_protected_node_random_passwd = '';
-    if ($node->protected_node_is_protected
-    && (user_access('edit any password') || user_access('edit ' . $node->type . ' password'))) {
-      $missing_password = FALSE;
-      if (empty($node->protected_node_passwd)) {
-        // password missing in database too?
-        $sql = "SELECT protected_node_passwd FROM {protected_nodes} WHERE nid = %d";
-        $result = trim(db_result(db_query($sql, $node->nid))); // getting "    " (40 spaces) when empty
-        if (empty($result)) {
-          $missing_password = TRUE;
-        }
-      }
+/**
+ * Implements hook_node_validate().
+ */
+function protected_node_node_validate($node, $form) {
+  $_protected_node_emails = '';
+  $_protected_node_random_passwd = '';
+  if ($node->protected_node_is_protected
+     && (user_access('edit any password') || user_access('edit ' . $node->type . ' password'))) {
+    $missing_password = FALSE;
+    if (empty($node->protected_node_passwd)) {
+      // password missing in database too?
+      $sql = "SELECT protected_node_passwd FROM {protected_nodes} WHERE nid = %d";
+      $result = trim(db_query("SELECT protected_node_passwd FROM {protected_nodes} WHERE nid = :nid", array(':nid' => $node->nid))->fetchField()); // getting "    " (40 spaces) when empty
+      if (empty($result)) {
+        $missing_password = TRUE;
+       }
+    }
 
-      if (!empty($node->protected_node_emails)) {
-        if ($node->status) {
-          // verify each email address
-          $emails = explode(',', str_replace(array("\r", "\n"), ',', $node->protected_node_emails));
-          foreach ($emails as $k => $m) {
-            $m = trim($m);
-            if ($m) {
-              if (!valid_email_address($m)) {
-                form_error($arg['protected_node']['protected_node_emails'], t('Invalid email address: @m. Please correct this mistake and try again.', array('@m' => $m)));
-                unset($emails[$k]); // unset just in case; should be useless though
-              }
-              else {
-                $emails[$k] = $m;
-              }
+    if (!empty($node->protected_node_emails)) {
+      if ($node->status) {
+        // verify each email address
+        $emails = explode(',', str_replace(array("\r", "\n"), ',', $node->protected_node_emails));
+        foreach ($emails as $k => $m) {
+          $m = trim($m);
+          if ($m) {
+            if (!valid_email_address($m)) {
+              form_error($arg['protected_node']['protected_node_emails'], t('Invalid email address: @m. Please correct this mistake and try again.', array('@m' => $m)));
+              unset($emails[$k]); // unset just in case; should be useless though
             }
             else {
-              // ignore empty entries
-              unset($emails[$k]);
+              $emails[$k] = $m;
             }
           }
-          $_protected_node_emails = implode(', ', $emails);
-          if ($_protected_node_emails && $missing_password && variable_get('protected_node_random_password', FALSE)) {
-            // automatically generate a password for the email (note that means the author won't know the password!)
-            $_protected_node_random_passwd = user_password();
-            $missing_password = FALSE; // not missing anymore
-            drupal_set_message('A random password was generated in order to send the email about this page. Remember that changing the password will prevent users you just emailed from accessing this page.', 'warning');
+          else {
+            // ignore empty entries
+            unset($emails[$k]);
           }
         }
-        else {
-          // the node is not published, forget about emails!
-          form_error($arg['protected_node']['protected_node_emails'], t('Email addresses were specified even though the password is turned off.'));
+        $_protected_node_emails = implode(', ', $emails);
+        if ($_protected_node_emails && $missing_password && variable_get('protected_node_random_password', FALSE)) {
+          // automatically generate a password for the email (note that means the author won't know the password!)
+          $_protected_node_random_passwd = user_password();
+          $missing_password = FALSE; // not missing anymore
+          drupal_set_message('A random password was generated in order to send the email about this page. Remember that changing the password will prevent users you just emailed from accessing this page.', 'warning');
         }
       }
-
-      if ($missing_password) {
-        if ($user->uid == 0) {
-          // if anonymous user, then global password is not an option otherwise
-          // all the nodes could be edited by all the anonymous users!
-          $global_password = PROTECTED_NODE_PER_NODE_PASSWORD;
-        }
-        else {
-          $global_password = variable_get('protected_node_use_global_password', PROTECTED_NODE_PER_NODE_PASSWORD);
-        }
-        switch ($global_password) {
+      else {
+        // the node is not published, forget about emails!
+        form_error($arg['protected_node']['protected_node_emails'], t('Invalid email address: @m. Please correct this mistake and try again.', array('@m' => $m)));
+      }
+    }
+    if ($missing_password) {
+      global $user;
+      if ($user->uid == 0) {
+        // if anonymous user, then global password is not an option otherwise
+        // all the nodes could be edited by all the anonymous users!
+        $global_password = PROTECTED_NODE_PER_NODE_PASSWORD;
+      }
+      else {
+        $global_password = variable_get('protected_node_use_global_password', PROTECTED_NODE_PER_NODE_PASSWORD);
+      }
+      switch ($global_password) {
         case PROTECTED_NODE_PER_NODE_PASSWORD:
           // $arg is the form in this case
           form_error($arg['protected_node']['protected_node_passwd'], t('To protect this page, please enter a password.'));
           break;
-
-        }
       }
     }
-    elseif (isset($node->protected_node_emails) && trim($node->protected_node_emails)) {
-      form_error($arg['protected_node']['protected_node_emails'], t('No email can be sent by the protected node module when the node is not protected or you do not have permission to set a password.'));
+  }
+  elseif (isset($node->protected_node_emails) && trim($node->protected_node_emails)) {
+    form_error($arg['protected_node']['protected_node_emails'], t('No email can be sent by the protected node module when the node is not protected or you do not have permission to set a password.'));
+  }
+}
+
+/**
+ * Implements hook_node_insert().
+ */
+function protected_node_node_insert($node) {
+
+  // ugly but we want to keep some variables between the validation and insert/update
+  global $_protected_node_emails;
+  global $_protected_node_random_passwd;
+
+  if (user_access('edit any password') || user_access('edit ' . $node->type . ' password')) {
+    if (!empty($_protected_node_random_passwd)) {
+      $node->protected_node_passwd = $_protected_node_random_passwd;
     }
-    break;
+    if (!empty($_protected_node_emails)) {
+      $node->protected_node_emails = $_protected_node_emails;
+    }
+    _protected_node_save($node);
+    if ($node->protected_node_is_protected && !empty($node->protected_node_emails)) {
+      module_load_include('mail.inc', 'protected_node');
+      protected_node_send_mail($node);
+    }
+  }
+}
 
-  case 'insert':
-  case 'update':
-    if (user_access('edit any password') || user_access('edit ' . $node->type . ' password')) {
-      if (!empty($_protected_node_random_passwd)) {
-        $node->protected_node_passwd = $_protected_node_random_passwd;
-      }
-      if (!empty($_protected_node_emails)) {
-        $node->protected_node_emails = $_protected_node_emails;
-      }
-      protected_node_save($node);
-      if ($node->protected_node_is_protected && !empty($node->protected_node_emails)) {
-        module_load_include('mail.inc', 'protected_node');
-        protected_node_send_mail($node);
-      }
+/**
+ * Implements hook_node_update().
+ */
+function protected_node_node_update($node) {
+
+  // ugly but we want to keep some variables between the validation and insert/update
+  global $_protected_node_emails;
+  global $_protected_node_random_passwd;
+
+  if (user_access('edit any password') || user_access('edit ' . $node->type . ' password')) {
+    if (!empty($_protected_node_random_passwd)) {
+      $node->protected_node_passwd = $_protected_node_random_passwd;
+    }
+    if (!empty($_protected_node_emails)) {
+      $node->protected_node_emails = $_protected_node_emails;
+    }
+    _protected_node_save($node);
+    if ($node->protected_node_is_protected && !empty($node->protected_node_emails)) {
+      module_load_include('mail.inc', 'protected_node');
+      protected_node_send_mail($node);
     }
-    break;
-
-  case 'view':
-    if (!empty($node->protected_node_is_protected)) {
-      // Accessed for search indexing? (usually by cron.php)
-      if ($node->build_mode == NODE_BUILD_SEARCH_INDEX) {
-        // "user" could see the node, but at this time, not its contents
-        // (the current user is Anonymous, so that statement is not exactly true,
-        // but at the time of the search index building we cannot know who will
-        // be searching so we let go without the access denied error.)
-        protected_node_invoke('protected_node_hide', $node);
+  }
+}
+
+/**
+ * Implements hook_node_view().
+ */
+function protected_node_node_view($node, $view_mode = 'full') {
+  global $user;
+  if (!empty($node->protected_node_is_protected)) {
+    // Accessed for search indexing? (usually by cron.php)
+    if ($view_mode == 'search_index') {
+      // "user" could see the node, but at this time, not its contents
+      // (the current user is Anonymous, so that statement is not exactly true,
+      // but at the time of the search index building we cannot know who will
+      // be searching so we let go without the access denied error.)
+      protected_node_invoke('protected_node_hide', $node);
+    }
+    elseif (!user_access('bypass password protection') && !user_access('view protected content')) {
+      if (!$user->uid && variable_get('cache', 1)) {
+        // prevent caching (do NOT use variable_set() since this is temporary for this session.)
+        $GLOBALS['conf']['cache'] = 0;
       }
-      elseif (!user_access('bypass password protection') && !user_access('view protected content')) {
-        if (!$user->uid && variable_get('cache', CACHE_DISABLED)) {
-          // prevent caching (do NOT use variable_set() since this is temporary for this session.)
-          $GLOBALS['conf']['cache'] = CACHE_DISABLED;
-        }
 
-        if ($node->uid !== $user->uid) {
-          // is there a password?
-          if (isset($_SESSION['_protected_node']['passwords'][$node->nid])) {
-            // is password out of date?
-            $when = $_SESSION['_protected_node']['passwords'][$node->nid];
-            if ($when <= variable_get('protected_node_session_timelimit', 0) // global reset time
-             || $when <= $node->protected_node_passwd_changed) {  // this page reset time
-              unset($_SESSION['_protected_node']['passwords'][$node->nid]);
-            }
+      if ($node->uid !== $user->uid) {
+        // is there a password?
+        if (isset($_SESSION['_protected_node']['passwords'][$node->nid])) {
+          // is password out of date?
+          $when = $_SESSION['_protected_node']['passwords'][$node->nid];
+          if ($when <= variable_get('protected_node_session_timelimit', 0) // global reset time
+           || $when <= $node->protected_node_passwd_changed) {  // this page reset time
+            unset($_SESSION['_protected_node']['passwords'][$node->nid]);
           }
-          if (!isset($_SESSION['_protected_node']['passwords'][$node->nid])) {
-            if (!user_access('access protected content')) {
-              // user will never be given access (no drupal_goto() call necessary)
-              drupal_access_denied();
-              exit();
-            }
-            // user could see the node, but at this time, not its contents
-            protected_node_invoke('protected_node_hide', $node);
+        }
+        if (!isset($_SESSION['_protected_node']['passwords'][$node->nid])) {
+          if (!user_access('access protected content')) {
+            // user will never be given access (no drupal_goto() call necessary)
+            drupal_access_denied();
+            exit();
           }
+          // user could see the node, but at this time, not its contents
+          protected_node_invoke('protected_node_hide', $node);
         }
       }
     }
-    break;
-
-  case 'delete':
-    db_query('DELETE FROM {protected_nodes} WHERE nid = %d', $node->nid);
-    break;
-
   }
 }
 
+/**
+ * Implements hook_node_delete().
+ */
+function protected_node_node_delete($node) {
+  db_delete('protected_nodes')
+    ->condition('nid', $node->nid)
+    ->execute();
+}
+
 
 /**
- * Implementation of hook_protected_node_hide().
+ * Implements hook_protected_node_hide().
  *
  * We implement this callback since it makes sense (I think) although
  * it makes the module a bit slower.
@@ -551,8 +605,7 @@ function protected_node_protected_node_hide(&$node) {
 
 
 /**
- * Implementation of hook_file_download().
- * @link http://api.drupal.org/api/function/hook_file_download/6
+ * Implements hook_file_download().
  */
 function protected_node_file_download($file) {
   global $user;
@@ -570,6 +623,7 @@ function protected_node_file_download($file) {
         . " FROM {files} f, {upload} u, {protected_nodes} pn, {node} n"
         . " WHERE pn.nid = u.nid AND u.nid = n.nid AND f.filename = '%s' AND u.fid = f.fid"
             . " AND pn.protected_node_is_protected = 1";
+  // TODO Please convert this statement to the D7 database API syntax.
   $file_info = db_fetch_array(db_query($sql, $file));
   if ($file_info === FALSE  // row doesn't exist, it's not protected
    || ($user->uid && $user->uid == $file_info['uid'])) { // $user is the author
@@ -603,12 +657,12 @@ function protected_node_file_download($file) {
  * @param[in,out] object $node The node to be saved.
  * @return boolean TRUE if the action was successful, FALSE otherwise.
  */
-function protected_node_save(&$node) {
+function _protected_node_save(&$node) {
   // we first test whether a protected_nodes entry exist so we can use UPDATE
   // or INSERT accordingly (UPDATE does not always properly report working
   // with MySQL.)
   // We also retrive nid because protected_node_passwd may exist and be empty
-  $result = db_fetch_array(db_query("SELECT nid, protected_node_passwd FROM {protected_nodes} WHERE nid = %d", $node->nid));
+  $result = db_query("SELECT nid, protected_node_passwd FROM {protected_nodes} WHERE nid = :nid", array(':nid' => $node->nid))->fetchAssoc();
   if (!empty($result)) {
     // note: the following test prevents the user from using "0"
     //       as a password.
@@ -628,43 +682,40 @@ function protected_node_save(&$node) {
       $changed = FALSE;
       $node->protected_node_passwd = $result['protected_node_passwd'];
     }
-    $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = %d,"
-            . " protected_node_passwd = '%s', protected_node_show_title = %d,"
-            . " protected_node_hint = '%s'";
     $args = array(
-      $node->protected_node_is_protected,
-      $node->protected_node_passwd,
-      $node->protected_node_show_title,
-      isset($node->protected_node_hint) ? $node->protected_node_hint : '',
-    );
+      'protected_node_is_protected' => $node->protected_node_is_protected,
+      'protected_node_passwd' =>$node->protected_node_passwd,
+      'protected_node_show_title' => $node->protected_node_show_title,
+      'protected_node_hint' => isset($node->protected_node_hint) ? $node->protected_node_hint : '',
+     );
     if ($changed) {
-      $sql .= ", protected_node_passwd_changed = %d";
-      $args[] = time(); // last time the password was changed (i.e. invalidate all existing sessions)
+      $args['protected_node_passwd_changed'] = REQUEST_TIME;
     }
-    $sql .= " WHERE nid = %d";
-    $args[] = $node->nid;
-    db_query($sql, $args);
+    $num_updated = db_update('protected_nodes')
+      ->fields($args)
+      ->condition('nid', $node->nid)
+      ->execute();
   }
   else {
     if (!isset($node->protected_node_passwd)) {
       // this happens when the global password is to be used
       $node->protected_node_passwd = '';
     }
-    elseif($node->protected_node_passwd) {
+    elseif ($node->protected_node_passwd) {
       $node->protected_node_clear_passwd = $node->protected_node_passwd;
       $node->protected_node_passwd = sha1($node->protected_node_passwd);
     }
     // we don't need to set the protected_node_passwd_changed since no
     // one has ever entered a password for this node
-    $sql = "INSERT INTO {protected_nodes} (protected_node_is_protected,"
-            . " protected_node_passwd, protected_node_show_title, nid,"
-            . " protected_node_hint)"
-            . " VALUES (%d, '%s', %d, %d, '%s')";
-    db_query($sql, $node->protected_node_is_protected,
-                   $node->protected_node_passwd,
-                   $node->protected_node_show_title,
-                   $node->nid,
-                   isset($node->protected_node_hint) ? $node->protected_node_hint : '');
+    $nid = db_insert('protected_nodes')
+      ->fields(array(
+        'protected_node_is_protected' => $node->protected_node_is_protected,
+        'protected_node_passwd' => $node->protected_node_passwd,
+        'protected_node_show_title' => $node->protected_node_show_title,
+        'nid' => $node->nid,
+        'protected_node_hint' => isset($node->protected_node_hint) ? $node->protected_node_hint : ''
+      ))
+      ->execute();
   }
 }
 
@@ -675,56 +726,58 @@ function protected_node_save(&$node) {
  *
  * @return An array with the node extended fields or FALSE.
  */
-function protected_node_load($node) {
-  // valid input parameters?
-  if (!is_object($node) || !is_numeric($node->nid)) {
-    return FALSE;
-  }
+function protected_node_load($nodes) {
+  foreach ($nodes as $nid => &$node) {
+    // valid input parameters?
+    if (!is_object($node) || !is_numeric($node->nid)) {
+      return FALSE;
+    }
 
-  // default fields for protected nodes
-  static $default_fields = array(
-    'protected_node_is_protected' => FALSE,
-    'protected_node_passwd' => '',
-    'protected_node_passwd_changed' => 0,
-    'protected_node_show_title' => 0,
-    'protected_node_hint' => '',
-  );
+    // default fields for protected nodes
+    static $default_fields = array(
+      'protected_node_is_protected' => FALSE,
+      'protected_node_passwd' => '',
+      'protected_node_passwd_changed' => 0,
+      'protected_node_show_title' => 0,
+      'protected_node_hint' => '',
+    );
 
-  // can the node be protected at all?
-  $protection = variable_get('protected_node_protection_' . $node->type, PROTECTED_NODE_PROTECTION_PROTECTABLE);
-  if ($protection == PROTECTED_NODE_PROTECTION_NEVER) {
-    // by default the node is not protected, return that
-    return $default_fields;
-  }
+    // can the node be protected at all?
+    $protection = variable_get('protected_node_protection_' . $node->type, PROTECTED_NODE_PROTECTION_PROTECTABLE);
+    if ($protection == PROTECTED_NODE_PROTECTION_NEVER) {
+      // by default the node is not protected, return that
+      return $default_fields;
+    }
 
-  $sql = "SELECT protected_node_is_protected, protected_node_passwd, protected_node_passwd_changed,"
-            . " protected_node_show_title, protected_node_hint FROM {protected_nodes} WHERE nid = %d";
-  $result = db_fetch_array(db_query($sql, $node->nid));
-  if (!is_array($result)) {
-    // the SELECT failed, use the defaults
-    $result = $default_fields;
-  }
-  else {
-    // define any missing field
-    $result += $default_fields;
-  }
+    $result = db_query("SELECT protected_node_is_protected, protected_node_passwd, protected_node_passwd_changed, protected_node_show_title, protected_node_hint FROM {protected_nodes} WHERE nid = :nid", array(':nid' => $node->nid))->fetchAssoc();
+    if (!is_array($result)) {
+      // the SELECT failed, use the defaults
+      $result = $default_fields;
+    }
+    else {
+      // define any missing field
+      $result += $default_fields;
+    }
 
-  // the password is a CHAR(40) and when empty it's all spaces
-  // (this is possible when the global password is used)
-  $result['protected_node_passwd'] = trim($result['protected_node_passwd']);
+    // the password is a CHAR(40) and when empty it's all spaces
+    // (this is possible when the global password is used)
+    $result['protected_node_passwd'] = trim($result['protected_node_passwd']);
 
-  // if the user changed the mode to "always protected" then we force that here
-  // it means the node may not be accessible to people without administration
-  // privileges since it may not have a default password
-  if ($protection == PROTECTED_NODE_PROTECTION_ALWAYS) {
-    $result['protected_node_is_protected'] = TRUE;
-  }
+    // if the user changed the mode to "always protected" then we force that here
+    // it means the node may not be accessible to people without administration
+    // privileges since it may not have a default password
+    if ($protection == PROTECTED_NODE_PROTECTION_ALWAYS) {
+      $result['protected_node_is_protected'] = TRUE;
+    }
 
-  return $result;
+    foreach ($result as $property => &$value) {
+      $node->$property = $value;
+    }
+  }
 }
 
 /**
- * Implementation of hook_token_list().
+ * Implements hook_token_list().
  *
  * This function defines some extras for the protected node (i.e. whether a
  * node is protected, title flag, last time the password was changed, etc.)
@@ -740,7 +793,7 @@ function protected_node_token_list($type = 'all') {
 }
 
 /**
- * Implementation of hook_node_type().
+ * Implements hook_node_type_delete().
  *
  * This function deletes the variables corresponding to the fields added
  * to the node type form.
@@ -748,20 +801,15 @@ function protected_node_token_list($type = 'all') {
  * @param[in] $op  The operation performed on the node type.
  * @param[in] $type  The type object concerned.
  */
-function protected_node_node_type($op, $type) {
-  switch ($op) {
-  case 'delete':
-    variable_del('protected_node_fieldset_' . $type->type);
-    variable_del('protected_node_protection_' . $type->type);
-    variable_del('protected_node_node_type_password_' . $type->type);
-    variable_del('protected_node_node_type_password_field_' . $type->type); // should already be deleted by the submit()
-    break;
-
-  }
+function protected_node_node_type_delete($info) {
+  variable_del('protected_node_fieldset_' . $info->type);
+  variable_del('protected_node_protection_' . $info->type);
+  variable_del('protected_node_node_type_password_' . $info->type);
+  variable_del('protected_node_node_type_password_field_' . $info->type); // should already be deleted by the submit()
 }
 
 /**
- * Implementation of hook_token_values().
+ * Implements hook_token_values().
  */
 function protected_node_token_values($type, $object = NULL, $options = array()) {
   if ($type == 'node' && $object) {
@@ -796,7 +844,7 @@ function protected_node_autocomplete_off($form_element, &$form_state) {
 }
 
 /**
- * Implementation of hook_db_rewrite_sql().
+ * Implements hook_db_rewrite_sql().
  *
  * This hook forbids end users from seeing a node they do not otherwise have
  * access to without a password.
@@ -880,18 +928,23 @@ function protected_node_set_protected($param, $passwd = NULL) {
 
   if (empty($node->protected_node_is_protected)) {
     // node exists in our table?
-    $r = db_result(db_query("SELECT nid FROM {protected_nodes} WHERE nid = %d", $node->nid));
+    $r = db_query("SELECT nid FROM {protected_nodes} WHERE nid = :nid", array(':nid' => $node->nid))->fetchField();
     if ($r) {
       if (empty($passwd)) {
         // in this case, an empty password is fine
-        $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = 1 WHERE nid = %d";
-        $result = db_query($sql, $node->nid) !== FALSE;
+        $result = db_update('protected_nodes')
+          ->fields(array(
+            'protected_node_is_protected' => 1,
+          ))
+          ->condition('nid', $node->nid)
+          ->execute() !== FALSE;
       }
       else {
         // we have to also update the password in this case
         $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = 1,"
             . " protected_node_passwd = '%s', protected_node_passwd_changed = %d WHERE nid = %d";
-        $result = db_query($sql, sha1($passwd), time(), $node->nid) !== FALSE;
+        // TODO Please convert this statement to the D7 database API syntax.
+        $result = db_query($sql, sha1($passwd), REQUEST_TIME, $node->nid) !== FALSE;
       }
     }
     else {
@@ -905,6 +958,7 @@ function protected_node_set_protected($param, $passwd = NULL) {
       $sql = "INSERT INTO {protected_nodes} (protected_node_is_protected,"
               . " protected_node_passwd, protected_node_show_title, nid)"
               . " VALUES (1, '%s', %d, %d)";
+      // TODO Please convert this statement to the D7 database API syntax.
       $result = db_query($sql, $passwd,
                      variable_get('protected_node_show_node_titles', FALSE),
                      $node->nid) !== FALSE;
@@ -917,8 +971,13 @@ function protected_node_set_protected($param, $passwd = NULL) {
       return TRUE;
     }
 
-    $sql = "UPDATE {protected_nodes} SET protected_node_passwd = '%s', protected_node_passwd_changed = %d WHERE nid = %d";
-    $result = db_query($sql, sha1($passwd), time(), $node->nid) !== FALSE;
+    $result = db_update('protected_nodes')
+      ->fields(array(
+          'protected_node_passwd' => sha1($passwd),
+          'protected_node_passwd_changed' => REQUEST_TIME,
+        ))
+      ->condition('nid', $node->nid)
+      ->execute() !== FALSE;
   }
 
   return $result;
@@ -932,9 +991,14 @@ function protected_node_set_protected($param, $passwd = NULL) {
  * @return TRUE if the node was protected before the call, FALSE otherwise.
  */
 function protected_node_unset_protected($nid) {
-  $r = db_result(db_query("SELECT protected_node_is_protected FROM {protected_nodes} WHERE nid = %d", $nid)) == 1;
+  $r = db_query("SELECT protected_node_is_protected FROM {protected_nodes} WHERE nid = :nid", array(':nid' => $nid))->fetchField() == 1;
 
-  db_query("UPDATE {protected_nodes} SET protected_node_is_protected = 0 WHERE nid = %d", $nid);
+  db_update('protected_nodes')
+    ->fields(array(
+      'protected_node_is_protected' => 0,
+    ))
+    ->condition('nid', $nid)
+    ->execute();
 
   return $r;
 }
@@ -954,7 +1018,7 @@ function protected_node_isset_protected($nid) {
     return FALSE;
   }
 
-  return db_result(db_query("SELECT protected_node_is_protected FROM {protected_nodes} WHERE nid = %d", $nid)) == 1;
+  return db_query("SELECT protected_node_is_protected FROM {protected_nodes} WHERE nid = :nid", array(':nid' => $nid))->fetchField() == 1;
 }
 
 /**
@@ -967,7 +1031,7 @@ function protected_node_isset_protected($nid) {
  *
  * @param[in] $nid  The node to lock.
  *
- * @return TRUE if the node gets unlocked. 
+ * @return TRUE if the node gets unlocked.
  */
 function protected_node_lock($nid) {
   if (is_numeric($nid) && isset($_SESSION['_protected_node']['passwords'][$nid])) {
@@ -990,24 +1054,9 @@ function protected_node_unlock($nid) {
     // make sure the node exists
     $node = node_load($nid);
     if ($node->protected_node_is_protected) {
-      $_SESSION['_protected_node']['passwords'][$nid] = time();
+      $_SESSION['_protected_node']['passwords'][$nid] = REQUEST_TIME;
       return TRUE;
     }
   }
   return FALSE;
 }
-
-/** @brief WebFM support.
- *
- * Check webfm file access. In this case, we just check whether the
- * node is protected for the current user.
- *
- * @param[out] $access  Variable whether the access result is saved.
- * @param[in] $node  Node being checked.
- * @param[in] $fid  File being checked.
- */
-function protected_node_webfm_file_access_alter(&$access, $node, $fid) {
-  $access = !protected_node_is_locked($node->nid, 'view');
-}
-
-// vim: ts=2 sw=2 et syntax=php
diff --git a/protected_node.redirect.inc b/protected_node.redirect.inc
index e29b566..b300d34 100644
--- a/protected_node.redirect.inc
+++ b/protected_node.redirect.inc
@@ -47,7 +47,7 @@ function protected_node_enterpassword() {
   }
 
   // some variable initialization
-  $types = node_get_types();
+  $types = node_type_get_types();
   $node_type = $types[$node->type];
   $has_token = module_exists('token');
 
@@ -55,8 +55,8 @@ function protected_node_enterpassword() {
   $title = variable_get('protected_node_title', NULL);
   if (!empty($title)) {
     if ($has_token) {
-      $title = token_replace($title, 'node', $node);
-      $title = token_replace($title, 'user', $user);
+      $title = token_replace($title, array('node' => $node));
+      $title = token_replace($title, array('user' => $user));
     }
     drupal_set_title($title);
   }
@@ -64,8 +64,8 @@ function protected_node_enterpassword() {
   // information appear between the title and the password form
   $info = variable_get('protected_node_info', '');
   if ($has_token) {
-    $info = token_replace($info, 'node', $node);
-    $info = token_replace($info, 'user', $user);
+    $info = token_replace($info, array('node' => $node));
+    $info = token_replace($info, array('user' => $user));
   }
   $form['protected_node'] = array(
     '#value' => $info,
@@ -77,7 +77,7 @@ function protected_node_enterpassword() {
     // TODO: this needs to move to {protected_node} and be loaded along the other information
     // in this case we assume the user may not have the token module
     // so we do conversions of the node type and title "by hand"
-    $node_title = variable_get('protected_node-'. $node->nid .'-show_title', FALSE);
+    $node_title = variable_get('protected_node-' . $node->nid . '-show_title', FALSE);
     if ($node_title) {
       // embellish the title with double quotes
       $node_title = '"' . $node_title . '"';
@@ -86,20 +86,20 @@ function protected_node_enterpassword() {
                      array('@node_type' => $node_type->name, '@node_title' => $node_title));
   }
   elseif ($has_token) {
-    $description = token_replace($description, 'node', $node);
-    $description = token_replace($description, 'user', $user);
+    $description = token_replace($description, array('node' => $node));
+    $description = token_replace($description, array('user' => $user));
   }
   $form['protected_node_enterpassword'] = array(
     '#type' => 'fieldset',
     '#description' => $description,
-    '#collapsible' => FALSE
+    '#collapsible' => FALSE,
   );
 
   // create the password widget
   $label = variable_get('protected_node_password_label', '');
   if ($label) {
-    $label = token_replace($label, 'node', $node);
-    $label = token_replace($label, 'user', $user);
+    $label = token_replace($label, array('node' => $node));
+    $label = token_replace($label, array('user' => $user));
   }
   else {
     $label = t('@node_type password', array('@node_type' => $node_type->name));
@@ -107,7 +107,7 @@ function protected_node_enterpassword() {
   $form['protected_node_enterpassword']['password'] = array(
     '#type' => 'password',
     '#title' => $label,
-    '#size' => 20
+    '#size' => 20,
   );
 
   // the node we're working on
@@ -146,38 +146,38 @@ function protected_node_enterpassword_validate($form, &$form_state) {
   //       password (i.e. extract local password instead of comparing!)
   // TODO: the protected_node_nid parameter should be extracted from the destination URI
   $sql = "SELECT nid FROM {protected_nodes} WHERE protected_node_passwd = '%s' AND nid = %d";
-  $passwd = sha1($form['#post']['password']);
-  $nid = db_result(db_query($sql, $passwd, $form_state['values']['protected_node_nid']));
+  $passwd = sha1($form_state['values']['password']);
+  $nid = db_query("SELECT nid FROM {protected_nodes} WHERE protected_node_passwd = :protected_node_passwd AND nid = :nid", array(':protected_node_passwd' => $passwd, ':nid' => $form_state['values']['protected_node_nid']))->fetchField();
   if (empty($nid)) {
     switch (variable_get('protected_node_use_global_password', PROTECTED_NODE_PER_NODE_PASSWORD)) {
-    case PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD:
-    case PROTECTED_NODE_GLOBAL_PASSWORD:
-      $global_passwd = variable_get('protected_node_global_password', '');
-      if ($global_passwd == $passwd) {
-        $nid = 1;
-      }
-      else {
-        // this comes last so we avoid loading the node if another password matches
-        // although that means the main global password has priority which may, in the
-        // long run, be a problem (but since the result is the same, I don't foresee
-        // this being a problem at all.)
-        $node = node_load($form_state['values']['protected_node_nid']);
-        $node_type_passwd = variable_get('protected_node_node_type_password_' . $node->type, '');
-        if ($node_type_passwd == $passwd) {
+      case PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD:
+      case PROTECTED_NODE_GLOBAL_PASSWORD:
+        $global_passwd = variable_get('protected_node_global_password', '');
+        if ($global_passwd == $passwd) {
+          $_SESSION['has_entered_global_password'] = 1;
           $nid = 1;
         }
-      }
-      if (!empty($nid)) {
-        // the user found a global password
-        // was the protected node created by an anonymous user?
-        // if so, prevent the use of any global password
-        $sql = "SELECT created FROM {node} WHERE nid = %d AND uid = 0";
-        $created = db_result(db_query($sql, $form_state['values']['protected_node_nid']));
-        if ($created) {
-          $nid = FALSE;
+        else {
+          // this comes last so we avoid loading the node if another password matches
+          // although that means the main global password has priority which may, in the
+          // long run, be a problem (but since the result is the same, I don't foresee
+          // this being a problem at all.)
+          $node = node_load($form_state['values']['protected_node_nid']);
+          $node_type_passwd = variable_get('protected_node_node_type_password_' . $node->type, '');
+          if ($node_type_passwd == $passwd) {
+            $nid = 1;
+          }
         }
-      }
-      break;
+        if (!empty($nid)) {
+          // the user found a global password
+          // was the protected node created by an anonymous user?
+          // if so, prevent the use of any global password
+          $created = db_query("SELECT created FROM {node} WHERE nid = :nid AND uid = :uid", array(':nid' => $form_state['values']['protected_node_nid'], ':uid' => 0))->fetchField();
+          if ($created) {
+            $nid = FALSE;
+          }
+        }
+        break;
 
     }
     if (empty($nid)) {
@@ -191,7 +191,7 @@ function protected_node_enterpassword_validate($form, &$form_state) {
  */
 function protected_node_enterpassword_submit($form, &$form_state) {
   // TODO: the protected_node_nid parameter should be extracted from the destination URI
-  $_SESSION['_protected_node']['passwords'][$form_state['values']['protected_node_nid']] = time();
+  $_SESSION['_protected_node']['passwords'][$form_state['values']['protected_node_nid']] = REQUEST_TIME;
 }
 
 // vim: ts=2 sw=2 et syntax=php
diff --git a/protected_node.settings.inc b/protected_node.settings.inc
index eb36b78..cbe9550 100644
--- a/protected_node.settings.inc
+++ b/protected_node.settings.inc
@@ -58,13 +58,13 @@ Thank you.
 function protected_node_menu_array() {
   $items = array();
 
-  $items['admin/settings/protected_node'] = array(
+  $items['admin/config/protected_node'] = array(
     'title' => 'Protected node',
     'description' => 'Edit the global Protected node settings',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('protected_node_admin_settings'),
     'access arguments' => array('administer site configuration'),
-    'file' => 'protected_node.settings.inc'
+    'file' => 'protected_node.settings.inc',
   );
   $items['protected-node'] = array(
     'title' => 'Protected page - Enter Password',
@@ -73,7 +73,7 @@ function protected_node_menu_array() {
     'page arguments' => array('protected_node_enterpassword'),
     'access callback' => 'protected_node_access_callback',
     'type' => MENU_CALLBACK,
-    'file' => 'protected_node.redirect.inc'
+    'file' => 'protected_node.redirect.inc',
   );
   $items['protected-nodes'] = array(
     'title' => 'Protected page - Enter Password',
@@ -82,7 +82,7 @@ function protected_node_menu_array() {
     'page arguments' => array('protected_node_enter_any_password'),
     'access arguments' => array('access protected content'),
     'type' => MENU_CALLBACK,
-    'file' => 'protected_node.fork.inc'
+    'file' => 'protected_node.fork.inc',
   );
 
   return $items;
@@ -106,27 +106,26 @@ function protected_node_node_form_alter(&$form) {
   // try to avoid pre-filled password forms
   $form['#attributes']['autocomplete'] = 'off';
 
-  $node_type = node_get_types('type', $form['type']['#value']);
+  $node_type = node_type_get_type($form['type']['#value']);
   $fieldset_mode = variable_get('protected_node_fieldset_' . $node_type->type, PROTECTED_NODE_FIELDSET_SMART);
   switch ($fieldset_mode) {
-  case PROTECTED_NODE_FIELDSET_OPEN:
-    $collapsed = FALSE;
-    break;
-
-  case PROTECTED_NODE_FIELDSET_CLOSE:
-    $collapsed = TRUE;
-    break;
-
-  default: //case PROTECTED_NODE_FIELDSET_SMART:
-    if ($protection == PROTECTED_NODE_PROTECTION_ALWAYS
-    || ($protection == PROTECTED_NODE_PROTECTION_PROTECTED && empty($form['nid']['#value']))) {
+    case PROTECTED_NODE_FIELDSET_OPEN:
       $collapsed = FALSE;
-    }
-    else {
-      $collapsed = empty($form['#node']->protected_node_is_protected);
-    }
-    break;
+      break;
+
+    case PROTECTED_NODE_FIELDSET_CLOSE:
+      $collapsed = TRUE;
+      break;
 
+    default: //case PROTECTED_NODE_FIELDSET_SMART:
+      if ($protection == PROTECTED_NODE_PROTECTION_ALWAYS
+      || ($protection == PROTECTED_NODE_PROTECTION_PROTECTED && empty($form['nid']['#value']))) {
+        $collapsed = FALSE;
+      }
+      else {
+        $collapsed = empty($form['#node']->protected_node_is_protected);
+      }
+      break;
   }
   $form['protected_node'] = array(
     '#type' => 'fieldset',
@@ -179,20 +178,16 @@ function protected_node_node_form_alter(&$form) {
 
   // define a password field unless only the global password should be used
   switch (variable_get('protected_node_use_global_password', PROTECTED_NODE_PER_NODE_PASSWORD)) {
-  case PROTECTED_NODE_PER_NODE_PASSWORD:
-  case PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD:
-    $form['protected_node']['protected_node_passwd'] = array(
-      '#type' => 'password_confirm',
-      '#description' => t('Enter the @node password here. Remember that changing the password prevents all the users who knew the old password to continue to access the page.', array('@node' => $node_type->name)),
-      '#size' => 20,
-      '#after_build' => array('protected_node_autocomplete_off'),
-    );
+    case PROTECTED_NODE_PER_NODE_PASSWORD:
+    case PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD:
+      $form['protected_node']['protected_node_passwd'] = array(
+        '#type' => 'password_confirm',
+        '#description' => t('Enter the @node password here. Remember that changing the password prevents all the users who knew the old password to continue to access the page.', array('@node' => $node_type->name)),
+        '#size' => 20,
+        '#after_build' => array('protected_node_autocomplete_off'),
+      );
 
-    if (variable_get('protected_node_show_password_strength', TRUE)) {
-      // yeah... we're calling a Core "private" function...
-      _user_password_dynamic_validation();
-    }
-    break;
+      break;
 
   }
 
@@ -243,14 +238,10 @@ function protected_node_admin_settings() {
     '#collapsible' => TRUE,
   );
 
-  $sql = "SELECT COUNT(n.nid) FROM {node} n LEFT JOIN {protected_nodes} pn ON pn.nid = n.nid WHERE pn.protected_node_is_protected = 0 OR pn.protected_node_is_protected IS NULL";
-  $unprotected_count = db_result(db_query($sql));
-  $sql = "SELECT COUNT(nid) FROM {protected_nodes} WHERE protected_node_is_protected = 1";
-  $protected_count = db_result(db_query($sql));
-  $sql = "SELECT COUNT(nid) FROM {protected_nodes} WHERE protected_node_is_protected = 1 AND protected_node_show_title = 1";
-  $title_count = db_result(db_query($sql));
-  $sql = "SELECT COUNT(nid) FROM {protected_nodes} WHERE protected_node_is_protected = 1 AND protected_node_passwd = ''";
-  $global_count = db_result(db_query($sql));
+  $unprotected_count = db_query("SELECT COUNT(n.nid) FROM {node} n LEFT JOIN {protected_nodes} pn ON pn.nid = n.nid WHERE pn.protected_node_is_protected = :protected_node_is_protected OR pn.protected_node_is_protected IS NULL", array(':protected_node_is_protected' => 0))->fetchField();
+  $protected_count = db_query("SELECT COUNT(nid) FROM {protected_nodes} WHERE protected_node_is_protected = :protected_node_is_protected", array(':protected_node_is_protected' => 1))->fetchField();
+  $title_count = db_query("SELECT COUNT(nid) FROM {protected_nodes} WHERE protected_node_is_protected = :protected_node_is_protected AND protected_node_show_title = :protected_node_show_title", array(':protected_node_is_protected' => 1, ':protected_node_show_title' => 1))->fetchField();
+  $global_count = db_query("SELECT COUNT(nid) FROM {protected_nodes} WHERE protected_node_is_protected = :protected_node_is_protected AND protected_node_passwd = :protected_node_passwd", array(':protected_node_is_protected' => 1, ':protected_node_passwd' => ''))->fetchField();
 
   // any nodes?
   if ($protected_count + $unprotected_count > 0) {
@@ -284,9 +275,9 @@ function protected_node_admin_settings() {
     '#title' => t('Global password handling'),
     '#default_value' => variable_get('protected_node_use_global_password', PROTECTED_NODE_PER_NODE_PASSWORD),
     '#options' => array(
-      PROTECTED_NODE_PER_NODE_PASSWORD            => 'Per node password',
+      PROTECTED_NODE_PER_NODE_PASSWORD => 'Per node password',
       PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD => 'Per node password or Global password',
-      PROTECTED_NODE_GLOBAL_PASSWORD              => 'Global password only',
+      PROTECTED_NODE_GLOBAL_PASSWORD => 'Global password only',
     ),
     '#description' => t('When checked, the global password is used if the user doesn\'t enter a password when creating/editing nodes.')
                     . t('<strong>WARNING:</strong> removing the global password when many pages were not otherwise assigned a password will make those nodes unaccessible except for UID=1 and the author of the node.'),
@@ -299,7 +290,7 @@ function protected_node_admin_settings() {
     '#description' => t('The default password for all nodes. This password is necessary if you select the previous checkbox.'),
   );
   // yeah... we're calling a Core "private" function...
-  _user_password_dynamic_validation();
+  //_user_password_dynamic_validation();
 
   $form['protected_node_security']['protected_node_show_password_strength'] = array(
     '#type' => 'checkbox',
@@ -409,6 +400,7 @@ function protected_node_admin_settings() {
   );
 
   if (module_exists('token')) {
+    // TODO Please change this theme call to use an associative array for the $variables parameter.
     $form['protected_node_form']['protected_node_tokens'] = array(
       '#value' => theme('token_tree', array('global', 'node', 'user')),
       '#description' => t('WARNING: the user tokens should only be used if anonymous users cannot access protected nodes; otherwise the result may not be what you\'d expect.'),
@@ -528,14 +520,14 @@ function _protected_node_admin_settings_validate($form, &$form_state) {
   // make sure that a password is included if a global password is required
   // and none was ever submitted before
   switch ($form_state['values']['protected_node_use_global_password']) {
-  case PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD:
-  case PROTECTED_NODE_GLOBAL_PASSWORD:
-    if (!$form_state['values']['protected_node_global_password_field']
-     && !variable_get('protected_node_global_password', '')) {
-      form_error($form['protected_node_security']['protected_node_global_password_field'],
-                 t('A global password is required to make use of the global password functionality.'));
-    }
-    break;
+    case PROTECTED_NODE_PER_NODE_AND_GLOBAL_PASSWORD:
+    case PROTECTED_NODE_GLOBAL_PASSWORD:
+      if (!$form_state['values']['protected_node_global_password_field']
+       && !variable_get('protected_node_global_password', '')) {
+        form_error($form['protected_node_security']['protected_node_global_password_field'],
+                   t('A global password is required to make use of the global password functionality.'));
+      }
+      break;
 
   }
 
@@ -584,7 +576,7 @@ function _protected_node_admin_settings_submit($form, &$form_state) {
  * before then is then considered out of date and will be ignored.
  */
 function protected_node_action_clear_sessions($form, &$form_state) {
-  variable_set('protected_node_session_timelimit', time());
+  variable_set('protected_node_session_timelimit', REQUEST_TIME);
   drupal_set_message('All the Protected Node sessions were cleared.');
 }
 
@@ -597,9 +589,12 @@ function protected_node_action_clear_sessions($form, &$form_state) {
 function protected_node_action_reset_passwords($form, &$form_state) {
   $passwd = $form_state['values']['protected_node_reset_passwords_password'];
   if ($passwd) {
-    $sql = "UPDATE {protected_nodes} SET protected_node_passwd = '%s'";
-    db_query($sql, sha1($passwd));
-    variable_set('protected_node_session_timelimit', time());
+    db_update('protected_nodes')
+      ->fields(array(
+        'protected_node_passwd' => sha1($passwd),
+      ))
+      ->execute();
+    variable_set('protected_node_session_timelimit', REQUEST_TIME);
     drupal_set_message('All protected nodes are now publicly visible unless protected by another module.');
   }
   else {
@@ -615,8 +610,12 @@ function protected_node_action_reset_passwords($form, &$form_state) {
  * of reseting the password to use the global password on all nodes.
  */
 function protected_node_action_remove_passwords($form, &$form_state) {
-  $sql = "UPDATE {protected_nodes} SET protected_node_passwd = '' WHERE protected_node_passwd <> ''";
-  db_query($sql);
+  db_update('protected_nodes')
+    ->fields(array(
+      'protected_node_passwd' =>  '',
+    ))
+    ->condition('protected_node_passwd', '', '<>')
+    ->execute();
 }
 
 /**
@@ -625,8 +624,12 @@ function protected_node_action_remove_passwords($form, &$form_state) {
  * This function sets all the protected_node_is_protected to 0.
  */
 function protected_node_action_unprotected_all($form, &$form_state) {
-  $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = 0 WHERE protected_node_is_protected = 1";
-  db_query($sql);
+  db_update('protected_nodes')
+    ->fields(array(
+      'protected_node_is_protected' =>  0,
+    ))
+    ->condition('protected_node_is_protected', 1)
+    ->execute();
 }
 
 /**
@@ -637,8 +640,12 @@ function protected_node_action_unprotected_all($form, &$form_state) {
  */
 function protected_node_action_protect_all_nodes($form, &$form_state) {
   // first protect all nodes that already are in our table
-  $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = 1 WHERE protected_node_is_protected = 0";
-  db_query($sql);
+  db_update('protected_nodes')
+    ->fields(array(
+      'protected_node_is_protected' =>  1,
+    ))
+    ->condition('protected_node_is_protected', 0)
+    ->execute();
 
   // then update the table with ALL the existing nodes and as we're at it
   // we mark them as protected
@@ -646,6 +653,7 @@ function protected_node_action_protect_all_nodes($form, &$form_state) {
        . " (SELECT n.nid, %d AS protected_node_show_title, 1 AS protected_node_is_protected, '' AS protected_node_passwd"
        . " FROM {node} n LEFT JOIN {protected_nodes} pn ON n.nid = pn.nid"
        . " WHERE pn.nid IS NULL)";
+  // TODO Please convert this statement to the D7 database API syntax.
   db_query($sql, $form_state['values']['protected_node_show_node_titles']);
 }
 
@@ -656,8 +664,13 @@ function protected_node_action_protect_all_nodes($form, &$form_state) {
  * restores those nodes protection (i.e. sets the is_protected to 1).
  */
 function protected_node_action_protect_nodes_with_password($form, &$form_state) {
-  $sql = "UPDATE {protected_nodes} SET protected_node_is_protected = 1 WHERE protected_node_is_protected = 0 AND protected_node_passwd <> ''";
-  db_query($sql);
+  db_update('protected_nodes')
+    ->fields(array(
+      'protected_node_is_protected' =>  1,
+    ))
+    ->condition('protected_node_is_protected', 0)
+    ->condition('protected_node_passwd', '', '<>')
+    ->execute();
   drupal_set_message('All nodes with an existing password (excluding the global password) are now protected.');
 }
 
@@ -681,10 +694,10 @@ function protected_node_node_type_form_alter(&$form) {
   );
 
   $options = array(
-    PROTECTED_NODE_PROTECTION_NEVER       => t('Never protected'),
+    PROTECTED_NODE_PROTECTION_NEVER => t('Never protected'),
     PROTECTED_NODE_PROTECTION_PROTECTABLE => t('Protectable (default is unprotected)'),
-    PROTECTED_NODE_PROTECTION_PROTECTED   => t('Protectable (default is protected)'),
-    PROTECTED_NODE_PROTECTION_ALWAYS      => t('Always protected'),
+    PROTECTED_NODE_PROTECTION_PROTECTED => t('Protectable (default is protected)'),
+    PROTECTED_NODE_PROTECTION_ALWAYS => t('Always protected'),
   );
   $form['protected_node']['protected_node_protection'] = array(
     '#type' => 'radios',
@@ -704,10 +717,10 @@ function protected_node_node_type_form_alter(&$form) {
     //'#default_value' => variable_get('protected_node_node_password_' . $form['#node_type']->type, ''),
   );
   // yeah... we're calling a Core "private" function...
-  _user_password_dynamic_validation();
+  //_user_password_dynamic_validation();
 
   $options = array(
-    PROTECTED_NODE_FIELDSET_OPEN  => t('Always open'),
+    PROTECTED_NODE_FIELDSET_OPEN => t('Always open'),
     PROTECTED_NODE_FIELDSET_SMART => t('Smart mode (Open when protected)'),
     PROTECTED_NODE_FIELDSET_CLOSE => t('Always closed'),
   );
@@ -765,5 +778,3 @@ function _protected_node_node_type_submit($form, &$form_state) {
     variable_del('protected_node_node_type_password_field_' . $old_node_type);
   }
 }
-
-// vim: ts=2 sw=2 et syntax=php
