CRM-16055 fix tasks
authorEileen McNaughton <eileen@fuzion.co.nz>
Mon, 16 Mar 2015 10:35:46 +0000 (23:35 +1300)
committerEileen McNaughton <eileen@fuzion.co.nz>
Mon, 16 Mar 2015 12:35:33 +0000 (01:35 +1300)
These appear to be the only 2 places in the whole codebase calling relationship:add - this function no longer
accepts the same parameters so the tasks have bee re-written to call createMultiple

CRM/Contact/BAO/Relationship.php
CRM/Contact/Form/Task/AddToHousehold.php
CRM/Contact/Form/Task/AddToOrganization.php
CRM/Contact/Form/Task/AddToParentClass.php [new file with mode: 0644]

index 0e9fc92037aa493de35455569a3c9630ecb0063f..fbe2b7294183434a52979c218824ed838df1c517 100644 (file)
@@ -1324,7 +1324,7 @@ LEFT JOIN  civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
    * @return array
    *   array reference of all relationship types with context to current contact type .
    */
-  public function getRelationType($targetContactType) {
+  static public function getRelationType($targetContactType) {
     $relationshipType = array();
     $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
 
@@ -1457,12 +1457,14 @@ LEFT JOIN  civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
 
     // done with 'values' array.
     // Finally add / edit / delete memberships for the related contacts
+
     foreach ($values as $cid => $details) {
       if (!array_key_exists('memberships', $details)) {
         continue;
       }
 
-      $mainRelatedContactId = key(CRM_Utils_Array::value('relatedContacts', $details, array()));
+      $relatedContacts = CRM_Utils_Array::value('relatedContacts', $details, array());
+      $mainRelatedContactId = reset($relatedContacts);
 
       foreach ($details['memberships'] as $membershipId => $membershipValues) {
         $relTypeIds = array();
index 2773a44b69a09001f295e6711132543b4b7e66e6..ee2444a696f1a8f816333c64b103d5b7a1581280 100644 (file)
  */
 
 /**
- *
- * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2014
- * $Id$
- *
+ * This class provides the functionality to add contact(s) to Household.
  */
-
-/**
- * This class provides the functionality to add contact(s) to Household
- */
-class CRM_Contact_Form_Task_AddToHousehold extends CRM_Contact_Form_Task {
+class CRM_Contact_Form_Task_AddToHousehold extends CRM_Contact_Form_Task_AddToParentClass {
 
   /**
    * Build the form object.
-   *
-   *
-   * @return void
-   */
-  public function preProcess() {
-    // initialize the task and row fields
-    parent::preProcess();
-  }
-
-  /**
-   * Build the form object.
-   *
-   *
-   * @return void
    */
   public function buildQuickForm() {
 
@@ -71,16 +49,16 @@ class CRM_Contact_Form_Task_AddToHousehold extends CRM_Contact_Form_Task {
     $searchCount = $this->get('searchCount');
     if ($searchRows) {
       $checkBoxes = array();
-      $chekFlag = 0;
+      $checkFlag = 0;
       foreach ($searchRows as $id => $row) {
-        if (!$chekFlag) {
-          $chekFlag = $id;
+        if (!$checkFlag) {
+          $checkFlag = $id;
         }
         $checkBoxes[$id] = $this->createElement('radio', NULL, NULL, NULL, $id);
       }
       $this->addGroup($checkBoxes, 'contact_check');
-      if ($chekFlag) {
-        $checkBoxes[$chekFlag]->setChecked(TRUE);
+      if ($checkFlag) {
+        $checkBoxes[$checkFlag]->setChecked(TRUE);
       }
       $this->assign('searchRows', $searchRows);
     }
@@ -107,196 +85,22 @@ class CRM_Contact_Form_Task_AddToHousehold extends CRM_Contact_Form_Task {
 
   /**
    * Process the form after the input has been submitted and validated.
-   *
-   *
-   * @return void
    */
   public function postProcess() {
 
     // store the submitted values in an array
-    $params = $this->controller->exportValues($this->_name);
+    $this->params = $this->controller->exportValues($this->_name);
 
     $this->set('searchDone', 0);
     if (!empty($_POST['_qf_AddToHousehold_refresh'])) {
       $searchParams['contact_type'] = array('Household' => 'Household');
-      $searchParams['rel_contact'] = $params['name'];
-      self::search($this, $searchParams);
+      $searchParams['rel_contact'] = $this->params['name'];
+      $this->search($this, $searchParams);
       $this->set('searchDone', 1);
       return;
     }
 
-    $data = array();
-    //$params['relationship_type_id']='4_a_b';
-    $data['relationship_type_id'] = $params['relationship_type_id'];
-    $data['is_active'] = 1;
-    $invalid = $valid = $duplicate = 0;
-    if (is_array($this->_contactIds)) {
-      foreach ($this->_contactIds as $value) {
-        $ids = array();
-        $ids['contact'] = $value;
-        //contact b --> household
-        // contact a  -> individual
-        $errors = CRM_Contact_BAO_Relationship::checkValidRelationship($params, $ids, $params['contact_check']);
-        if ($errors) {
-          $invalid++;
-          continue;
-        }
-
-        if (CRM_Contact_BAO_Relationship::checkDuplicateRelationship($params,
-          CRM_Utils_Array::value('contact', $ids),
-          // step 2
-          $params['contact_check']
-        )
-        ) {
-          $duplicate++;
-          continue;
-        }
-        CRM_Contact_BAO_Relationship::add($data, $ids, $params['contact_check']);
-        $valid++;
-      }
-
-      $house = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['contact_check'], 'display_name');
-      list($rtype, $a_b) = explode('_', $data['relationship_type_id'], 2);
-      $relationship = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $rtype, "label_$a_b");
-
-      $status = array(
-        ts('%count %2 %3 relationship created', array(
-            'count' => $valid,
-            'plural' => '%count %2 %3 relationships created',
-            2 => $relationship,
-            3 => $house,
-        )),
-      );
-      if ($duplicate) {
-        $status[] = ts('%count was skipped because the contact is already %2 %3', array(
-            'count' => $duplicate,
-            'plural' => '%count were skipped because the contacts are already %2 %3',
-            2 => $relationship,
-            3 => $house,
-          ));
-      }
-      if ($invalid) {
-        $status[] = ts('%count relationship was not created because the contact is not of the right type for this relationship', array(
-            'count' => $invalid,
-            'plural' => '%count relationships were not created because the contact is not of the right type for this relationship',
-          ));
-      }
-      $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
-      CRM_Core_Session::setStatus($status, ts('Relationship created.', array(
-            'count' => $valid,
-            'plural' => 'Relationships created.',
-          )), 'success', array('expires' => 0));
-    }
-  }
-
-  /**
-   * get the result of the search for Add to * forms
-   *
-   * @param CRM_Core_Form $form
-   * @param array $params
-   *   This contains elements for search criteria.
-   *
-   *
-   * @return void
-   */
-  public function search(&$form, &$params) {
-    //max records that will be listed
-    $searchValues = array();
-    if (!empty($params['rel_contact'])) {
-      if (isset($params['rel_contact_id']) &&
-        is_numeric($params['rel_contact_id'])
-      ) {
-        $searchValues[] = array('contact_id', '=', $params['rel_contact_id'], 0, 1);
-      }
-      else {
-        $searchValues[] = array('sort_name', 'LIKE', $params['rel_contact'], 0, 1);
-      }
-    }
-    $contactTypeAdded = FALSE;
-
-    $excludedContactIds = array();
-    if (isset($form->_contactId)) {
-      $excludedContactIds[] = $form->_contactId;
-    }
-
-    if (!empty($params['relationship_type_id'])) {
-      $relationshipType = new CRM_Contact_DAO_RelationshipType();
-      list($rid, $direction) = explode('_', $params['relationship_type_id'], 2);
-
-      $relationshipType->id = $rid;
-      if ($relationshipType->find(TRUE)) {
-        if ($direction == 'a_b') {
-          $type = $relationshipType->contact_type_b;
-          $subType = $relationshipType->contact_sub_type_b;
-        }
-        else {
-          $type = $relationshipType->contact_type_a;
-          $subType = $relationshipType->contact_sub_type_a;
-        }
-
-        $form->set('contact_type', $type);
-        $form->set('contact_sub_type', $subType);
-        if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') {
-          $searchValues[] = array('contact_type', '=', $type, 0, 0);
-          $contactTypeAdded = TRUE;
-        }
-
-        if ($subType) {
-          $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0);
-        }
-      }
-    }
-
-    if (!$contactTypeAdded && !empty($params['contact_type'])) {
-      $searchValues[] = array('contact_type', '=', $params['contact_type'], 0, 0);
-    }
-
-    // get the count of contact
-    $contactBAO = new CRM_Contact_BAO_Contact();
-    $query = new CRM_Contact_BAO_Query($searchValues);
-    $searchCount = $query->searchQuery(0, 0, NULL, TRUE);
-    $form->set('searchCount', $searchCount);
-    if ($searchCount <= 50) {
-      // get the result of the search
-      $result = $query->searchQuery(0, 50, NULL);
-
-      $config = CRM_Core_Config::singleton();
-      $searchRows = array();
-
-      //variable is set if only one record is foun and that record already has relationship with the contact
-      $duplicateRelationship = 0;
-
-      while ($result->fetch()) {
-        $query->convertToPseudoNames($result);
-        $contactID = $result->contact_id;
-        if (in_array($contactID, $excludedContactIds)) {
-          $duplicateRelationship++;
-          continue;
-        }
-
-        $duplicateRelationship = 0;
-
-        $searchRows[$contactID]['id'] = $contactID;
-        $searchRows[$contactID]['name'] = $result->sort_name;
-        $searchRows[$contactID]['city'] = $result->city;
-        $searchRows[$contactID]['state'] = $result->state_province;
-        $searchRows[$contactID]['email'] = $result->email;
-        $searchRows[$contactID]['phone'] = $result->phone;
-
-        $contact_type = '<img src="' . $config->resourceBase . 'i/contact_';
-
-        $searchRows[$contactID]['type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type
-        );
-      }
-
-      $form->set('searchRows', $searchRows);
-      $form->set('duplicateRelationship', $duplicateRelationship);
-    }
-    else {
-      // resetting the session variables if many records are found
-      $form->set('searchRows', NULL);
-      $form->set('duplicateRelationship', NULL);
-    }
+    $this->addRelationships();
   }
 
 }
index 8614654664abbc053826b40e680ef10782a7ea74..08064e7b0a75701701b736fd9c853cc9cfcfc5b8 100644 (file)
 /**
  * This class provides the functionality to add contact(s) to Organization
  */
-class CRM_Contact_Form_Task_AddToOrganization extends CRM_Contact_Form_Task {
+class CRM_Contact_Form_Task_AddToOrganization extends CRM_Contact_Form_Task_AddToParentClass {
 
   /**
    * Build the form object.
-   *
-   *
-   * @return void
-   */
-  public function preProcess() {
-    // initialize the task and row fields
-    parent::preProcess();
-  }
-
-  /**
-   * Build the form object.
-   *
-   *
-   * @return void
    */
   public function buildQuickForm() {
     CRM_Utils_System::setTitle(ts('Add Contacts to Organization'));
@@ -110,83 +96,21 @@ class CRM_Contact_Form_Task_AddToOrganization extends CRM_Contact_Form_Task {
 
   /**
    * Process the form after the input has been submitted and validated.
-   *
-   *
-   * @return void
    */
   public function postProcess() {
     // store the submitted values in an array
-    $params = $this->controller->exportValues($this->_name);
+    $this->params = $this->controller->exportValues($this->_name);
 
     $this->set('searchDone', 0);
     if (!empty($_POST['_qf_AddToOrganization_refresh'])) {
       $searchParams['contact_type'] = array('Organization' => 'Organization');
-      $searchParams['rel_contact'] = $params['name'];
-      CRM_Contact_Form_Task_AddToHousehold::search($this, $searchParams);
+      $searchParams['rel_contact'] = $this->params['name'];
+      $this->search($this, $searchParams);
       $this->set('searchDone', 1);
       return;
     }
 
-    $data = array();
-    $data['relationship_type_id'] = $params['relationship_type_id'];
-    $data['is_active'] = 1;
-    $invalid = 0;
-    $valid = 0;
-    $duplicate = 0;
-    if (is_array($this->_contactIds)) {
-      foreach ($this->_contactIds as $value) {
-        $ids = array();
-        $ids['contact'] = $value;
-        $errors = CRM_Contact_BAO_Relationship::checkValidRelationship($params, $ids, $params['contact_check']);
-        if ($errors) {
-          $invalid++;
-          continue;
-        }
-
-        if (CRM_Contact_BAO_Relationship::checkDuplicateRelationship($params,
-          CRM_Utils_Array::value('contact', $ids),
-          // step 2
-          $params['contact_check']
-        )
-        ) {
-          $duplicate++;
-          continue;
-        }
-        CRM_Contact_BAO_Relationship::add($data, $ids, $params['contact_check']);
-        $valid++;
-      }
-      $org = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['contact_check'], 'display_name');
-      list($rtype, $a_b) = explode('_', $data['relationship_type_id'], 2);
-      $relationship = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $rtype, "label_$a_b");
-
-      $status = array(
-        ts('%count %2 %3 relationship created', array(
-            'count' => $valid,
-            'plural' => '%count %2 %3 relationships created',
-            2 => $relationship,
-            3 => $org,
-          )),
-      );
-      if ($duplicate) {
-        $status[] = ts('%count was skipped because the contact is already %2 %3', array(
-            'count' => $duplicate,
-            'plural' => '%count were skipped because the contacts are already %2 %3',
-            2 => $relationship,
-            3 => $org,
-          ));
-      }
-      if ($invalid) {
-        $status[] = ts('%count relationship was not created because the contact is not of the right type for this relationship', array(
-            'count' => $invalid,
-            'plural' => '%count relationships were not created because the contact is not of the right type for this relationship',
-          ));
-      }
-      $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
-      CRM_Core_Session::setStatus($status, ts('Relationship created.', array(
-            'count' => $valid,
-            'plural' => 'Relationships created.',
-          )), 'success', array('expires' => 0));
-    }
+    $this->addRelationships();
   }
 
 }
diff --git a/CRM/Contact/Form/Task/AddToParentClass.php b/CRM/Contact/Form/Task/AddToParentClass.php
new file mode 100644 (file)
index 0000000..f2c1e6d
--- /dev/null
@@ -0,0 +1,216 @@
+<?php
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.6                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2014                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+ */
+
+/**
+ * This class provides the shared functionality for addToHousehold and addToOrganization.
+ */
+class CRM_Contact_Form_Task_AddToParentClass extends CRM_Contact_Form_Task {
+
+  /**
+   * Exported parameters from the form.
+   *
+   * @var array.
+   */
+  protected $params;
+
+  /**
+   * Build the form object.
+   */
+  public function preProcess() {
+    parent::preProcess();
+  }
+
+  /**
+   * Add relationships from form.
+   */
+  public function addRelationships() {
+
+    if (!is_array($this->_contactIds)) {
+      // Could this really happen?
+      return;
+    }
+    $relationshipTypeParts = explode('_', $this->params['relationship_type_id']);
+    $params = array(
+      'relationship_type_id' => $relationshipTypeParts[0],
+      'is_active' => 1,
+    );
+    $secondaryRelationshipSide = $relationshipTypeParts[1];
+    $primaryRelationshipSide = $relationshipTypeParts[2];
+    $primaryFieldName = 'contact_id_' . $primaryRelationshipSide;
+    $secondaryFieldName = 'contact_id_' . $secondaryRelationshipSide;
+
+
+    $relationshipLabel = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
+      $params['relationship_type_id'], "label_{$secondaryRelationshipSide}_{$primaryRelationshipSide}");
+
+
+    $params[$secondaryFieldName] = $this->_contactIds;
+    $params[$primaryFieldName] = $this->params['contact_check'];
+    $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $primaryRelationshipSide);
+
+    $relatedContactName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$primaryFieldName],
+      'display_name');
+
+    $status = array(
+      ts('%count %2 %3 relationship created', array(
+        'count' => $outcome['valid'],
+        'plural' => '%count %2 %3 relationships created',
+        2 => $relationshipLabel,
+        3 => $relatedContactName,
+      )),
+    );
+    if ($outcome['duplicate']) {
+      $status[] = ts('%count was skipped because the contact is already %2 %3', array(
+        'count' => $outcome['duplicate'],
+        'plural' => '%count were skipped because the contacts are already %2 %3',
+        2 => $relationshipLabel,
+        3 => $relatedContactName,
+      ));
+    }
+    if ($outcome['invalid']) {
+      $status[] = ts('%count relationship was not created because the contact is not of the right type for this relationship', array(
+        'count' => $outcome['invalid'],
+        'plural' => '%count relationships were not created because the contact is not of the right type for this relationship',
+      ));
+    }
+    $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
+    CRM_Core_Session::setStatus($status, ts('Relationship created.', array(
+      'count' => $outcome['valid'],
+      'plural' => 'Relationships created.',
+    )), 'success', array('expires' => 0));
+
+
+  }
+
+  /**
+   * Get the result of the search for Add to * forms.
+   *
+   * @param CRM_Core_Form $form
+   * @param array $params
+   *   This contains elements for search criteria.
+   */
+  public function search(&$form, &$params) {
+    //max records that will be listed
+    $searchValues = array();
+    if (!empty($params['rel_contact'])) {
+      if (isset($params['rel_contact_id']) &&
+        is_numeric($params['rel_contact_id'])
+      ) {
+        $searchValues[] = array('contact_id', '=', $params['rel_contact_id'], 0, 1);
+      }
+      else {
+        $searchValues[] = array('sort_name', 'LIKE', $params['rel_contact'], 0, 1);
+      }
+    }
+    $contactTypeAdded = FALSE;
+
+    $excludedContactIds = array();
+    if (isset($form->_contactId)) {
+      $excludedContactIds[] = $form->_contactId;
+    }
+
+    if (!empty($params['relationship_type_id'])) {
+      $relationshipType = new CRM_Contact_DAO_RelationshipType();
+      list($rid, $direction) = explode('_', $params['relationship_type_id'], 2);
+
+      $relationshipType->id = $rid;
+      if ($relationshipType->find(TRUE)) {
+        if ($direction == 'a_b') {
+          $type = $relationshipType->contact_type_b;
+          $subType = $relationshipType->contact_sub_type_b;
+        }
+        else {
+          $type = $relationshipType->contact_type_a;
+          $subType = $relationshipType->contact_sub_type_a;
+        }
+
+        $form->set('contact_type', $type);
+        $form->set('contact_sub_type', $subType);
+        if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') {
+          $searchValues[] = array('contact_type', '=', $type, 0, 0);
+          $contactTypeAdded = TRUE;
+        }
+
+        if ($subType) {
+          $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0);
+        }
+      }
+    }
+
+    if (!$contactTypeAdded && !empty($params['contact_type'])) {
+      $searchValues[] = array('contact_type', '=', $params['contact_type'], 0, 0);
+    }
+
+    // get the count of contact
+    $contactBAO = new CRM_Contact_BAO_Contact();
+    $query = new CRM_Contact_BAO_Query($searchValues);
+    $searchCount = $query->searchQuery(0, 0, NULL, TRUE);
+    $form->set('searchCount', $searchCount);
+    if ($searchCount <= 50) {
+      // get the result of the search
+      $result = $query->searchQuery(0, 50, NULL);
+
+      $config = CRM_Core_Config::singleton();
+      $searchRows = array();
+
+      //variable is set if only one record is foun and that record already has relationship with the contact
+      $duplicateRelationship = 0;
+
+      while ($result->fetch()) {
+        $query->convertToPseudoNames($result);
+        $contactID = $result->contact_id;
+        if (in_array($contactID, $excludedContactIds)) {
+          $duplicateRelationship++;
+          continue;
+        }
+
+        $duplicateRelationship = 0;
+
+        $searchRows[$contactID]['id'] = $contactID;
+        $searchRows[$contactID]['name'] = $result->sort_name;
+        $searchRows[$contactID]['city'] = $result->city;
+        $searchRows[$contactID]['state'] = $result->state_province;
+        $searchRows[$contactID]['email'] = $result->email;
+        $searchRows[$contactID]['phone'] = $result->phone;
+
+        $contact_type = '<img src="' . $config->resourceBase . 'i/contact_';
+
+        $searchRows[$contactID]['type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type
+        );
+      }
+
+      $form->set('searchRows', $searchRows);
+      $form->set('duplicateRelationship', $duplicateRelationship);
+    }
+    else {
+      // resetting the session variables if many records are found
+      $form->set('searchRows', NULL);
+      $form->set('duplicateRelationship', NULL);
+    }
+  }
+
+}