Index: petition.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/petition/petition.module,v
retrieving revision 1.6
diff -u -r1.6 petition.module
--- petition.module	28 Jul 2006 19:53:04 -0000	1.6
+++ petition.module	16 Apr 2008 16:54:56 -0000
@@ -11,8 +11,6 @@
  */
 function petition_help($section) {
   switch ($section) {
-    case 'admin/modules#description':
-      return t('Enables users to create online petitions and for other users to sign it.');
 
     case 'node/add#petition':
       return t('Creates a new petition for users to sign and support.');
@@ -47,44 +45,52 @@
   $items = array();
 
   if ($may_cache) {
-    $items[] = array('title'   => t('petition'),
+    $items[] = array('title'   => t('Petition'),
                      'path'    => 'node/add/petition',
                      'access'  => user_access('create petition'),
     );
-    $items[] = array('title'    => t('petitions'),
+    $items[] = array('title'    => t('Petitions'),
                      'path'     => 'petition',
                      'callback' => 'petition_overview',
                      'access'   => user_access('respond to petition'),
     );
-    $items[] = array('title'    => t('petition statistics'),
-                     'path'     => 'admin/petition', 
+    $items[] = array('title'    => t('Petitions'),
+                     'path'     => 'admin/content/petition', 
                      'callback' => 'petition_results_overview',
+                     'description' => t('List petition data.'),
                      'access'   => user_access('access petition stats'),
     );
-    $items[] = array('title'    => t('comments'),
+    $items[] = array('title'    => t('Comments'),
                      'path'     => 'admin/petition/comments', 
                      'callback' => 'petition_results_comments',
                      'access'   => user_access('access petition stats'),
                      'type'     => MENU_CALLBACK,
     );
-    $items[] = array('title'    => t('signatories'),
+    $items[] = array('title'    => t('Signatories'),
                      'path'     => 'admin/petition/signatories', 
                      'callback' => 'petition_results_signatories',
                      'access'   => user_access('access petition stats'),
                      'type'     => MENU_CALLBACK,
     );
-    $items[] = array('title'    => t('signatories (csv)'),
+    $items[] = array('title'    => t('Signatories (csv)'),
                      'path'     => 'admin/petition/signatories/csv',
                      'callback' => 'petition_results_signatories_csv',
                      'access'   => user_access('access petition stats'),
                      'type'     => MENU_CALLBACK,
     );
-    $items[] = array('title'    => t('trending'),
+    $items[] = array('title'    => t('Trending'),
                      'path'     => 'admin/petition/trending', 
                      'callback' => 'petition_results_trending',
                      'access'   => user_access('access petition stats'),
                      'type'     => MENU_CALLBACK,
     );
+    $items[] = array('title' => t('Petition settings'),
+                     'path' => 'admin/settings/petition',
+                     'callback' => 'drupal_get_form',
+                     'callback arguments' => array('petition_admin_settings'),
+                     'description' => t('Configure petition settings.'),
+                     'access' => user_access('administer site configuration'),
+    );
   }
 
   return $items;
@@ -94,7 +100,13 @@
  * Implementation of hook_node_info().
  */
 function petition_node_info() {
-  return array('petition' => array('name' => t('petition'), 'base' => 'petition'));
+  return array(
+    'petition' => array(
+      'name' => t('Petition'), 
+      'module' => 'petition',
+      'description' => t('An online petition that users can sign.'),
+    )
+  );
 }
 
 /**
@@ -116,8 +128,6 @@
  * Implementation of hook_form().
  */
 function petition_form(&$node) {
-  civicrm_initialize(TRUE);
-
   $form['title'] = array(
     '#type'          => 'textfield',
     '#title'         => t('Title'),
@@ -177,9 +187,13 @@
 
   // emails enabled, so allow message customization.
   if (variable_get('petition_default_autorespond', 1)) {
-    $profile_fields = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1)));
-    $wildcards = array('%petition_title'); // we'll use the node->title here when it comes time.
-    foreach ($profile_fields as $key => $value) { $wildcards[] = "%$key"; }
+    if (module_exists('civicrm')) {
+      civicrm_initialize();
+      require_once('api/UFGroup.php');
+      $profile_fields = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1)));
+    }
+    $wildcards = array('@petition_title'); // we'll use the node->title here when it comes time.
+    foreach ($profile_fields as $key => $value) { $wildcards[] = "@$key"; }
     $wildcards = implode(', ', $wildcards); // for #description display.
 
     $form['defaultibles']['autorespond_from'] = array(
@@ -244,11 +258,47 @@
  * Implementation of hook_view().
  */
 function petition_view(&$node, $teaser = FALSE, $page = FALSE) {
-  civicrm_initialize(TRUE);
+  global $user;
+  $signed = FALSE;
+ 
+  if ($user->uid) {
+    if (module_exists('civicrm')) {
+      civicrm_initialize();
+      require_once('api/v2/Contact.php');
+      $options = array('email' => $user->mail);
+      $contact = civicrm_contact_get($options);
+    }
+    $signatory = db_result(db_query("SELECT cid FROM {petition_signatories} WHERE pid = %d AND cid = %d", $node->nid, $contact['contact_id']));
+    if (!empty($signatory)) {
+      $signed = TRUE;
+    }
+  }
 
+  $node = node_prepare($node, $teaser);
+  if ($signed) {
+    $node->petition_signup_form = t('You have already signed this petition.');
+  }
+  else {
+    $node->petition_signup_form = drupal_get_form('petition_signup_form_data', $node);
+  }
+  $node->appeal = check_markup($node->appeal, $node->format, FALSE);
+  $node->personal = $node->personal ? check_markup($node->personal, $node->format, FALSE) : NULL;
+  $node->content['body'] = array(
+    '#value' => theme('petition_view', $node),
+    '#weight' => 0,
+  );
+  return $node;
+}
+
+function petition_signup_form_data($node) {
   // generate the signup form. forms only support textfields.
   $profile_id = variable_get('petition_profile', 1);
-  $fields     = crm_uf_get_profile_fields($profile_id, true);
+  $fields = array();
+  if (module_exists('civicrm')) {
+    civicrm_initialize();
+    require_once('api/UFGroup.php');
+    $fields = crm_uf_get_profile_fields($profile_id, true);
+  }
   foreach ($fields as $row) {
     if ($row['where'] == 'civicrm_state_province.name' || $row['where'] == 'civicrm_country.name') {
       $country_options = $row['is_required'] ? CRM_Core_PseudoConstant::country() : array('' => '<'.t('none').'>') + CRM_Core_PseudoConstant::country();
@@ -270,18 +320,51 @@
       );
     }
   }
+  if (is_null($form['email'])) {
+    $form['email'] = array(
+      '#type'     => 'textfield',
+      '#title'    => t('Email'),
+      '#required' => TRUE,
+    );
+  }
   $form['comment'] = array(
     '#type'     => 'textarea',
     '#title'    => t('Your comment to leaders and the press')
   );
   $form['pid']     = array( '#type' => 'hidden', '#value' => $node->nid, );
   $form['submit']  = array( '#type' => 'submit', '#value' => t('Submit'), );
-  $node->petition_signup_form = drupal_get_form('petition_signup_form_data', $form);
-  $node->body = check_markup($node->body, $node->format, FALSE);
-  $node->teaser = check_markup($node->teaser, $node->format, FALSE);
-  $node->appeal = check_markup($node->appeal, $node->format, FALSE);
-  $node->personal = $node->personal ? check_markup($node->personal, $node->format, FALSE) : NULL;
-  $node->body = theme('petition_view', $node);
+  return $form;
+}
+
+/*
+ * Validate petition signup.
+ */
+function petition_signup_form_data_validate($form_id, $form_values) {
+  global $user;
+
+  if (!$user->uid) {
+    // Don't allow anonymous users to sign if the email has an associated Drupal account.
+    $email = db_result(db_query("SELECT mail FROM {users} WHERE mail = '%s'", $form_values['email']));
+    if (!empty($email)) {
+      form_set_error('email', 'There is a Drupal account associated with that email address.  Please '. l(t('log in'), 'user/login', array(), 'destination=node/'. $form_values['pid']) .' to sign the petition.'); 
+    }
+  
+    // Don't allow anonymous users to sign the petition twice with the same email address.
+    $crm_fields    = array('email' => $form_values['email']);
+    if (module_exists('civicrm')) {
+      civicrm_initialize();
+      require_once('api/v2/Contact.php');
+      $contact_check = civicrm_contact_search($crm_fields, array('email'));
+    }
+    if (count($contact_check[0]) > 0) {
+      $cid = array_shift($contact_check[0]);
+      $cid = $cid['contact_id'];
+    }
+    $signatory = db_result(db_query("SELECT cid FROM {petition_signatories} WHERE pid = %d AND cid = %d", $form_values['pid'], $cid));
+    if (!empty($signatory)) {
+      form_set_error('email', 'Someone has already signed this petition with that email address.');
+    }
+  }
 }
 
 /**
@@ -290,7 +373,6 @@
  * indicating he or she signed the petition.
  */
 function petition_signup_form_data_submit($form_id, $form_values) {
-  civicrm_initialize(TRUE);
   $node = node_load($form_values['pid']);
   $cid = 0; // if existing user, it'll be their cid.
 
@@ -301,7 +383,15 @@
   // based on email. @todo someday, this should be user configurable or,
   // better yet, hook into CiviCRM's duplication checks.
   $crm_fields    = array('email' => $form_values['email']);
-  $contact_check = crm_contact_search($crm_fields, array('email'));
+  if (module_exists('civicrm')) {
+    civicrm_initialize();
+    require_once('api/v2/Contact.php');
+    require_once('api/v2/Activity.php');
+    require_once('api/v2/Group.php');
+    require_once('api/v2/GroupContact.php');
+    require_once('api/UFGroup.php');
+    $contact_check = civicrm_contact_search($crm_fields, array('email'));
+  }
 
   // contact_search returns an array of matches.
   // need to make sure we only found one person.
@@ -314,13 +404,15 @@
   if ($cid == 0) {
     $form_values['country_id']        = isset($form_values['country']) ? $form_values['country'] : NULL;
     $form_values['state_province_id'] = isset($form_values['state_province']) ? $form_values['state_province'] : NULL;
-    $new = crm_create_contact($form_values, 'Individual');
+    $form_values['contact_type'] = 'Individual';
+    $new = civicrm_contact_add($form_values);
     $cid = $new->id;
   }
 
   // load the full user object, which now exists regardless
   // of whether the user existed already, or is brand new.
-  $contact = crm_get_contact(array('contact_id' => $cid));
+  $options = array('contact_id' => $cid);
+  $contact = civicrm_contact_get($options);
   $contact->contact_id = $contact->id;
 
   // add this contact to a group, if enabled.
@@ -328,22 +420,23 @@
     $groups = variable_get('petition_group', array());
     foreach ($groups as $group) {
       $contacts_to_add = array($contact);
-      $thisgroup = crm_get_groups(array('id' => $group));
-      crm_add_group_contacts($thisgroup[0], $contacts_to_add);
+      $options = array('id' => $group);
+      $thisgroup = civicrm_groups_get($options);
+      civicrm_group_contact_add($thisgroup[0], $contacts_to_add);
     }
   }
 
   // insert activity record.
-  $activity_params = array(
-    'entity_table'     => 'civicrm_contact',
-    'entity_id'        => $cid,
-    'activity_type'    => t('Signed Petition: %title', array('%title' => $node->title)),
-    'module'           => t('Petition'),
-    'activity_id'      => $node->nid,
-    'activity_summary' => t('This contact signed the %title petition.', array('%title' => $node->title)),
-    'activity_date'    => date('YmdHis')
-  );
-  crm_create_activity_history($activity_params);
+//  $activity_params = array(
+//    'entity_table'     => 'civicrm_contact',
+//    'entity_id'        => $cid,
+//    'activity_type'    => t('Signed Petition: %title', array('%title' => $node->title)),
+//    'module'           => t('Petition'),
+//    'activity_id'      => $node->nid,
+//    'activity_summary' => t('This contact signed the %title petition.', array('%title' => $node->title)),
+//    'activity_date'    => date('YmdHis')
+//  );
+//  crm_create_activity_history($activity_params);
 
   // record the contact id, petition id, and any comments.
   petition_register_signatory($node->nid, $cid, $form_values['comment']);
@@ -352,15 +445,14 @@
   if (variable_get('petition_default_autorespond', 1) && $form_values['email']) { 
     $wildcards = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1)));
     foreach ($wildcards as $key => $field) {
-      $wildcards["%$key"] = $form_values[$key];
+      $wildcards["@$key"] = $form_values[$key];
       unset($wildcards[$key]);
     }
-    $wildcards['%petition_title'] = $node->title;
+    $wildcards['@petition_title'] = $node->title;
     $from    = $node->autorespond_from ? $node->autorespond_from : variable_get('site_mail', ini_get('sendmail_from'));
     $subject = $node->autorespond_subject ? $node->autorespond_subject : variable_get('petition_default_autorespond_subject', t('Thanks for signing %petition_title'));
     $message = $node->autorespond_message ? $node->autorespond_message : variable_get('petition_default_autorespond_message', t('Thanks for signing this petition, %first_name!'));
-    $headers = "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from";
-    user_mail($form_values['email'], t($subject, $wildcards), t($message, $wildcards), $headers);
+    drupal_mail('petition_mail', $form_values['email'], t($subject, $wildcards), t($message, $wildcards), $from);
   }
 
   // and send 'em along home, danno.
@@ -383,7 +475,7 @@
  * Displays the entire petition to the user.
  */
 function theme_petition_view($node) {
-  theme_add_style(drupal_get_path('module', 'petition').'/petition.css');
+  drupal_add_css(drupal_get_path('module', 'petition') .'/petition.css');
   $output  = '<div id="petition">';
 
   if ($node->statistics) {
@@ -438,9 +530,7 @@
 /**
  * Implementation of hook_settings().
  */
-function petition_settings() {
-  civicrm_initialize(true);
-
+function petition_admin_settings() {
   $form['petition'] = array(
     '#type'          => 'fieldset',
     '#title'         => t('Default Settings'),
@@ -460,21 +550,26 @@
   );
 
   // wildcards, like %thing, can be used to customize the email autoresponse.
-  $profile_fields = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1)));
-  $wildcards = array('%petition_title'); // we'll use the node->title here when it comes time.
-  foreach ($profile_fields as $key => $value) { $wildcards[] = "%$key"; }
+  if (module_exists('civicrm')) {
+    civicrm_initialize();
+    require_once('api/UFGroup.php');
+    require_once('api/v2/Group.php');
+    $profile_fields = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1)));
+  }
+  $wildcards = array('@petition_title'); // we'll use the node->title here when it comes time.
+  foreach ($profile_fields as $key => $value) { $wildcards[] = "@$key"; }
   $wildcards = implode(', ', $wildcards); // for #description display.
 
   $form['petition']['petition_default_autorespond_subject'] = array(
     '#type'          => 'textfield',
     '#title'         => t('Default Email Auto-Respond Subject'),
-    '#default_value' => variable_get('petition_default_autorespond_subject', t('Thanks for signing %petition_title')),
+    '#default_value' => variable_get('petition_default_autorespond_subject', t('Thanks for signing @petition_title')),
     '#description'   => t('Subject of auto-response email message to be sent. You may include the following wildcards: %wild.', array('%wild' => $wildcards)),
   );
   $form['petition']['petition_default_autorespond_message'] = array(
     '#type'          => 'textarea',
     '#title'         => t('Default Email Auto-Respond Message'),
-    '#default_value' => variable_get('petition_default_autorespond_message', t('Thanks for signing this petition, %first_name!')),
+    '#default_value' => variable_get('petition_default_autorespond_message', t('Thanks for signing this petition, @first_name!')),
     '#description'   => t('Body of auto-response email message to be sent. You may include the following wildcards: %wild.', array('%wild' => $wildcards)),
   );
 
@@ -494,7 +589,8 @@
 
   // Build select for groups.
   $group_options = array();
-  $groups = crm_get_groups();
+  $options = array();
+  $groups = civicrm_groups_get($options);
   $i = 0; while ($i < count($groups) ) {
     $group_options[$groups[$i]->id] = $groups[$i]->name;
     ++$i;
@@ -522,7 +618,7 @@
     '#description'   => t('Select the CiviCRM profile for petition signers to use.'),
   );
 
-  return $form;
+  return system_settings_form($form);
 }
 
 /**
@@ -575,11 +671,14 @@
  * Signatories for a specific petition.
  */
 function petition_results_signatories($pid = NULL) {
-  civicrm_initialize(true);
   $node = node_load($pid);
-
-  // return a list of fields used in the petition signup form.
-  $profile_fields = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1)));
+  if (module_exists('civicrm')) {
+    civicrm_initialize();
+    require_once('api/UFGroup.php');
+    require_once('api/v2/Contact.php');
+    // return a list of fields used in the petition signup form.
+    $profile_fields = _petition_adjust_fields(crm_uf_get_profile_fields(variable_get('petition_profile', 1), false, CRM_CORE_ACTION_VIEW));
+  }
 
   // set up headers for the table.
   $return_properties = array();
@@ -594,7 +693,7 @@
   while ($result = db_fetch_object($results)) {
     $row = array(); // for this row only.
     $search_params  = array('id' => $result->cid);
-    $match = array_shift(crm_contact_search($search_params, $return_properties));
+    $match = array_shift(civicrm_contact_search($search_params, $return_properties));
     $row[] = l($result->cid, "civicrm/contact/view", NULL, 'cid='.$result->cid);
     foreach ($return_properties as $key => $value) {
       $row[] = $match[$result->cid][$key];
@@ -613,7 +712,6 @@
  * Displays a trending report.
  */
 function petition_results_trending($pid = NULL) {
-  civicrm_initialize(true);
 
   $rows    = array();
   $headers = array(t('Week Starting'), t('Signatures'), t('Trend'));
@@ -642,7 +740,7 @@
  *
  */
 function theme_petition_trend($trend = 'pos', $data) {
-  theme_add_style(drupal_get_path('module', 'petition').'/petition.css');
+  drupal_add_css(drupal_get_path('module', 'petition') .'/petition.css');
   $output = ($trend == 'pos')
     ? '<span class="trend_positive">'
     : '<span class="trend_negative">';
@@ -668,13 +766,17 @@
  */
 function petition_results_signatories_csv($arg1) {
   $sort = $_GET;
-  civicrm_initialize(true);
   $petition = node_load($arg1);
-
-  // return a list of fields used in the petition signup form
-  // turn the fields into headers on the form
-  $dat = crm_uf_get_profile_fields ( variable_get('petition_profile', 1) );
-   $dat =  _petition_adjust_fields($dat);
+  
+  if (module_exists('civicrm')) {
+    civicrm_initialize();
+    require_once('api/UFGroup.php');
+    require_once('api/v2/Contact.php');
+    // return a list of fields used in the petition signup form
+    // turn the fields into headers on the form
+    $dat = crm_uf_get_profile_fields ( variable_get('petition_profile', 1), false, CRM_CORE_ACTION_VIEW );
+  }
+  $dat =  _petition_adjust_fields($dat);
  
   // set up headers for the table
   // and fields for the CRM contact search
@@ -684,23 +786,25 @@
   }
   $header[] = t('Contact ID');
   $header[] = t('Date Signed');
+  $header[] = t('Comment');
   $headers = $header;
 
   $rows = array();
 
-  $sql = db_query(db_rewrite_sql("SELECT DISTINCT(cid), created FROM {petition_signatories} WHERE pid = %d ORDER BY created"), $arg1);
+  $sql = db_query(db_rewrite_sql("SELECT DISTINCT(cid), created, comment FROM {petition_signatories} WHERE pid = %d ORDER BY created"), $arg1);
 
   while($row = db_fetch_object($sql)){
     
     $con_data = array();
     $params = array( 'id' => $row->cid );
     $return_properties = array( "sort_name"=>1, "email"=>1 );
-    $result = crm_contact_search( $params, $fields );
+    $result = civicrm_contact_search( $params, $fields );
     foreach($fields as $key => $value){
       $signer[$key] = $result[0][$row->cid][$key];
     }
     $signer['cid'] = $row->cid;
-    $signer['created'] = $row->created;
+    $signer['created'] = format_date($row->created);
+    $signer['comment'] = $row->comment;
     $rows[] = $signer;
   }
   
