? modules/nmoderation/nmoderation.install
Index: modules/nmoderation/nmoderation.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/nmoderation/nmoderation.module,v
retrieving revision 1.22
diff -u -r1.22 nmoderation.module
--- modules/nmoderation/nmoderation.module	25 Apr 2005 12:25:25 -0000	1.22
+++ modules/nmoderation/nmoderation.module	7 Apr 2006 04:18:12 -0000
@@ -1,11 +1,15 @@
 <?php
-// $Id: nmoderation.module,v 1.22 2005/04/25 12:25:25 weitzman Exp $
+// $Id: nmoderation.module,v 1.11 2006/03/27 22:13:29 eaton Exp $
 
 /**
  * @file
  * Enables users to vote nodes onto the home page.
 */
 
+define('NMODERATION_VOTE_TYPE', 'option');
+define('NMODERATION_CACHE_TYPE', 'points');
+define('NMODERATION_TAG', 'moderation');
+
 /**
  * Implementation of hook_help().
  */
@@ -33,8 +37,6 @@
       'callback' => 'nmoderation_vote_settings', 'access' => $access,'type' => MENU_LOCAL_TASK);
 
     $access = user_access('moderate nodes');
-    $items[] = array('path' => 'nmoderation/add', 'title' => t('add node moderation vote'),
-      'callback' => 'nmoderation_uservote_add', 'access' => $access, 'type' => MENU_CALLBACK);
     $items[] = array('path' => 'nmoderation/edit', 'title' => t('edit node moderation vote'),
       'callback' => 'nmoderation_uservote_edit', 'access' => $access, 'type' => MENU_CALLBACK);
     $items[] = array('path' => 'nmoderation/delete', 'title' => t('delete node moderation vote'),
@@ -49,39 +51,67 @@
       'callback' => 'nmoderation_list_all', 'weight' => 5, 'access' => user_access('administer node moderation votes'));
   }
   else {
-    $items[] = array('path' => 'node/'. arg(1). '/nmoderation', 'title' => t('manage votes'),
-      'type' => MENU_LOCAL_TASK, 'callback' => 'nmoderation_list_node', 'weight' => 5, 'access' => user_access('administer node moderation votes'), 'callback arguments' => array(arg(1)));
-    drupal_set_html_head(implode("\n", nmoderation_set_head()));
+  	if (arg(0) == 'node' && is_numeric(arg(1))) {
+  	  $access = user_access('administer node moderation votes') || user_access('view node moderation votes');
+      $items[] = array('path' => 'node/'. arg(1). '/nmoderation', 'title' => t('votes'),
+        'type' => MENU_LOCAL_TASK, 'callback' => 'nmoderation_list_node', 'weight' => 5, 'access' => $access, 'callback arguments' => array(arg(1)));
+    }
+    theme('add_style', drupal_get_path('module','nmoderation') . '/nmoderation.css');
   }
   return $items;
 }
 
-function nmoderation_set_head() {
-  global $base_url;
-  if (user_access('access content')) {
-    $output[] = "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"$base_url/modules/nmoderation/nmoderation.css\" />";
-    return $output;
-  }
-}
-
 /**
  * Implementation of hook_perm().
  */
 function nmoderation_perm() {
-  return array('nmoderate nodes', 'administer node moderation votes', 'administer node moderation configuration');
+  return array('nmoderate nodes', 'view node moderation votes', 'administer node moderation votes', 'administer node moderation configuration');
 }
 
-function nmoderation_matrix_settings() {
-  if ($edit = $_POST['edit']) {
-    db_query('DELETE FROM {nmoderation_roles} ');
-    foreach ($edit as $role_id => $votes) {
-      foreach ($votes as $mid => $value) {
-        $sql = "('$mid', '$role_id', '". ($value ? $value : 0) ."')";
-        db_query('INSERT INTO {nmoderation_roles} (mid, rid, value) VALUES '. $sql);
-      }
-    }
-    drupal_set_message(t('the vote values have been saved.'));
+
+/**
+ * Validates module dependencies for the module.
+ *
+ * @param $form The form array passed from hook_form_alter.
+ *
+ * Set the $module variable to a string which is the name of the module, minus
+ * the .module extension.  Set $dependencies to an array of module names which
+ * the module is dependent on--each element is a string which is the module name
+ * minus the .module extension.  Note that this will not check for any dependencies
+ * for the modules this module depends on--only those that are explicitly listed in
+ * the $dependencies array.
+ */
+function nmoderation_system_module_validate(&$form) {
+ $module = 'nmoderation';
+ $dependencies = array('votingapi');
+ foreach ($dependencies as $dependency) {
+     if (!in_array($dependency, $form['status']['#default_value'])) {
+       $missing_dependency = TRUE;
+       $missing_dependency_list[] = $dependency;
+     }
+ }
+ if (in_array($module, $form['status']['#default_value']) && isset($missing_dependency)) {
+   db_query("UPDATE {system} SET status = 0 WHERE type = 'module' AND name = '%s'", $module);
+   $key = array_search($module, $form['status']['#default_value']);
+   unset($form['status']['#default_value'][$key]);
+   drupal_set_message(t('The module %module was deactivated--it requires the following disabled/non-existant modules to function properly: %dependencies', array('%module' => $module, '%dependencies' => implode(', ', $missing_dependency_list))), 'error');
+ }
+}
+
+/* this is a check for module dependencies.  the only way we
+   can ensure this check happening when the module is initially
+   enabled is to insert the check for when the form is initially
+   built, which will also be caught when the admin/module page is
+   reloaded upon submission.  this means we never want to call this
+   function when the form has been submitted, so make sure there's
+   no $_POST. */
+function nmoderation_form_alter($form_id, $form) {
+  if ($form_id == 'system_modules' && !$_POST) {
+    nmoderation_system_module_validate($form);
   }
+}
+
+function nmoderation_matrix_settings() {
   $output .= '<h3>Node Moderation vote/value matrix</h3>';
   $result = db_query("SELECT r.rid, r.name FROM {role} r, {permission} p WHERE r.rid = p.rid AND p.perm LIKE '%moderate nodes%'");
   $role_names = array();
@@ -94,116 +124,237 @@
     $mod_roles[$role->rid][$role->mid] = $role->value;
   }
 
-  $header = array_merge(array(t('votes')), array_values($role_names));
-
   $result = db_query('SELECT mid, vote FROM {nmoderation_votes} ORDER BY weight');
   while ($vote = db_fetch_object($result)) {
-    $row = array($vote->vote);
+    $form['votes'][$vote->mid]['vote'] = array(
+      '#type' => 'markup',
+      '#value' => $vote->vote,
+    );
     foreach (array_keys($role_names) as $rid) {
-      $row[] = array('data' => form_textfield(NULL, "$rid][$vote->mid", $mod_roles[$rid][$vote->mid], 4, 3));
+      $form['votes'][$vote->mid][$rid] = array(
+        '#type' => 'textfield',
+        '#default_value' => $mod_roles[$rid][$vote->mid],
+        '#size' => 3,
+        '#maxlength' => 4,
+      );
+    }
+  }
+
+  $form['#tree'] = TRUE; // make sure we preserve all hierarchial values.
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Submit votes')
+  );
+
+  // Stick a few extra bits into the $form array for the theming function to use
+  $form['role_names'] = array(
+    '#type' => 'value',
+    '#value' => $role_names,
+  );
+
+  $output .= drupal_get_form('nmoderation_matrix_form', $form);
+  return $output;
+}
+
+function nmoderation_matrix_form_submit($form_id, $form_values) {
+  // db_query('DELETE FROM {nmoderation_roles} ');
+  foreach (element_children($form_values['votes']) as $mid) {
+    foreach (element_children($form_values['votes'][$mid]) as $rid) {
+      $value = $form_values['votes'][$mid][$rid];
+      $sql = "('$mid', '$rid', '". ($value ? $value : 0) ."')";
+      db_query('INSERT INTO {nmoderation_roles} (mid, rid, value) VALUES '. $sql);
+    }
+  }
+
+  drupal_set_message(t('the vote values have been saved.'));
+}
+
+function theme_nmoderation_matrix_form(&$form) {
+  $role_names = $form['role_names']['#value'];
+  $header = array_merge(array(t('votes')), array_values($role_names));
+
+  foreach (element_children($form['votes']) as $mid) {
+    $row = array();
+    foreach (element_children($form['votes'][$mid]) as $rid) {
+      $row[] = form_render($form['votes'][$mid][$rid]);
     }
     $rows[] = $row;
   }
+
   if (!$rows) {
     $rows[] = array(array('data' => t('No votes have been defined.'), 'colspan' => '5'));
+    unset($form['submit']);
   }
 
-  $output .= theme('table', $header, $rows);
-  if ($rows) { $output .= '<br />'. form_submit(t('Submit votes')); }
-
-  return form($output);
+  $output = theme('table', $header, $rows);
+  $output .= form_render($form);
+  return $output;
 }
 
 /**
  * Menu callback; allows admin to set default scores for different roles.
  */
 function nmoderation_role_settings() {
+  $output .= '<h3>Initial node scores</h3>';
+  
+  $start_values = variable_get('nmoderation_roles', array());
+  
+  $result = db_query("SELECT r.rid, r.name FROM {role} r, {permission} p WHERE r.rid = p.rid AND p.perm LIKE '%moderate nodes%' ORDER BY r.rid");
+  while ($role = db_fetch_object($result)) {
+    $form['role'][$role->rid] = array(
+      '#title' => $role->name,
+      '#type' => 'textfield',
+      '#default_value' => $start_values[$role->rid],
+      '#size' => 3,
+      '#maxlength' => 4,
+    );
+  }
 
-  $edit = $_POST['edit'];
+  $form['#tree'] = TRUE; // make sure we preserve all hierarchial values.
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save scores')
+  );
 
-  $output .= '<h3>Initial node scores</h3>';
+  $output .= drupal_get_form('nmoderation_role_form', $form);
+  return $output;
+}
 
-  if ($edit) {
-    variable_set('nmoderation_roles', $edit);
-    drupal_set_message(t('the node moderation scores have been saved.'));
-  }
+function nmoderation_role_form_validate($form_id, $form_values) {
+  // make sure everything is numeric/int
+}
 
-  $start_values = variable_get('nmoderation_roles', array());
-  $result = db_query("SELECT r.rid, r.name FROM {role} r, {permission} p WHERE r.rid = p.rid AND p.perm LIKE '%moderate nodes%'");
+function nmoderation_role_form_submit($form_id, $form_values) {
+    $new_values = array();
+    foreach (element_children($form_values['role']) as $rid) {
+      $new_values[$rid] = $form_values['role'][$rid]['#value'];
+    }
+    variable_set('nmoderation_roles', $new_values);
+    drupal_set_message(t('the node moderation scores have been saved.'));
+}
 
+function theme_nmoderation_role_form(&$form) {
   $header = array(t('user role'), t('initial score'));
 
-  while ($role = db_fetch_object($result)) {
-    $rows[] = array($role->name, array('data' => form_textfield(NULL, $role->rid, $start_values[$role->rid], 4, 3), 'align' => 'center'));
+  $rows = array();
+  foreach (element_children($form['role']) as $rid) {
+    $row = array();
+    $row[] = $form['role'][$rid]['#title'];
+    unset($form['role'][$rid]['#title']);
+    $row[] = form_render($form['role'][$rid]);
+    $rows[] = $row;
   }
 
-  $output .= theme('table', $header, $rows);
-  $output .= '<br />'. form_submit(t('Save scores'));
-
-  return form($output);
+  $output = theme('table', $header, $rows);
+  $output .= form_render($form);
+  return $output;
 }
 
 /**
  * Menu callback; displays page for assigning names to vote values.
  */
-function nmoderation_vote_settings($mid = 0) {
-  $op   = $_POST['op'];
-  $edit = $_POST['edit'];
-
-  if ($op == t('Save vote')) {
-    db_query("UPDATE {nmoderation_votes} SET vote = '%s', weight = %d WHERE mid = %d", $edit['vote'], $edit['weight'], $mid);
-    $mid = 0; // zero it out so we return to the overview.
-    drupal_set_message(t('the vote has been saved.'));
-  }
-  else if ($op == t('Delete vote')) {
-    db_query('DELETE FROM {nmoderation_votes} WHERE mid = %d', $mid);
-    db_query('DELETE FROM {nmoderation_roles} WHERE mid = %d', $mid);
-    $mid = 0; // zero it out so we return to the overview.
-    drupal_set_message(t('the vote has been deleted.'));
-  }
-  else if ($op == t('Add new vote')) {
-    db_query("INSERT INTO {nmoderation_votes} (vote, weight) VALUES ('%s', %d)", $edit['vote'], $edit['weight']);
-    $mid = 0; // zero it out so we return to the overview.
-    drupal_set_message(t('the vote has been added.'));
-  }
-
+function nmoderation_vote_settings() {
   $output .= '<h3>'. t('Node moderation votes overview') .'</h3>';
 
   // load up and show any vote types previously defined.
-  $header = array(t('votes'), t('weight'), t('operations'));
   $result = db_query('SELECT mid, vote, weight FROM {nmoderation_votes} ORDER BY weight');
   while ($vote = db_fetch_object($result)) {
-    $rows[] = array($vote->vote, array('data' => $vote->weight), array('data' => l(t('edit'), "admin/nmoderation/votes/$vote->mid")));
-  }
-  if (!$rows) {
-    $rows[] = array(array('data' => t('No vote types have been defined.'), 'colspan' => '3'));
-  }
-  $output .= theme('table', $header, $rows);
+    $form['old'][$vote->mid]['vote'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $vote->vote,
+      '#size' => 32,
+      '#maxlength' => 64,
+    );
+    
+    $form['old'][$vote->mid]['weight'] = array(
+      '#type' => 'textfield',
+      '#default_value' => $vote->weight,
+      '#size' => 32,
+      '#maxlength' => 64,
+    );
+
+    $form['old'][$vote->mid]['delete'] = array(
+      '#type' => 'checkbox',
+      '#default_value' => 0,
+      '#return_value' => 1,
+    );
+  }
+  
+  // Add a set of fields for new votes.
+  $form['new']['vote'] = array(
+   '#type' => 'textfield',
+   '#default_value' => $vote->vote,
+   '#size' => 32,
+   '#maxlength' => 64,
+  );
+    
+  $form['new']['weight'] = array(
+    '#type' => 'textfield',
+    '#default_value' => $vote->weight,
+    '#size' => 32,
+    '#maxlength' => 64,
+  );
 
-  if ($mid) { // if we're not saving, deleting, or adding, we must be editing, so prefill the form fields.
-    $vote = db_fetch_object(db_query('SELECT vote, weight FROM {nmoderation_votes} WHERE mid = %d', $mid));
-  }
+  $form['#tree'] = TRUE; // make sure we preserve all hierarchial values.
+  $form[] = array(
+    '#type' => 'submit',
+    '#value' => t('Save changes'),
+  );
 
-  $output .= '<br /><h3>'. (isset($mid) ? 'Edit' : 'Add new') .' node moderation option</h3>';
-  $form .= form_textfield(t('Vote'), 'vote', $vote->vote, 32, 64, t('The name of this vote.  Example: "off topic", "excellent", "sucky".'));
-  $form .= form_textfield(t('Weight'), 'weight', $vote->weight, 32, 64, t('Used to order votes in the voting box; heavier sink.'));
-  if ($mid) {
-    $form .= form_submit(t('Save vote'));
-    $form .= form_submit(t('Delete vote'));
-  }
-  else {
-    $form .= form_submit(t('Add new vote'));
-  }
+  $output = drupal_get_form('nmoderation_vote_form', $form);
+  return $output;
+}
 
-  return $output . form($form);
+function nmoderation_vote_form_validate($form_id, $form_values) {
+  // make sure $weight is an int and $vote is markup clean, no injections.
 }
 
-function nmoderation_get_vote($uid, $gid, $realm = 'node_nid') {
-  $sql = "SELECT uvid, mid FROM {nmoderation_uservotes} WHERE uid = $uid AND gid = $gid AND realm = '$realm'";
-  return db_fetch_object(db_query($sql));
+function nmoderation_vote_form_submit($form_id, $form_values) {
+  // loop through the fields for old votes, update or delete as necessary.
+  foreach (element_children($form_values['old']) as $mid) {
+    if ($form_values['old'][$mid]['delete'] == 1) {
+       db_query('DELETE FROM {nmoderation_votes} WHERE mid = %d', $mid);
+      db_query('DELETE FROM {nmoderation_roles} WHERE mid = %d', $mid);
+    }
+    else {
+      db_query("UPDATE {nmoderation_votes} SET vote = '%s', weight = %d WHERE mid = %d", $form_values['old'][$mid]['vote'], $form_values['old'][$mid]['weight'], $mid);
+    }
+  }  
+  
+  // if a new vote has been added, insert it.
+  if ($form_values['new']['vote'] != '') {
+    db_query("INSERT INTO {nmoderation_votes} (vote, weight) VALUES ('%s', %d)", $form_values['new']['vote'], $form_values['new']['weight']);
+  }
+
+  drupal_set_message(t('the changes have been saved.'));
+  drupal_goto('admin/nmoderation/votes'); // do this because we want the form completely rebuilt.
+}
+
+function theme_nmoderation_vote_form(&$form) {
+  $header = array(t('votes'), t('weight'), t('delete'));
+  
+  // render the existing-vote fields.
+  foreach (element_children($form['old']) as $mid) {
+    $row = array();
+    $row[] = form_render($form['old'][$mid]['vote']);
+    $row[] = form_render($form['old'][$mid]['weight']);
+    $row[] = form_render($form['old'][$mid]['delete']);
+    $rows[] = $row;
+  }
+
+  // render the add-a-vote fields.
+  $row = array();
+  $row[] = form_render($form['new']['vote']);
+  $row[] = form_render($form['new']['weight']);
+  $row[] = '';
+  $rows[] = $row;
+  
+  $output .= theme('table', $header, $rows);
+  $output .= form_render($form);
+  return $output;
 }
 
-function nmoderation_form($mid) {
+function nmoderation_get_moderation_form($content_type, $content_id, $vote, $title= NULL) {
   global $user;
   static $votes;
 
@@ -211,28 +362,87 @@
     if (!isset($votes) && $user->roles) {
       $result = db_query('SELECT mid, vote FROM {nmoderation_votes} ORDER BY weight ASC');
       $votes = array();
-      while ($vote = db_fetch_object($result)) {
-        $votes[$vote->mid] = $vote->vote;
+      while ($dbvote = db_fetch_object($result)) {
+        $votes[$dbvote->mid] = $dbvote->vote;
       }
     }
+    
     if ($votes) {
-      $output = form_select(t('Moderate Post'), 'mid', $mid, $votes, t('Your vote contributes to whether or not this post appears on the home page.'));
-      return $output;
+      $form['value'] = array(
+        '#type' => 'select',
+        '#title' => t('Moderate Post'),
+        '#default_value' => $vote->value,
+        '#options' => $votes,
+        '#description' => t('Your vote contributes to whether or not this post appears on the home page.'),
+      );
+      
+      $form['content_type'] = array(
+        '#type' => 'hidden',
+        '#value' => $content_type,
+      );
+
+      $form['content_id'] = array(
+        '#type' => 'hidden',
+        '#value' => $content_id,
+      );
+
+      if ($vote) {
+        $form['vote_id'] = array(
+          '#type' => 'hidden',
+          '#value' => $vote->vote_id,
+        );
+      }
+
+      if ($title) {
+        $form['submit'] = array(
+          '#type' => 'submit',
+          '#value' => $title,
+        );
+      }
+      return $form;
     }
   }
 }
 
-// TODO disallow adds on unwanted node types, out of interval, self
-function nmoderation_uservote_add($nid) {
+function nmoderation_moderation_form_submit($form_id, $form_values) {
   global $user;
-  $edit = $_POST['edit'];
-  $mid = $edit['mid'];
-  $value = nmoderation_get_value($mid);
-  $sql = "INSERT INTO {nmoderation_uservotes} (uid, mid, gid, value, realm) VALUES ($user->uid, $mid, $nid, $value, 'node_nid')";
-  db_query($sql);
-  nmoderation_set_promote($nid);
-  drupal_set_message(t('Vote added.'));
-  drupal_goto($edit['destination']);
+  $content_type = $form_values['content_type'];
+  $content_id = $form_values['content_id'];
+  $value = $form_values['value'];
+  $vote_id = $form_values['vote_id'];
+
+  if ($vote_id) {
+    // There's already a vote, we're editing.
+    $vote = db_fetch_object(db_query("SELECT * FROM {votingapi_vote} WHERE vote_id=%d", $vote_id));
+    if ($vote->uid != $user->uid) {
+      $account = user_load(array('uid' => $vote->uid));
+    }
+    else {
+      $account = $user;
+    }
+  }
+
+  // Use the existing types, or the defaults if there was no original vote.
+  $vote->tag = $vote->tag ? $vote->tag : NMODERATION_TAG;
+  $vote->value_type = $vote->value_type ? $vote->value_type : NMODERATION_VOTE_TYPE;
+  $vote->value = $value;
+
+  votingapi_set_vote($content_type, $content_id, $vote, $account);
+  nmoderation_set_promote($content_id, $content_type);
+
+  if ($vote_id) {
+    drupal_set_message(t('Vote edited.'));
+  }
+  else {
+    drupal_set_message(t('Vote added.'));
+  }
+}
+
+function theme_nmoderation_moderation_form($form) {
+  // We aren't actually going to do anything fancy, but it's here
+  // in case folks want to override it for a given theme.
+  $output = form_render($form);
+  return $output;
 }
 
 // if you pass in an $account object, it must have $uid and $roles elements
@@ -246,87 +456,90 @@
   return db_result(db_query_range($sql, $mid, $roles, 0, 1)); // see comment_moderate() for analogous function
 }
 
-function nmoderation_uservote_edit($uvid) {
+function nmoderation_uservote_edit($vote_id) {
   global $user;
-  $edit = $_POST['edit'];
-  $sql = 'SELECT uid, gid, mid FROM {nmoderation_uservotes} WHERE uvid = %d';
-  $vote = db_fetch_object(db_query($sql, $uvid));
+  $sql = 'SELECT vote_id, uid, content_id, value FROM {votingapi_vote} WHERE vote_id = %d';
+  $vote = db_fetch_object(db_query($sql, $vote_id));
 
   // may only edit own vote if you are not an admin
   if ($user->uid == $vote->uid || user_access('administer node moderation votes')) {
+    $node = node_load($vote->content_id);
+    $form = nmoderation_get_moderation_form('node', $node->nid, $vote, t('Edit vote'));
+    
     if ($vote->uid != $user->uid) {
-      $account = user_load(array('uid' => $vote->uid));
-      $output = form_item(t('Voter'), format_name($account));
-    }
-    if ($_POST['op'] == t('Edit vote')) {
-      $value = nmoderation_get_value($edit['mid'], $account);
-      $sql = 'UPDATE {nmoderation_uservotes} SET mid = %d, value = %d WHERE uvid = %d';
-      db_query($sql, $edit['mid'], $value, $uvid);
-      nmoderation_set_promote($vote->gid);
-      drupal_set_message(t('Vote edited.'));
-      $dest = $edit['destination'] ? $edit['destination'] : 'nmoderation/voted';
-      drupal_goto($dest);
-    }
-    else {
-      $sql = "SELECT title FROM {node} WHERE nid = %d";
-      $title = db_result(db_query($sql, $vote->gid));
-      $output .= form_item(t('Title'), $title);
-      $frm = nmoderation_form($vote->mid);
-      $frm .= form_submit(t('Edit vote'));
-      $output .= form($frm, 'post', url("nmoderation/edit/$uvid"));
-      return $output;
-    }
+      $form['username'] = array(
+        '#type' => 'markup',
+        '#title' => t('Voter'),
+        '#value' => theme('username', $account),
+        '#weight' => -2,
+      );
+    }
+    
+    $form['title'] = array(
+      '#type' => 'markup',
+      '#title' => t('Title'),
+      '#value' => $node->title,
+      '#weight' => -1,
+    );
+
+    $output .= drupal_get_form('nmoderation_moderation_form', $form);
+    return $output;
   }
   else {
     drupal_access_denied();
   }
 }
 
-function nmoderation_uservote_delete($uvid) {
+function nmoderation_uservote_delete($vote_id) {
+  $form['vote_id'] = array('#type' => 'value', '#value' => $vote_id);
+  $output = confirm_form(
+    'nmoderation_delete_confirm',
+    $form,
+    t('Are you sure you want to delete this vote?'),
+    $_GET['destination'] ? $_GET['destination'] : 'nmoderation/voted',
+    t('This action cannot be undone.'),
+    t('Delete Vote'),
+    t('Cancel') 
+  );
+  return $output;
+}
+
+function nmoderation_delete_confirm_submit($form_id, $form_values) {
   global $user;
-  $edit = $_POST['edit'];
-  if ($_POST['op'] == t('Delete vote')) {
-    $sql = 'SELECT uid, gid FROM {nmoderation_uservotes} WHERE uvid = %d';
-    $vote = db_fetch_object(db_query($sql, $uvid));
-    // may only delete own vote if you are not an admin
+  if ($form_values['confirm']) {
+    $sql = 'SELECT * FROM {votingapi_vote} WHERE vote_id = %d';
+    $vote = db_fetch_object(db_query($sql, $vote_id));
+
     if ($user->uid == $vote->uid || user_access('administer node moderation votes')) {
-      $sql = "DELETE FROM {nmoderation_uservotes} WHERE uvid=%d";
-      db_query($sql, $uvid);
+      votingapi_delete_vote($vote);
+      nmoderation_set_promote($vote->content_id, $vote->content_type);
+      
       drupal_set_message(t('Vote deleted.'));
-      nmoderation_set_promote($vote->gid);
-      $dest = $edit['destination'] ? $edit['destination'] : 'nmoderation/voted';
-      drupal_goto($dest);
+      drupal_goto('nmoderation/voted');
     }
     else {
       drupal_access_denied();
     }
   }
-  else {
-    $frm = form_item(t('Confirmation'), t('Are you sure you want to delete this vote?'));
-    $frm .= form_button(t('Delete vote'));
-    return form($frm);
-  }
 }
 
 // will either promote or unpublish or do nothing, depending on the curent score for this node
-function nmoderation_set_promote($gid, $realm = 'node_nid') {
-  $sql = "SELECT SUM(value) AS score FROM {nmoderation_uservotes} WHERE gid = $gid AND realm = '$realm'";
-  $result = db_query($sql);
-  $row = db_fetch_object($result);
-  $node = node_load(array('nid' => $gid));
+function nmoderation_set_promote($content_id, $content_type = 'node') {
+  $result = votingapi_get_voting_result($content_type, $content_id, NMODERATION_CACHE_TYPE, NMODERATION_TAG, 'vote');
+  $node = node_load($content_id);
   // have to load terms in order that they don't get lost upon saving the node.
-  $node->taxonomy = array_keys(taxonomy_node_get_terms($gid));
-  if ($row->score < variable_get('nmoderation_threshold_unpublish', 4)) {
+
+  if ($result->value < variable_get('nmoderation_threshold_unpublish', 4)) {
     $node->status = 0;
     node_save($node);
   }
-  elseif ($row->score > variable_get('nmoderation_threshold_promote', 4)) {
+  elseif ($result->value > variable_get('nmoderation_threshold_promote', 4)) {
     $node->promote = 1;
     node_save($node);
   }
 }
 
-function nmoderation_list_unvoted($realm = 'node_nid') {
+function nmoderation_list_unvoted($content_type = 'node') {
   global $user;
 
   $header = array(
@@ -336,8 +549,8 @@
   );
   $cols = 2;
   $title = t('my unmoderated nodes');
-  $types = implode("','", variable_get('nmoderation_node_types', drupal_map_assoc(node_list())));
-  $sql = "SELECT n.nid, n.created, u.name, n.title, n.uid FROM {node} n INNER JOIN {users} u ON n.uid = u.uid LEFT JOIN {nmoderation_uservotes} nmuv ON n.nid = nmuv.gid AND nmuv.realm = '$realm' AND nmuv.uid = $user->uid WHERE n.type IN ('$types') AND n.status = 1 AND ISNULL(nmuv.uvid)";
+  $types = implode("','", variable_get('nmoderation_node_types', node_get_types()));
+  $sql = "SELECT n.nid, n.created, u.name, n.title, n.uid FROM {node} n INNER JOIN {users} u ON n.uid = u.uid LEFT JOIN {votingapi_vote} v ON n.nid = v.content_id AND v.content_type = '$content_type' AND v.uid = $user->uid WHERE n.type IN ('$types') AND n.status = 1 AND v.value_type = '".NMODERATION_VOTE_TYPE."' AND ISNULL(v.vote_id)";
   $min = time()-24*3600*variable_get('nmoderation_vote_interval', 7);
   $sql .= " AND n.created > $min";
   if (!user_access('administer node moderation votes')) {
@@ -346,7 +559,7 @@
   $sql .= tablesort_sql($header);
   $result = pager_query(db_rewrite_sql($sql), 50);
   while ($vote = db_fetch_object($result)) {
-    $rows[] = array(l($vote->title, "node/$vote->nid"), format_name($vote), format_date($vote->created, 'small'));
+    $rows[] = array(l($vote->title, "node/$vote->nid"), theme('username', $vote), format_date($vote->created, 'small'));
   }
   if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
     $rows[] = array(array('data' => $pager, 'colspan' => $cols));
@@ -357,7 +570,7 @@
 }
 
 // TODO disallow changing of votes on node types which are now unvotable?
-function nmoderation_list_voted($realm = 'node_nid') {
+function nmoderation_list_voted($content_type = 'node') {
   global $user;
   $header = array(
     array('data' => t('title'), 'field' => 'title'),
@@ -366,14 +579,15 @@
     array('data' => t('vote')),
     array('data' => t('operations'), 'colspan' => 2)
   );
-  $sql = "SELECT n.nid, u.name, n.title, n.changed, n.created, n.uid, v.vote, nmuv.uvid FROM {nmoderation_uservotes} nmuv INNER JOIN {nmoderation_votes} v ON nmuv.mid = v.mid INNER JOIN {node} n ON n.nid = nmuv.gid INNER JOIN {user}s u ON n.uid = u.uid WHERE n.status = 1 AND nmuv.uid = $user->uid AND nmuv.realm = '$realm'";
+
+  $sql = "SELECT n.nid, u.name, n.title, n.changed, n.created, n.uid, nv.vote, v.vote_id FROM {votingapi_vote} v INNER JOIN {nmoderation_votes} nv ON v.value = nv.mid INNER JOIN {node} n ON n.nid = v.content_id INNER JOIN {users} u ON n.uid = u.uid WHERE n.status = 1 AND v.uid = $user->uid AND v.content_type = '$content_type' AND v.value_type = '" . NMODERATION_VOTE_TYPE . "'";
   $sql .= tablesort_sql($header);
   $result = pager_query(db_rewrite_sql($sql), 50);
   while ($vote = db_fetch_object($result)) {
-    $row = array(l($vote->title, "node/$vote->nid"), format_name($vote), format_date($vote->created, 'small'), $vote->vote);
+    $row = array(l($vote->title, "node/$vote->nid"), theme('username', $vote), format_date($vote->created, 'small'), $vote->vote);
     if (nmoderation_is_votable($vote)) {
-      $row[] = l(t('edit'), "nmoderation/edit/$vote->uvid");
-      $row[] = l(t('delete'), "nmoderation/delete/$vote->uvid");
+      $row[] = l(t('edit'), "nmoderation/edit/$vote->vote_id");
+      $row[] = l(t('delete'), "nmoderation/delete/$vote->vote_id");
     }
     else {
       $row[] = array('data' => t('voting period expired'), 'colspan' => 2);
@@ -388,20 +602,28 @@
   return $output;
 }
 
-function nmoderation_list_all($realm = 'node_nid') {
+function nmoderation_list_all($content_type = 'node') {
   $header = array(
     array('data' => t('title'), 'field' => 'title'),
     array('data' => t('date'), 'field' => 'created', 'sort' => 'desc'),
     array('data' => t('voter'), 'field' => 'u.name'),
-    array('data' => t('vote'), 'field' => 'v.vote'),
-    array('data' => t('value'), 'field' => 'nmuv.value'),
+    array('data' => t('vote'), 'field' => 'nv.vote'),
+    array('data' => t('value')),
     array('data' => t('operations'), 'colspan' => 2)
   );
-  $sql = "SELECT v.vote, nmuv.value, nmuv.uvid, n.nid, n.created, n.title, nmuv.uid, u.name FROM {nmoderation_uservotes} nmuv INNER JOIN {nmoderation_votes} v ON nmuv.mid = v.mid INNER JOIN {node} n ON nmuv.gid = n.nid AND nmuv.realm = '$realm' INNER JOIN {users} u ON nmuv.uid = u.uid WHERE n.status = 1";
+  $sql = "SELECT nv.vote, v.value, v.vote_id, n.nid, n.created, n.title, v.uid, u.name FROM {votingapi_vote} v INNER JOIN {nmoderation_votes} nv ON v.value = nv.mid INNER JOIN {node} n ON v.content_id = n.nid AND v.content_type = '$content_type' AND v.value_type = '". NMODERATION_VOTE_TYPE ."' INNER JOIN {users} u ON v.uid = u.uid WHERE n.status = 1";
   $sql .= tablesort_sql($header);
   $result = pager_query(db_rewrite_sql($sql), 50);
   while ($vote = db_fetch_object($result)) {
-    $rows[] = array(l($vote->title, "node/$vote->nid"), format_date($vote->created, 'small'), format_name($vote), $vote->vote, $vote->value, l(t('edit'), "nmoderation/edit/$vote->uvid"), l(t('delete'), "nmoderation/delete/$vote->uvid"));
+    $rows[] = array(
+      l($vote->title, "node/$vote->nid"),
+      format_date($vote->created, 'small'),
+      theme('username', $vote),
+      $vote->vote,
+      nmoderation_get_value($vote->value, user_load(array('uid'=>$vote->uid))),
+      l(t('edit'), "nmoderation/edit/$vote->vote_id"),
+      l(t('delete'), "nmoderation/delete/$vote->vote_id")
+    );
   }
   if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
     $rows[] = array(array('data' => $pager, 'colspan' => $cols));
@@ -411,24 +633,44 @@
   return $output;
 }
 
-function nmoderation_list_node($gid, $realm = 'node_nid') {
-  $header = array(
-    array('data' => t('voter'), 'field' => 'u.name'),
-    array('data' => t('vote'), 'field' => 'v.vote'),
-    array('data' => t('value'), 'field' => 'nmuv.value'),
-    array('data' => t('operations'), 'colspan' => 2)
-  );
-  $sql = "SELECT v.vote, nmuv.uvid, nmuv.uid, nmuv.value, u.name FROM {nmoderation_uservotes} nmuv INNER JOIN {nmoderation_votes} v ON nmuv.mid = v.mid INNER JOIN {users} u ON nmuv.uid = u.uid WHERE nmuv.realm = '$realm' AND nmuv.gid = %d";
+function nmoderation_list_node($content_id, $content_type = 'node') {
+  if (user_access('administer node moderation votes')) {
+    $header = array(
+      array('data' => t('voter'), 'field' => 'u.name'),
+      array('data' => t('vote'), 'field' => 'v.vote'),
+      array('data' => t('value')),
+      array('data' => t('operations'), 'colspan' => 2)
+    );
+    $cols = 4;
+  }
+  else {
+    $header = array(
+      array('data' => t('voter'), 'field' => 'u.name'),
+      array('data' => t('vote'), 'field' => 'v.vote'),
+    );
+    $cols = 2;
+  }
+
+  $sql = "SELECT nv.vote, v.vote_id, v.uid, v.value, u.name FROM {votingapi_vote} v INNER JOIN {nmoderation_votes} nv ON v.value = nv.mid INNER JOIN {users} u ON v.uid = u.uid WHERE v.content_type = '$content_type' AND v.content_id = %d";
   $sql .= tablesort_sql($header);
-  $result = pager_query($sql, 50, NULL, NULL, $gid);
-  while ($vote = db_fetch_object($result)) {
-    $rows[] = array(format_name($vote), $vote->vote, $vote->value, l(t('edit'), "nmoderation/edit/$vote->uvid"), l(t('delete'), "nmoderation/delete/$vote->uvid"));
+  $result = pager_query($sql, 50, NULL, NULL, $content_id);
+
+  if (user_access('administer node moderation votes')) {
+    while ($vote = db_fetch_object($result)) {
+      $rows[] = array(theme('username', $vote), $vote->vote, nmoderation_get_value($vote->value, user_load(array('uid'=>$vote->uid))), l(t('edit'), "nmoderation/edit/$vote->vote_id"), l(t('delete'), "nmoderation/delete/$vote->vote_id"));
+    }
   }
+  else {
+    while ($vote = db_fetch_object($result)) {
+      $rows[] = array(theme('username', $vote), $vote->vote);
+    }
+  }
+
   if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
     $rows[] = array(array('data' => $pager, 'colspan' => $cols));
   }
   $output .= theme('table', $header, $rows);
-  $node = node_load(array('nid' => $gid));
+  $node = node_load($content_id);
   drupal_set_title($title);
   return $output;
 }
@@ -438,11 +680,38 @@
   $unpublish = drupal_map_assoc(array(-1, -2, -3, -4, -5, -6, -7, -8, -8, -10, -11, -12, -13, -14, -15, -20, -25, -30));
   $interval = drupal_map_assoc(range(1,60));
 
-  $output .= form_select(t('Node Types'), 'nmoderation_node_types', variable_get('nmoderation_node_types', drupal_map_assoc(node_list())), drupal_map_assoc(node_list()), t('Select the node types upon which accept node moderation votes.'), 0, 1);
-  $output .= form_select(t('Promote threshold'), 'nmoderation_threshold_promote', variable_get('nmoderation_threshold_promote', 4), $promote, t('When a post exceeds this moderation score, it is immediately <strong>promoted to the front page</strong>.'));
-  $output .= form_select(t('Unpublish threshold'), 'nmoderation_threshold_unpublish', variable_get('nmoderation_threshold_unpublish', -2), $unpublish, t('When a post drops below this score, it is immediately <strong>unpublished</strong>.'));
-  $output .= form_select(t('Voting Interval'), 'nmoderation_vote_interval', variable_get('nmoderation_vote_interval', 7), $interval, t('The number of days since the creation of a node when we allow voting.'));
-  return $output;
+  $form['nmoderation_node_types'] = array(
+    '#type' => 'select',
+    '#title' => t('Node Types'),
+    '#default_value' => variable_get('nmoderation_node_types', node_get_types()),
+    '#options' => node_get_types(),
+    '#description' => t('Select the node types upon which accept node moderation votes.'),
+    '#extra' => 0,
+    '#multiple' => 1,
+  );
+  $form['nmoderation_threshold_promote'] = array(
+    '#type' => 'select',
+    '#title' => t('Promote threshold'),
+    '#default_value' => variable_get('nmoderation_threshold_promote', 4),
+    '#options' => $promote,
+    '#description' => t('When a post exceeds this moderation score, it is immediately <strong>promoted to the front page</strong>.'),
+  );
+  $form['nmoderation_threshold_unpublish'] = array(
+    '#type' => 'select',
+    '#title' => t('Unpublish threshold'),
+    '#default_value' => variable_get('nmoderation_threshold_unpublish', -2),
+    '#options' => $unpublish,
+    '#description' => t('When a post drops below this score, it is immediately <strong>unpublished</strong>.'),
+  );
+  $form['nmoderation_vote_interval'] = array(
+    '#type' => 'select',
+    '#title' => t('Voting Interval'),
+    '#default_value' => variable_get('nmoderation_vote_interval', 7),
+    '#options' => $interval,
+    '#description' => t('The number of days since the creation of a node when we allow voting.'),
+  );
+
+  return $form;
 }
 
 
@@ -458,30 +727,35 @@
 }
 
 
-
 function nmoderation_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
   switch ($op) {
     case 'view':
-        if ($page && nmoderation_is_votable($node) && in_array($node->type, variable_get('nmoderation_node_types', drupal_map_assoc(node_list())))) {
+        if ($page && nmoderation_is_votable($node) && in_array($node->type, variable_get('nmoderation_node_types', node_get_types()))) {
           global $user;
-          $vote = nmoderation_get_vote($user->uid, $node->nid);
+          $vote = votingapi_get_vote('node', $node->nid, NMODERATION_VOTE_TYPE, NMODERATION_TAG, $user->uid);
 
-          if ($vote->uvid) {
-            $btn = t('Edit vote');
-            $action = "edit/$vote->uvid";
+          if ($vote->vote_id) {
+            $title = t('Edit vote');
           }
           else {
-            $btn = t('Add vote');
-            $action = "add/$node->nid";
+            $title = t('Add vote');
           }
-          if ($frm = nmoderation_form($vote->mid)) {
-            $frm .= form_hidden('destination', $_GET['q']);
-            $frm .= form_button($btn);
-            $node->body .= form($frm, 'post', url("nmoderation/$action"), array('class' => 'nmoderation-form'));
+          if ($frm = nmoderation_get_moderation_form('node', $node->nid, $vote, $title)) {
+            $node->body .= drupal_get_form('nmoderation_moderation_form', $frm);
           }
         }
         break;
   }
 }
 
-?>
+function nmoderation_votingapi(&$cache, $op, $arg3, $arg4, $arg5) {
+  if ($op == 'calculate' && $arg4 == 'node' && nmoderation_is_votable(node_load($arg5))) {
+    //loop through the $votes collection and calculate the weighted value.
+    foreach($arg3 as $vote) {
+      if ($vote->value_type == NMODERATION_VOTE_TYPE && $vote->tag == NMODERATION_TAG) {
+        $account = user_load(array('uid' => $vote->uid));
+        $cache[NMODERATION_TAG][NMODERATION_CACHE_TYPE]['vote'] = $cache[NMODERATION_CACHE_TAG][NMODERATION_TYPE]['vote'] + nmoderation_get_value($vote->value, $account);
+      }
+    }
+  }
+}
Index: modules/nmoderation/readme.txt
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/nmoderation/readme.txt,v
retrieving revision 1.4
diff -u -r1.4 readme.txt
--- modules/nmoderation/readme.txt	15 Apr 2005 15:26:23 -0000	1.4
+++ modules/nmoderation/readme.txt	7 Apr 2006 04:17:40 -0000
@@ -1,20 +1,14 @@
 DESCRIPTION
-This module enables users to vote on nodes and allows community promotion of nodes to the Drupal home page. Like comment moderation, the available votes and the value of each vote is configured by the administrator.
+This module enables users to vote on nodes and allows community promotion of nodes to the Drupal home page. The list of possible votes and the value of each vote is configured by the administrator.
 
-Each node maintains a score, based on the sum of all votes. As each vote is processed, the score is recalculated and if necessary, the post is either promoted to home page or unpublished. The thresholds for these actions are defined by the administrator.
+Each node maintains a score, based on the sum of all votes. As each vote is processed, the score is recalculated and if necessary, the post is either promoted to home page or unpublished. The thresholds for these actions are defined by the administrator. (For Drupal 4.7 and later, Node Moderation depends on the VotingAPI module.)
 
 USAGE
-1. Create the SQL tables. This depends a little on your system, but the most common method is:
+1. Copy the nmoderation and votingapi directories to the Drupal modules/ directory.
 
---- mysql -u username -ppassword drupal < nmoderation.mysql
-        
---- Postgres database support has not yet been tested.
+2. Enable boht VotingAPI and the Node Moderation module in the "administer >> modules" menu.
 
-2. Copy the nmoderation.module to the Drupal modules/ directory.
-
-3. Enable the Node Moderation module in the "administer >> modules" menu.
-
-4. Set your desired permissions to allow certain user roles access to node moderation. In the menu "administer >> users" and select the "configure >> permissions" tab.  Look at the permissions associated with the nmoderation module, they are:
+3. Set your desired permissions to allow certain user roles access to node moderation. In the menu "administer >> users" and select the "configure >> permissions" tab.  Look at the permissions associated with the nmoderation module, they are:
 
 --- administer node moderation configuration: This permission is for admins only, as it allows users to setup and manipulate the vote matrix.
 
@@ -22,7 +16,7 @@
 
 --- nmoderate nodes: This permission is for any user roles that you want to be allowed to vote on nodes.  NOTE: As a general rule anonymous users should not have this permission.
    
-5. Setup Moderation Votes.  The first step is to create moderation labels which allow users to rate a node. Go to "administer >> node moderation >> moderation votes" menu. In the vote field, enter the textual labels which users will see when casting their votes. Some examples are:
+4. Setup Moderation Votes.  The first step is to create moderation labels which allow users to rate a node. Go to "administer >> node moderation >> moderation votes" menu. In the vote field, enter the textual labels which users will see when casting their votes. Some examples are:
 
     * Excellent Post! +2
     * Good Post! +1
@@ -47,7 +41,7 @@
 
 10. Set the voting Interval.  Go to the "administer >> settings >> node moderation" menu and enter the number of days that the nodes shall be eligible for voting.
 
-11. Styling the voting form.  You may want to add the optional CSS rule contained in the nmoderation.css file to insure the vote form appears on its own line.
+11. Styling the voting form.  You may want to add the optional CSS rule contained in the nmoderation.css file to insure the vote form appears on its own line. For greater control, override the theme_nmoderation_moderation_form() function.
 
 12. Enjoy!
 
