From 496de8944d242e5072af9f1cbb9bb9de3084b0df Mon Sep 17 00:00:00 2001
From: Lorenz Schori <lo@znerol.ch>
Date: Mon, 29 Aug 2011 22:15:57 +0200
Subject: [PATCH 3/3] Rewrite regcode_og for drupal 7

Rewrite regcode_og in the spirit of the drupal 7 port of
regcode_dynamic. Use machine_name and store rules in a variable instead
of a table. This will aid with the exportability of the configuration.
Implement the user interface with some drupal 7 sugar, especially the
self updating machine name widget and local actions.
---
 regcode_og/regcode_og.install |   46 +-------
 regcode_og/regcode_og.module  |  289 +++++++++++++++++++++++++++-------------
 2 files changed, 196 insertions(+), 139 deletions(-)

diff --git a/regcode_og/regcode_og.install b/regcode_og/regcode_og.install
index 1feb138..1915c16 100644
--- a/regcode_og/regcode_og.install
+++ b/regcode_og/regcode_og.install
@@ -10,49 +10,5 @@
  * Implements hook_uninstall().
  */
 function regcode_og_uninstall() {
-  // TODO The drupal_(un)install_schema functions are called automatically in D7.
-  // drupal_uninstall_schema('regcode_og')
-}
-
-
-/**
- * Implements hook_install().
- */
-function regcode_og_install() {
-  // TODO The drupal_(un)install_schema functions are called automatically in D7.
-  // drupal_install_schema('regcode_og')
-}
-
-
-/**
- * Implements hook_schema().
- */
-function regcode_og_schema() {
-  $schema['regcode_og'] = array(
-    'description' => 'Registration code organic group assignment information',
-    'fields' => array(
-      'id' => array(
-        'description' => 'Rule ID',
-        'type' => 'serial',
-        'unsigned' => TRUE,
-        'not null' => TRUE,
-        'size' => 'normal',
-      ),
-      'tid' => array(
-        'description' => 'Term ID',
-        'type' => 'int',
-        'size' => 'normal',
-        'not null' => TRUE,
-      ),
-      'og' => array(
-        'description' => 'Organic Group ID',
-        'type' => 'int',
-        'unsigned' => TRUE,
-        'size' => 'normal',
-      ),
-    ),
-    'primary key' => array('id'),
-  );
-
-  return $schema;
+  variable_del('regcode_og_settings');
 }
diff --git a/regcode_og/regcode_og.module b/regcode_og/regcode_og.module
index 19f90f6..cd1af85 100644
--- a/regcode_og/regcode_og.module
+++ b/regcode_og/regcode_og.module
@@ -1,14 +1,6 @@
 <?php
 
 /**
- * TODO this function no longer exists in D7!
- */
-function og_all_groups_options() {
-  return array();
-}
-
-
-/**
  * Implements hook_help().
  */
 function regcode_og_help($path, $arg) {
@@ -35,17 +27,37 @@ function regcode_og_menu() {
     'title' => t('Organic Groups'),
     'description' => t('Automate organic group assignment'),
     'page callback' => 'drupal_get_form',
-    'page arguments' => array('regcode_og_admin'),
+    'page arguments' => array('regcode_og_rules_page'),
     'type' => MENU_LOCAL_TASK,
     'access arguments' => array('administer registration codes'),
     'weight' => 101,
   );
 
-  $items['admin/config/people/regcode/og/delete/%'] = array(
-    'page callback' => 'regcode_og_delete_rule',
-    'page arguments' => array(5),
+  $items['admin/config/people/regcode/og/rule/%'] = array(
+    'title' => 'Edit rule',
+    'description' => 'Modify settings for this og assignement rule',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('regcode_og_settings', 6),
+    'access arguments' => array('administer registration codes'),
     'type' => MENU_CALLBACK,
+  );
+
+  $items['admin/config/people/regcode/og/add-rule'] = array(
+    'title' => 'Add rule',
+    'description' => 'Create a new og assignement rule',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('regcode_og_create'),
     'access arguments' => array('administer registration codes'),
+    'type' => MENU_LOCAL_ACTION,
+  );
+
+  $items['admin/config/people/regcode/og/rule/%/delete'] = array(
+    'title' => 'Delete rule',
+    'description' => 'Delete settings for this og assignement rule',
+    'page callback' => 'regcode_og_settings_delete',
+    'page arguments' => array(6),
+    'access arguments' => array('administer registration codes'),
+    'type' => MENU_CALLBACK,
   );
 
   return $items;
@@ -53,49 +65,69 @@ function regcode_og_menu() {
 
 
 /**
- * Delete a rule
+ * Callback: Delete a rule
  */
-function regcode_og_delete_rule($rid) {
-  db_delete('regcode_og')
-    ->condition('id', $rid)
-    ->execute();
-  drupal_set_message(t('Rule was deleted (Rule ##rule)', array('#rule' => $rid)));
-  drupal_goto('admin/user/regcode/og');
+function regcode_og_settings_delete($machine_name) {
+  $settings = variable_get('regcode_og_settings', array());
+  unset($settings[$machine_name]);
+  variable_set('regcode_og_settings', $settings);
+
+  drupal_set_message(t('Rule deleted'));
+  drupal_goto('admin/config/people/regcode/og');
 }
 
 
 /**
- * Admin page for role assignment
+ * Form: Settings form for an og assignement rule
  */
-function regcode_og_admin($form, &$form_state) {
-  $form = array();
+function regcode_og_settings($form, &$form_state, $machine_name) {
+  $settings = variable_get('regcode_og_settings', array());
+  if (!isset($settings[$machine_name])) {
+    drupal_not_found();
+  }
+
+  $data = $settings[$machine_name];
+
+  $gids = og_get_all_group();
+  $options = array();
+  foreach($gids as $gid) {
+     $options[$gid] = og_label($gid);
+  }
 
-  $form['regcode_og']['new'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Create a new rule')  ,
+  // store rule in form state
+  $form_state['regcode_og_rule'] = $data;
+
+  $form['regcode_og_rule']['name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Rule name'),
+    '#required' => TRUE,
+    '#default_value' => $data['name'],
   );
 
-  $form['regcode_og']['new']['ogs'] = array(
+  $form['regcode_og_rule']['ogs'] = array(
     '#type' => 'checkboxes',
-    '#title' => t('Assign organic group(s)'),
-    '#options' => og_all_groups_options(),
+    '#title' => t('Groups'),
+    '#description' => t('Assign user to this og group(s)'),
+    '#options' => $options,
+    '#default_value' => (array) $data['ogs'],
   );
 
-  $form['regcode_og']['new']['tid'] = array(
+  $form['regcode_og_rule']['tid'] = array(
     '#type' => 'select',
-    '#title' => t('When a user uses a regcode tagged with'),
+    '#title' => t('Tag'),
+    '#description' => t('When a user uses a regcode tagged with this term'),
     '#options' => regcode_get_vocab_terms(),
+    '#default_value' => $data['tid'],
   );
 
-  $form['regcode_og']['new']['submit'] = array(
+  $form['regcode_og_save'] = array(
     '#type' => 'submit',
-    '#value' => t('Create rule'),
+    '#value' => t('Save rule'),
   );
 
-
-  $form['regcode_og']['list'] = array(
-    '#type' => 'markup',
-    '#value' => regcode_og_rules_list_markup(),
+  $form['regcode_og_delete'] = array(
+    '#type' => 'submit',
+    '#value' => t('Delete rule'),
   );
 
   return $form;
@@ -103,84 +135,149 @@ function regcode_og_admin($form, &$form_state) {
 
 
 /**
- * Return the formatted HTML list
+ * Form submit: Save settings form
  */
-function regcode_og_rules_list_markup() {
-  $headings = array(
-    t('Rule ID'),
-    t('Term'),
-    t('Group ID'),
-    t('Group Name'),
-    t('Actions'),
-  );
-
-  $rows = regcode_og_get_rules(array(), TRUE);
-
-  $group_name_mapping = og_all_groups_options();
+function regcode_og_settings_submit($form, $form_state) {
+  $data = $form_state['regcode_og_rule'];
+  $machine_name = $data['machine_name'];
 
-  // Add actions
-  foreach ($rows as &$row) {
-    $row['group_name'] = $group_name_mapping[$row['ogid']];
-    $row['action'] = l(t('Remove'), 'admin/user/regcode/og/delete/' . $row['id']);
+  foreach (element_children($form['regcode_og_rule']) as $key) {
+    $data[$key] = $form_state['values'][$key];
   }
 
-  return theme('table', array('header' => $headings, 'rows' => $rows));
+  $settings = variable_get('regcode_og_settings', array());
+  $settings[$machine_name] = $data;
+  variable_set('regcode_og_settings', $settings);
+
+  drupal_set_message(t('Your settings have been saved.'));
+  drupal_goto('admin/config/people/regcode/og');
 }
 
 
 /**
- * Create the roles
+ * Form: Create form for og assignement rules
  */
-function regcode_og_admin_submit($form, $form_state) {
-  $ogs = array_filter($form_state['values']['ogs']);
-  $tid = $form_state['values']['tid'];
+function regcode_og_create($form, &$form_state) {
+  $gids = og_get_all_group();
+  $options = array();
+  foreach($gids as $gid) {
+     $options[$gid] = og_label($gid);
+  }
+
+  $form['name'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Rule name'),
+    '#maxlength' => 255,
+    '#description' => t('Name this rule for administration purposes.'),
+    '#required' => TRUE,
+  );
+
+  $form['machine_name'] = array(
+    '#type' => 'machine_name',
+    '#title' => t('Machine name'),
+    '#maxlength' => 21,
+    '#description' => t('A unique name to construct the URL for this rule. It must only contain lowercase letters, numbers and hyphens.'),
+    '#machine_name' => array(
+      'exists' => 'regcode_og_name_exists',
+    ),
+  );
+
+  $form['ogs'] = array(
+    '#type' => 'checkboxes',
+    '#title' => t('Groups'),
+    '#options' => $options,
+    '#description' => t('Assign user to this og group(s)'),
+    '#required' => TRUE,
+  );
 
-  regcode_og_create_rule($tid, $ogs);
-  drupal_set_message(t('New registration code rule created.'));
+  $form['tid'] = array(
+    '#type' => 'select',
+    '#title' => t('Tag'),
+    '#description' => t('When a user uses a regcode tagged with this term'),
+    '#options' => regcode_get_vocab_terms(),
+  );
+
+  $form['save'] = array(
+    '#type' => 'submit',
+    '#value' => t('Create rule'),
+  );
+
+  return $form;
 }
 
 
 /**
- * List all of the regcode rules
- *
- * @param array $tags A key => value array of tids and terms
- * @param bool $list_all Return all rules
+ * Returns true if a rule with the given machine_name exists
  */
-function regcode_og_get_rules($tags = array(), $list_all = FALSE) {
+function regcode_og_name_exists($value) {
+  $settings = variable_get('regcode_og_settings', array());
+  return isset($settings[$value]);
+}
 
-  // Sanity check
-  if (!count($tags) && !$list_all) {
-    return array();
-  }
 
-  // Query
-  $tid_string = implode(',', array_keys($tags));
-  $query = 'SELECT id, term_data.name AS term, regcode_og.og AS ogid
-            FROM {regcode_og} AS regcode_og
-            LEFT JOIN {taxonomy_term_data} AS term_data ON {regcode_og.tid = term_data.tid}';
-  if ($list_all) {
-    $res = db_query($query);
-  }
-  else {
-    $res = db_query($query . ' WHERE term_data.tid IN (%s)', $tid_string);
-  }
+/**
+ * Form submit: Create a new rule set
+ */
+function regcode_og_create_submit($form, $form_state) {
+  $machine_name = $form_state['values']['machine_name'];
+  $settings = variable_get('regcode_og_settings', array());
+  $settings[$machine_name] = array(
+    'name' => $form_state['values']['name'],
+    'machine_name' => $form_state['values']['machine_name'],
+    'ogs' => $form_state['values']['ogs'],
+    'tid' => $form_state['values']['tid'],
+  );
+  variable_set('regcode_og_settings', $settings);
 
-  return $res->fetchAll(PDO::FETCH_ASSOC);
+  drupal_set_message(t('New og rule created'));
+  drupal_goto('admin/config/people/regcode/og');
 }
 
 
 /**
- * Create a new regcode rule
+ * List all of the rules as a HTML table
  */
-function regcode_og_create_rule($tid, $ogs) {
-  foreach ($ogs as $og) {
-    $id = db_insert('regcode_og')
-      ->fields(array(
-        'tid' => $tid,
-        'og' => $og,
-      ))
-      ->execute();
+function regcode_og_rules_page() {
+  $rules = variable_get('regcode_og_settings', array());
+  $rows  = array();
+
+  foreach ($rules as $row) {
+    $actions = array();
+    $actions[] = l('Edit', sprintf(
+      'admin/config/people/regcode/og/rule/%s', $row['machine_name']));
+    $actions[] = l('Delete', sprintf(
+      'admin/config/people/regcode/og/rule/%s/delete', $row['machine_name']));
+
+    $ognames = array();
+    foreach ($row['ogs'] as $ogid) {
+      $ognames[] = og_label($ogid);
+    }
+    $term = taxonomy_term_load($row['tid']);
+
+    $rows[] = array(
+      $row['name'],
+      implode(", ", $ognames),
+      $term->name,
+      implode(' | ', $actions),
+    );
   }
+
+  $header = array(
+    t('Name'),
+    t('Groups'),
+    t('Tag'),
+    t('Operations'),
+  );
+
+  $table = array(
+    '#theme' => 'table',
+    '#header' => $header,
+    '#rows' => $rows,
+    '#empty' => t('No rules defined. <a href="@link">Add rule</a>.', array('@link' => url('admin/config/people/regcode/og/add-rule'))),
+
+  );
+
+  return $table;
 }
 
 
@@ -195,11 +292,15 @@ function regcode_og_regcode_used(&$edit, &$account, $regcode) {
     return;
   }
 
-  // Grab applicable roles for tags used
-  $rules = regcode_og_get_rules($regcode->tags);
+  $settings = variable_get('regcode_og_settings', array());
 
   // Apply the rules
-  foreach ($rules as $rule) {
-    og_save_subscription($rule['ogid'], $account->uid, array('is_active' => 1));
+  $tags = array_keys($regcode->tags);
+  foreach ($settings as $rule) {
+    if (in_array($rule['tid'], $tags)) {
+      foreach ($rule['ogs'] as $ogid) {
+        og_group($ogid, array('entity' => $account));
+      }
+    }
   }
 }
-- 
1.7.4.1

