Index: modules/paypal_subscription/paypal_subscription.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/paypal_subscription/paypal_subscription.module,v
retrieving revision 1.6
diff -u -r1.6 paypal_subscription.module
--- modules/paypal_subscription/paypal_subscription.module	25 May 2005 04:50:58 -0000	1.6
+++ modules/paypal_subscription/paypal_subscription.module	9 May 2006 18:28:23 -0000
@@ -61,7 +61,7 @@
 
     case 'admin/settings/paypal_subscription':
       return t('This module requires cron and paypal_framework.module.');
-    case 'admin/paypal_subscription':
+    case 'admin/paypal/subscription':
       return t('Create, edit, and delete PayPal subscriptions that you want to handle automatically.');
   }
 
@@ -79,18 +79,19 @@
   if ($may_cache) {
     $items[] = array('path' => 'admin/paypal/subscription',
                      'title' => t('subscriptions'),
-                     'callback' => 'paypal_subscription_admin',
+                     'callback' => 'paypal_subscription_admin_page',
                      'access' => user_access('administer paypal subscriptions'));
-  }
-  elseif (arg(0) == 'admin' && arg(1) == 'paypal' && arg(2) == 'subscription' && is_numeric(arg(3)) && arg(4)) {
-    $items[] = array('path' => 'admin/paypal/subscription/'.arg(3).'/subscribers',
+    $items[] = array('path' => 'admin/paypal/subscription/subscribers',
                      'title' => t('subscribers'),
-                     'callback' => 'paypal_subscription_admin',
-                     'type' => MENU_LOCAL_TASK);
-    $items[] = array('path' => 'admin/paypal_subscription/'.arg(3).'/edit',
+                     'callback' => 'paypal_subscription_admin_subscribers_page',
+                     'type' => MENU_CALLBACK);
+    $items[] = array('path' => 'admin/paypal/subscription/edit',
                      'title' => t('edit'),
-                     'callback' => 'paypal_subscription_admin',
-                     'type' => MENU_LOCAL_TASK);
+                     'callback' => 'paypal_subscription_admin_edit_page',
+                     'type' => MENU_CALLBACK);
+    $items[] = array('path' => 'admin/paypal/subscription/delete',
+                     'callback' => 'paypal_subscription_admin_delete_page',
+                     'type' => MENU_CALLBACK);
   }
 
   return $items;
@@ -107,13 +108,21 @@
  * Implementation of hook_settings()
  */
 function paypal_subscription_settings() {
-  $form = form_textfield(t('Hours between updates'), 
-                         'paypal_subscription_cron_period', 
-                         variable_get('paypal_subscription_cron_period', 12), 
-                         3, 10, 
-                         t('The primary purpose of updating is to demote users who have not paid recently.  So enter here the maximum amount of time that should transpire before a delinquent user is demoted. This should be a multiple of the time between cron updates.'));
-  $form .= form_checkbox(t('Enable debugging mode'), 'paypal_subscription_debug_enabled', TRUE, variable_get('paypal_subscription_debug_enabled', FALSE), t('Debugging messages will appear in the log when this box is checked.'));
-
+  $form['paypal_subscription_cron_period'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Hours between updates'),
+    '#default_value' => variable_get('paypal_subscription_cron_period', 12),
+    '#size' => 3,
+    '#maxlength' => 10,
+    '#description' => t('The primary purpose of updating is to demote users who have not paid recently.  So enter here the maximum amount of time that should transpire before a delinquent user is demoted. This should be a multiple of the time between cron updates.'),
+  );
+  $form['paypal_subscription_debug_enabled'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Enable debugging mode'),
+    '#return_value' => TRUE,
+    '#default_value' => variable_get('paypal_subscription_debug_enabled', FALSE),
+    '#description' => t('Debugging messages will appear in the log when this box is checked.'),
+  );
   return $form;
 }
 
@@ -306,239 +315,384 @@
   }
 }
 
-/**
- * Administer paypal subscriptions: add, edit, and delete
- */
-function paypal_subscription_admin() {
-  $op = $_POST['op'];
-  $edit = $_POST['edit'];
-  $id = arg(3);
-
-  if (empty($op)) {
-    $op = arg(4);
+function paypal_subscription_admin_edit_page($id = '') {
+  if (!is_numeric($id)) {
+    drupal_set_message(t('Invalid id.'), 'error');
+    drupal_goto('admin/paypal/subscription');
+    break;
   }
 
-  switch ($op) {
-    case t('edit'):
-      //
-      // Display the form to edit a single subscription.
-      //
-      if (!is_numeric($id)) {
-        drupal_set_message(t('Invalid id.'), 'error');
-        drupal_goto('admin/paypal/subscription');
-        break;
-      }
-
-      // Prepare data for the form
-      $period = array('1 day'=>t('1 day'), '2 days'=>t('2 days'), '1 week'=>t('1 week'), '2 weeks'=>t('2 weeks'), '1 month'=>t('1 month'), '2 months'=>t('2 months'), '6 months'=>t('6 months'), '1 year'=>t('1 year'));
-
-      $email_addresses = array();
-      foreach (explode("\n", variable_get('paypal_emails', '')) AS $email) {
-        $email_addresses[$email] = $email;
-      }
-
-      // Pass '1' to exclude 'anonymous user'
-      $roles = user_roles(1);
-
-      $currencies = array('USD' => t('U.S. Dollars'), 'GBP' => t('Pounds Sterling'), 'EUR' => t('Euros'), 'CAD' => t('Canadian Dollars'), 'JPY' => t('Yen'));
-      asort($currencies);
-
-      $subscription = db_fetch_object(db_query('SELECT * FROM {paypal_subscription} WHERE subscription_id=%d', $id));
+  $subscription = db_fetch_object(db_query('SELECT * FROM {paypal_subscription} WHERE subscription_id=%d', $id));
 
+  // Provide default values.
+  $defaults = _paypal_subscription_email_defaults();
+  
+  !$subscription->welcome_subject && $subscription->welcome_subject = $defaults->welcome_subject;
+  !$subscription->welcome_body    && $subscription->welcome_body    = $defaults->welcome_body;
+  !$subscription->warning_subject && $subscription->warning_subject = $defaults->warning_subject;
+  !$subscription->warning_body    && $subscription->warning_body    = $defaults->warning_body;
+  !$subscription->goodbye_subject && $subscription->goodbye_subject = $defaults->goodbye_subject;
+  !$subscription->goodbye_body    && $subscription->goodbye_body    = $defaults->goodbye_body;
+  
+  $form = _paypal_subscription_build_edit_form($subscription);
 
-      // Generate the form elements
-      $output = form_textfield(t('Subscription name'), 'name', $subscription->name, 64, 64);
-      $output .= form_textfield(t('PayPal item number'), 'item_number', $subscription->item_number, 64, 64);
-      $output .= form_select(t('PayPal recipient\'s email address'), 'receiver_email', $subscription->receiver_email, $email_addresses, t('PayPal uses email addresses to identify their accounts.  This list of email addresses comes from %paypal_framework.', array('%paypal_framework' => l('paypal_framework', 'admin/settings/paypal_framework'))));
-      $output .= form_select(t('Payment currency'), 'currency', $subscription->currency, $currencies, t('All payments must be made in this currency.  Payments in other currencies will not be rejected, but they will not count toward the subscription, either.'));
-      $output .= form_textfield(t('Payment amount'), 'payment', $subscription->payment, 16, 16, t('The minimum amount that must be paid in each time period.'));
-      $output .= form_select(t('Period'), 'period', $subscription->period, $period, t('This defines the length of time during which a user must pay.'));
-      $output .= form_select(t('Role to grant'), 'role', $subscription->role, $roles, t('When a user is paid up, they will be granted this role.  When they are delinquent, they will lose this role.'));
-
-      // Provide default values.
-      $defaults = _paypal_subscription_email_defaults();
-      !$subscription->welcome_subject && $subscription->welcome_subject = $defaults->welcome_subject;
-      !$subscription->welcome_body    && $subscription->welcome_body    = $defaults->welcome_body;
-      !$subscription->warning_subject && $subscription->warning_subject = $defaults->warning_subject;
-      !$subscription->warning_body    && $subscription->warning_body    = $defaults->warning_body;
-      !$subscription->goodbye_subject && $subscription->goodbye_subject = $defaults->goodbye_subject;
-      !$subscription->goodbye_body    && $subscription->goodbye_body    = $defaults->goodbye_body;
-      
-      $group = form_checkbox(t('Send welcome emails.'), 'send_welcome', 1, TRUE, t('Check this box to send new subscribers a welcoming email.'));
-      $group .= form_checkbox(t('Send warning emails.'), 'send_warning', 1, TRUE, t('Check this box to send subscribers an email when their subscription is less than 6 hours from ending.'));
-      $group .= form_checkbox(t('Send goodbye emails.'), 'send_goodbye', 1, TRUE, t('Check this box to send subscribers an email after their subscription ends.'));
-      $output .= form_group(t('Email settings'), $group, t('You may edit the email messages below.'));
-
-      $group = form_textfield(t('Subject of welcoming email'), 'welcome_subject', $subscription->welcome_subject, 64, 64);
-      $group .= form_textarea(t('Body of welcoming email'), 'welcome_body', $subscription->welcome_body, 70, 10);
-      $group .= form_textfield(t('Subject of warning email'), 'warning_subject', $subscription->warning_subject, 64, 64);
-      $group .= form_textarea(t('Body of warning email'), 'warning_body', $subscription->warning_body, 70, 10);
-      $group .= form_textfield(t('Subject of goodbye email'), 'goodbye_subject', $subscription->goodbye_subject, 64, 64);
-      $group .= form_textarea(t('Body of goodbye email'), 'goodbye_body', $subscription->goodbye_body, 70, 10);
-      $output .= form_group(t('Email messages'), $group, t('You may include the following variables in any field: %username, %site_name, %site_url, %login_url, %subscription_name, %subscription_price, %subscription_period, %item_number, %role, %payment_currency, %recipient_email, %subscription_end_date.<br /><br />Note: The %subscription_end_date is predicted using the assumption that the last payment from this user was greater than or equal to the %subscription_price.  If that is not the case, the subscription will still end at the correct time.  But because the prediction is wrong, the user may not receive a warning email and the predicted %subscription_end_date will be too far in the future.  This situation can be provoked if a user pays for a subscription in installments or if the site administrator raises the price while there are active subscriptions.'));
-
-      $output .= form_submit(t('Save subscription'));
-      $output .= form_submit(t('Delete subscription'));
-      $output .= form_hidden('subscription_id', $subscription->subscription_id);
-
-      $output = form($output);
-
-      print theme('page', $output);
-      break;
-
-    case t('Add subscription'):
-      $edit['subscription_id'] = db_next_id('{paypal_subscription}_subscription_id');
-
-      db_query('INSERT INTO {paypal_subscription} (subscription_id, name)
-                            VALUES (%d, "%s")',
-                            $edit['subscription_id'], $edit['name']);
-
-      drupal_set_message(t('PayPal subscription <em>%a</em> was added.', array('%a'=>$edit['name'])));
-      drupal_goto('admin/paypal/subscription/'.$edit['subscription_id'].'/edit');
-      break;
-
-    case t('Delete subscription'):
-      $output = '<p>'.t('Are you sure you want to remove the PayPal subscription <em>%subscription</em>?  This will not erase recorded transactions.', array('%subscription' => $edit['name'])).'</p>';
-      $output .= form_submit(t('Confirm delete'));
-      $output .= form_hidden('subscription_id', $edit['subscription_id']);
-
-      drupal_set_title(t('Delete PayPal subscription'));
-      print theme('page', form($output)); 
-      break;
-    case t('Confirm delete'):
-      db_query('DELETE FROM {paypal_subscription} WHERE subscription_id=%d', $id);
-
-      drupal_set_message(t('The PayPal subscription was removed.'));
-      drupal_goto('admin/paypal/subscription');
-      break;
-
-    case t('Save subscription'):
-      db_query('UPDATE {paypal_subscription} SET name="%s", item_number="%s", 
-                                                 receiver_email="%s", currency="%s", 
-                                                 payment="%s", period="%s", 
-                                                 role=%d, send_welcome=%d,
-                                                 send_warning=%d, send_goodbye=%d,
-                                                 welcome_subject="%s", welcome_body="%s",
-                                                 warning_subject="%s", warning_body="%s",
-                                                 goodbye_subject="%s", goodbye_body="%s"
-                                                 WHERE subscription_id=%d',
-               $edit['name'], $edit['item_number'], $edit['receiver_email'], $edit['currency'], 
-               $edit['payment'], $edit['period'], $edit['role'], $edit['send_welcome'],
-               $edit['send_warning'], $edit['send_goodbye'], $edit['welcome_subject'], 
-               $edit['welcome_body'], $edit['warning_subject'], $edit['warning_body'],
-               $edit['goodbye_subject'], $edit['goodbye_body'], $edit['subscription_id']);
-
-      drupal_set_message(t('Your changes were saved.'));
-      drupal_goto('admin/paypal/subscription');
-      break;
-
-    case t('subscribers'):
-      //
-      // Print a list of people who have paid anything for the current time period.  Those who have paid too much
-      // and those who have paid too little will be flagged.
-      //
-      $subscription = _paypal_subscription_load($id);
-      $title = t('PayPal subscriptions: %subscription_name', array('%subscription_name' => $subscription->name));
+  $output = drupal_get_form('paypal_subscriptions_edit', $form);
 
-      $timeperiod = _paypal_subscription_time_period($id);
+  return $output;
+}
 
-      //
-      // Make the table sortable.
-      //
-      $header = array(array('data' => t('Username'), 'field' => 'u.name', 'sort' => 'asc'), 
-                      array('data' => t('Real name'), 'field' => 'realname'),
-                      array('data' => t('Email address'), 'field' => 'ppl.payer_email'),
-                      array('data' => t('Total payment'), 'field' => 'payment'),
-                      array('data' => t('Last transaction'), 'field' => 'last_payment_date')
-                     );
-      $result = pager_query('SELECT u.uid, u.name as username, ppl.payer_email AS email_address, 
-                               concat(ppp.first_name, " ", ppp.last_name) as realname, ppp.payer_id, 
-                               SUM(ppl.mc_gross) AS payment, UNIX_TIMESTAMP(MAX(ppl.transaction_date)) AS last_payment_date 
-                             FROM {paypal_log} ppl 
-                               LEFT JOIN {users} u ON ppl.payer_email=u.mail 
-                               LEFT JOIN {paypal_payer} ppp ON ppl.payer_id=ppp.payer_id
-                             WHERE ppl.mc_currency="%s" 
-                               AND UNIX_TIMESTAMP(ppl.transaction_date) >= %d 
-                               AND UNIX_TIMESTAMP(ppl.transaction_date) <  %d 
-                               AND ppl.item_number="%s" 
-                             GROUP BY ppl.payer_email 
-                             %s', 
-                             25, 0,
-                             'SELECT COUNT(DISTINCT(ppl.payer_id))
-                              FROM {paypal_log} ppl
-                              WHERE ppl.mc_currency="%s"
-                                AND UNIX_TIMESTAMP(ppl.transaction_date) >= %d
-                                AND UNIX_TIMESTAMP(ppl.transaction_date) <  %d
-                                AND ppl.item_number="%s"',
-                             $subscription->currency, $timeperiod->start, $timeperiod->stop, $subscription->item_number, 
-                             tablesort_sql($header));
+function paypal_subscription_admin_subscribers_page($id = '') {
+  if (!is_numeric($id)) {
+    drupal_set_message(t('Invalid id.'), 'error');
+    drupal_goto('admin/paypal/subscription');
+    break;
+  }
 
-      //
-      // Create the page title.
-      //
-      // The subscription period is stored as an English string.  There is a finite list of possibilities:
-      // see $period near line 89 above.
-      //
-      $output = '<div class="paypal-subtitle">' . t('%duration: %start to %stop', array('%duration' => t($subscription->period), '%start' => format_date($timeperiod->start), '%stop' => format_date($timeperiod->stop))) . '</div>';
+  //
+  // Print a list of people who have paid anything for the current time period.  Those who have paid too much
+  // and those who have paid too little will be flagged.
+  //
+  $subscription = _paypal_subscription_load($id);
+  $title = t('PayPal subscriptions: %subscription_name', array('%subscription_name' => $subscription->name));
+  
+  $timeperiod = _paypal_subscription_time_period($id);
+  
+  //
+  // Make the table sortable.
+  //
+  $header = array(array('data' => t('Username'), 'field' => 'u.name', 'sort' => 'asc'), 
+                  array('data' => t('Real name'), 'field' => 'realname'),
+                  array('data' => t('Email address'), 'field' => 'ppl.payer_email'),
+                  array('data' => t('Total payment'), 'field' => 'payment'),
+                  array('data' => t('Last transaction'), 'field' => 'last_payment_date')
+                 );
+  $result = pager_query('SELECT u.uid, u.name as username, ppl.payer_email AS email_address, 
+                           concat(ppp.first_name, " ", ppp.last_name) as realname, ppp.payer_id, 
+                           SUM(ppl.mc_gross) AS payment, UNIX_TIMESTAMP(MAX(ppl.transaction_date)) AS last_payment_date 
+                         FROM {paypal_log} ppl 
+                           LEFT JOIN {users} u ON ppl.payer_email=u.mail 
+                           LEFT JOIN {paypal_payer} ppp ON ppl.payer_id=ppp.payer_id
+                         WHERE ppl.mc_currency="%s" 
+                           AND UNIX_TIMESTAMP(ppl.transaction_date) >= %d 
+                           AND UNIX_TIMESTAMP(ppl.transaction_date) <  %d 
+                           AND ppl.item_number="%s" 
+                         GROUP BY ppl.payer_email 
+                         %s', 
+                         25, 0,
+                         'SELECT COUNT(DISTINCT(ppl.payer_id))
+                          FROM {paypal_log} ppl
+                          WHERE ppl.mc_currency="%s"
+                            AND UNIX_TIMESTAMP(ppl.transaction_date) >= %d
+                            AND UNIX_TIMESTAMP(ppl.transaction_date) <  %d
+                            AND ppl.item_number="%s"',
+                         $subscription->currency, $timeperiod->start, $timeperiod->stop, $subscription->item_number, 
+                         tablesort_sql($header));
+  
+  //
+  // Create the page title.
+  //
+  // The subscription period is stored as an English string.  There is a finite list of possibilities:
+  // see $period near line 89 above.
+  //
+  $output = '<div class="paypal-subtitle">' . t('%duration: %start to %stop', array('%duration' => t($subscription->period), '%start' => format_date($timeperiod->start), '%stop' => format_date($timeperiod->stop))) . '</div>';
+  
+  //
+  // Display a reader-friendly description of the currency.
+  //
+  $currencies = array('USD' => 'US$', 'CAD' => 'CA$', 'GBP' => '&pound;', 'EUR' => '&euro;', 'YEN' => '&yen;');
+  $currency = $currencies[$subscription->currency];
+  
+  //
+  // Fill the table with information.
+  //
+  while ($payer = db_fetch_object($result)) {
+    if ($payer->payment > $subscription->payment) {
+      $value = '<span class="paypal-excess">'.$payer->payment." $currency</span>";
+    }
+    elseif ($payer->payment == $subscription->payment) {
+      $value = '<span class="paypal-okay">'.$payer->payment." $currency</span>";
+    }
+    elseif ($payer->payment > 0) {
+      $value = '<span class="paypal-error">'.$payer->payment." $currency</span>";
+    }
+  
+    $rows[] = array(l($payer->name, 'user/'.$payer->uid), l($payer->realname, 'admin/paypal/payer/'.$payer->payer_id), $payer->email_address, $value, format_date($payer->last_payment_date));
+  }
+  
+  if (!$rows) {
+    $rows[] = array(array('data' => t('No payments were made to this subscription in this time period.'), 'colspan' => 6));
+  }
+  if ($pager = theme('pager', NULL, 25, 0, tablesort_pager())) {
+    $rows[] = array(array('data' => $pager, 'colspan' => '6'));
+  }
+  
+  $output .= theme('table', $header, $rows);
+  
+  drupal_set_title($title);
 
-      //
-      // Display a reader-friendly description of the currency.
-      //
-      $currencies = array('USD' => 'US$', 'CAD' => 'CA$', 'GBP' => '&pound;', 'EUR' => '&euro;', 'YEN' => '&yen;');
-      $currency = $currencies[$subscription->currency];
+  return $output;
+}
 
-      //
-      // Fill the table with information.
-      //
-      while ($payer = db_fetch_object($result)) {
-        if ($payer->payment > $subscription->payment) {
-          $value = '<span class="paypal-excess">'.$payer->payment." $currency</span>";
-        }
-        elseif ($payer->payment == $subscription->payment) {
-          $value = '<span class="paypal-okay">'.$payer->payment." $currency</span>";
-        }
-        elseif ($payer->payment > 0) {
-          $value = '<span class="paypal-error">'.$payer->payment." $currency</span>";
-        }
+/*
+ * Provide a form to confirm deletion of a view.
+ */
+function paypal_subscription_admin_delete_page($id = '') {
+  $subscription = db_fetch_object(db_query('SELECT * FROM {paypal_subscription} WHERE subscription_id=%d', $id));
 
-        $rows[] = array(l($payer->name, 'user/'.$payer->uid), l($payer->realname, 'admin/paypal/payer/'.$payer->payer_id), $payer->email_address, $value, format_date($payer->last_payment_date));
-      }
+  if (!$subscription) {
+    drupal_set_message(t('Invalid id.'), 'error');
+    drupal_goto('admin/paypal/subscription');
+    break;
+  }
 
-      if (!$rows) {
-        $rows[] = array(array('data' => t('No payments were made to this subscription in this time period.'), 'colspan' => 6));
-      }
-      if ($pager = theme('pager', NULL, 25, 0, tablesort_pager())) {
-        $rows[] = array(array('data' => $pager, 'colspan' => '6'));
-      }
+  $form['subscription_id'] = array('#type' => 'value', '#value' => $subscription->subscription_id);
+  return confirm_form('paypal_subscription_delete_confirm', $form,
+    t('Are you sure you want to remove the PayPal subscription <em>%subscription</em>?  This will not erase recorded transactions.', array('%subscription' => $subscription->name)), 
+    $_GET['destination'] ? $_GET['destination'] : 'admin/paypal/subscription', 
+    t('This action cannot be undone.'),
+    t('Delete'), t('Cancel')  
+  );
+}
 
-      $output .= theme('table', $header, $rows);
+/*
+ * Handle the submit button to delete a view.
+ */
+function paypal_subscription_delete_confirm_submit($formid, $form) {
+  if ($form['confirm']) {
+    db_query('DELETE FROM {paypal_subscription} WHERE subscription_id=%d', $form['subscription_id']);
+    drupal_set_message(t('The PayPal subscription was removed.'));
+    drupal_goto('admin/paypal/subscription');
+  }
+}
 
-      drupal_set_title($title);
-      print theme('page', $output);
-      break;
 
-    default:
-      //
-      // Create a list of PayPal subscriptions with 'edit' links and a box to add a new one.
-      //
-      $result = db_query('SELECT subscription_id AS id, name, item_number FROM {paypal_subscription} ORDER BY name');
+/**
+ * Administer paypal subscriptions
+ */
+function paypal_subscription_admin_page() {
+  $result = db_query('SELECT subscription_id AS id, name, item_number FROM {paypal_subscription} ORDER BY name');
+  
+  $header = array(t('Name'), t('Operations'));
+  while ($row = db_fetch_object($result)) {
+    $rows[] = array($row->name, 
+                    array('data' => l(t('edit'), 'admin/paypal/subscription/edit/'.$row->id) .'<br />'. 
+                                    l(t('view subscribers'), 'admin/paypal/subscription/subscribers/'.$row->id).'<br />'.
+                                    l(t('view transactions'), 'admin/paypal/item/'.$row->item_number)
+                         )
+                   );
+  }
+  if ($rows) {
+    $output = theme('table', $header, $rows);
+  }
+    
+  // Generate the form elements
+  $form['name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Add a new subscription'),
+    '#size' => 64,
+    '#maxlength' => 64,
+  );
+  
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Add subscription'),
+  );
+  
+  $output .= drupal_get_form('paypal_subscriptions_add', $form);  
+  
+  return $output;
+}
 
-      $header = array(t('Name'), t('Operations'));
-      while ($row = db_fetch_object($result)) {
-        $rows[] = array($row->name, 
-                        array('data' => l(t('edit'), 'admin/paypal/subscription/'.$row->id.'/edit') .'<br />'. 
-                                        l(t('view subscribers'), 'admin/paypal/subscription/'.$row->id.'/subscribers').'<br />'.
-                                        l(t('view transactions'), 'admin/paypal/item/'.$row->item_number)
-                             )
-                       );
-      }
-      $rows[] = array('<input type="text" size="64" maxlength="64" name="edit[name]" />', '<input type="submit" name="op" value="'. t('Add subscription') .'" />');
+function paypal_subscriptions_add_submit($form_id, $form_values) {
+  $form_values['subscription_id'] = db_next_id('{paypal_subscription}_subscription_id');
+  
+  db_query('INSERT INTO {paypal_subscription} (subscription_id, name)
+                        VALUES (%d, "%s")',
+                        $form_values['subscription_id'], $form_values['name']);
+  
+  drupal_set_message(t('PayPal subscription <em>%a</em> was added.', array('%a'=>$form_values['name'])));
+  drupal_goto('admin/paypal/subscription/edit/'.$form_values['subscription_id']);
+}
 
-      $output = theme('table', $header, $rows);
-      $output = form($output);
+function paypal_subscriptions_edit_submit($form_id, $form_values) {
+  db_query('UPDATE {paypal_subscription} SET name="%s", item_number="%s", 
+                                           receiver_email="%s", currency="%s", 
+                                           payment="%s", period="%s", 
+                                           role=%d, send_welcome=%d,
+                                           send_warning=%d, send_goodbye=%d,
+                                           welcome_subject="%s", welcome_body="%s",
+                                           warning_subject="%s", warning_body="%s",
+                                           goodbye_subject="%s", goodbye_body="%s"
+                                           WHERE subscription_id=%d',
+         $form_values['name'], $form_values['item_number'], $form_values['receiver_email'], $form_values['currency'], 
+         $form_values['payment'], $form_values['period'], $form_values['role'], $form_values['send_welcome'],
+         $form_values['send_warning'], $form_values['send_goodbye'], $form_values['welcome_subject'], 
+         $form_values['welcome_body'], $form_values['warning_subject'], $form_values['warning_body'],
+         $form_values['goodbye_subject'], $form_values['goodbye_body'], $form_values['subscription_id']);
+
+  drupal_set_message(t('Your changes were saved.'));
+  drupal_goto('admin/paypal/subscription');
+}
+
+function _paypal_subscription_build_edit_form($subscription) {
+  // Prepare data for the form
+  $period = array('1 day'=>t('1 day'), '2 days'=>t('2 days'), '1 week'=>t('1 week'), '2 weeks'=>t('2 weeks'), '1 month'=>t('1 month'), '2 months'=>t('2 months'), '6 months'=>t('6 months'), '1 year'=>t('1 year'));
+
+  $email_addresses = array();
+  foreach (explode("\n", variable_get('paypal_emails', '')) AS $email) {
+    $email_addresses[$email] = $email;
+  }
+
+  // Pass '1' to exclude 'anonymous user'
+  $roles = user_roles(1);
+
+  $currencies = array('USD' => t('U.S. Dollars'), 'GBP' => t('Pounds Sterling'), 'EUR' => t('Euros'), 'CAD' => t('Canadian Dollars'), 'JPY' => t('Yen'));
+  asort($currencies);
+
+  // Generate the form elements
+  $form['name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Subscription name'),
+    '#default_value' => $subscription->name,
+    '#size' => 64,
+    '#maxlength' => 64,
+  );
+  
+  $form['item_number'] = array(
+    '#type' => 'textfield',
+    '#title' => t('PayPal item number'),
+    '#default_value' => $subscription->item_number,
+    '#size' => 64,
+    '#maxlength' => 64,
+  );
+  
+  $form['receiver_email'] = array(
+    '#type' => 'select',
+    '#title' => t('PayPal recipient\'s email address'),
+    '#default_value' => $subscription->receiver_email,
+    '#options' => $email_addresses,
+    '#description' => t('PayPal uses email addresses to identify their accounts.  This list of email addresses comes from %paypal_framework.', array('%paypal_framework' => l('paypal_framework', 'admin/settings/paypal_framework'))),
+  );
+  
+  $form['payment'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Payment amount'),
+    '#default_value' => $subscription->payment,
+    '#size' => 16,
+    '#maxlength' => 16,
+    '#description' => t('The minimum amount that must be paid in each time period.'),
+  );
+  
+  $form['period'] = array(
+    '#type' => 'select',
+    '#title' => t('Period'),
+    '#default_value' => $subscription->period,
+    '#options' => $period,
+    '#description' => t('This defines the length of time during which a user must pay.'),
+  );
+  
+  $form['role'] = array(
+    '#type' => 'select',
+    '#title' => t('Role to grant'),
+    '#default_value' => $subscription->role,
+    '#options' => $roles,
+    '#description' => t('When a user is paid up, they will be granted this role.  When they are delinquent, they will lose this role.'),
+  );
+  
+  $form['email_settings'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Email settings'),
+    '#description' => t('You may edit the email messages below.'),
+    '#collapsible' => true,
+    '#collapsed' => true,
+ );
+  $form['email_settings']['send_welcome'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Send welcome emails.'),
+    '#return_value' => 1,
+    '#default_value' => TRUE,
+    '#description' => t('Check this box to send new subscribers a welcoming email.'),
+  );
+  $form['email_settings']['send_warning'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Send warning emails.'),
+    '#return_value' => 1,
+    '#default_value' => TRUE,
+    '#description' => t('Check this box to send subscribers an email when their subscription is less than 6 hours from ending.'),
+  );
+  $form['email_settings']['send_goodbye'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Send goodbye emails.'),
+    '#return_value' => 1,
+    '#default_value' => TRUE,
+    '#description' => t('Check this box to send subscribers an email after their subscription ends.'),
+  );
+  
+  $form['email_messages'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Email messages'),
+    '#description' => t('You may include the following variables in any field: %username, %site_name, %site_url, %login_url, %subscription_name, %subscription_price, %subscription_period, %item_number, %role, %payment_currency, %recipient_email, %subscription_end_date.<br /><br />Note: The %subscription_end_date is predicted using the assumption that the last payment from this user was greater than or equal to the %subscription_price.  If that is not the case, the subscription will still end at the correct time.  But because the prediction is wrong, the user may not receive a warning email and the predicted %subscription_end_date will be too far in the future.  This situation can be provoked if a user pays for a subscription in installments or if the site administrator raises the price while there are active subscriptions.'),
+    '#collapsible' => true,
+    '#collapsed' => true,
+  );
+  $form['email_messages']['welcome_subject'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Subject of welcoming email'),
+    '#default_value' => $subscription->welcome_subject,
+    '#size' => 64,
+    '#maxlength' => 64,
+  );
+  $form['email_messages']['welcome_body'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Body of welcoming email'),
+    '#default_value' => $subscription->welcome_body,
+    '#cols' => 70,
+    '#rows' => 10,
+  );
+  $form['email_messages']['warning_subject'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Subject of warning email'),
+    '#default_value' => $subscription->warning_subject,
+    '#size' => 64,
+    '#maxlength' => 64,
+  );
+  $form['email_messages']['warning_body'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Body of warning email'),
+    '#default_value' => $subscription->warning_body,
+    '#cols' => 70,
+    '#rows' => 10,
+  );
+  $form['email_messages']['goodbye_subject'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Subject of goodbye email'),
+    '#default_value' => $subscription->goodbye_subject,
+    '#size' => 64,
+    '#maxlength' => 64,
+  );
+  $form['email_messages']['goodbye_body'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Body of goodbye email'),
+    '#default_value' => $subscription->goodbye_body,
+    '#cols' => 70,
+    '#rows' => 10,
+  );
+  $form['subscription_id'] = array(
+    '#type' => 'hidden',
+    '#value' => $subscription->subscription_id,
+  );
+  
 
-      print theme('page', $output);
-  }
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save subscription'),
+  );
+  $form['delete'] = array(
+    '#type' => 'submit',
+    '#value' => t('Delete subscription'),
+  );
+  
+  return $form;
 }
 
 /**
@@ -729,4 +883,3 @@
     watchdog('paypal_subscription', ($name ? "$name: " : '') . _paypal_print_object($object));
   }
 }
-?>
