--- paypernode.module	2007-06-12 03:34:50.000000000 -0700
+++ paypernode.module.new	2007-07-24 13:36:49.000000000 -0700
@@ -702,4 +702,60 @@ function paypernode_user_update($uid, $t
   }
 
 }
-?>
\ No newline at end of file
+
+/**
+ * Process node removals at expiry time and unpublish the nodes from
+ * the system.
+ *
+ * This function increments $GLOBALS['expirations']['nodes_removed'] each time
+ * it removes a node.
+ *
+ * @param $node Product for which nodes are processed. This function expects
+ * $node->expired_schedule to be set to the expiring entry from
+ * ec_recurring_schedule and $node->uid to be the user that purchased the
+ * product.
+ */
+function paypernode_atexpiry($node) {
+  global $expirations;
+
+  // Do nothing if the product was previously renewed
+  if ($node->expired_schedule['status'] == ECRECURRING_STATUS_RENEWED) {
+    return;
+  }
+
+  // Try and find the node(s) that needs to be unpublished.
+  // NOTE: This would probably be a lot better if we could somehow associate pay-per-nodes with the transaction they were purchased from, but that would require some big changes.
+  $qty = db_fetch_object(db_query("SELECT qty FROM {ec_transaction_product} WHERE txnid = %d AND nid = %d", $node->txnid, $node->nid));
+  $result = db_query("SELECT n.nid FROM {node} n WHERE n.type = '%s' AND n.uid = %d AND n.status = 1 ORDER BY n.created LIMIT {$qty->qty}", $node->node_type, $node->expired_schedule['uid']);
+  $nodes = array();
+  while ($nid = db_fetch_object($result)) {
+    $nodes[] = $nid->nid;
+    $expirations['nodes_removed']++;
+  }
+  node_operations_unpublish($nodes);
+  // Also make them anonymous so the user can't re-publish them
+  db_query('UPDATE {node} SET uid = 0 WHERE nid IN(%s)', implode(',', $nodes));
+}
+
+/**
+ * Implementation of hook_recurringapi().
+ */
+function paypernode_recurringapi($op, &$obj, $val1 = NULL, $val2 = NULL) {
+  switch ($op) {
+    case 'on expiry':
+      paypernode_atexpiry($obj);
+      break;
+    case 'on purchase':
+      // If it's a renewal then the node is already created, and thus we need
+      // to decrement the number they are allowed to create
+      if ($val2) {
+        $node = node_load($val1);
+        db_query("UPDATE {ec_paypernode_user} SET allowed = allowed - %d WHERE uid = %d AND node_type = '%s'", $node->node_qtty, $obj['uid'], $node->node_type);
+      }
+      break;
+    case 'cron report':
+      print "Nodes removed: ".$GLOBALS['expirations']['nodes_removed']."\n\n";
+      break;
+  }
+}
+?>
