Merge remote-tracking branch 'origin/4.4' into 4.4-4.5-2014-09-14-13-58-42
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
index ddf9e41ed5e4e27425daf1efda2d760f9b8f4c50..242eb75c83902708c841284a853153466b2c1688 100644 (file)
@@ -1,9 +1,9 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 4.4                                                |
+ | CiviCRM version 4.5                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2013                                |
+ | Copyright CiviCRM LLC (c) 2004-2014                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2013
+ * @copyright CiviCRM LLC (c) 2004-2014
  *
  */
 
@@ -45,6 +45,9 @@ class CRM_Contact_Page_AJAX {
 
   const AUTOCOMPLETE_TTL = 21600; // 6hr; 6*60*60
 
+  /**
+   * @deprecated
+   */
   static function getContactList() {
     // if context is 'customfield'
     if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
@@ -61,7 +64,8 @@ class CRM_Contact_Page_AJAX {
       'tableName' => 'table_name',
       'context' => 'context',
       'rel' => 'rel',
-      'contact_sub_type' => 'contact_sub_type'
+      'contact_sub_type' => 'contact_sub_type',
+      'contact_type' => 'contact_type'
     );
     foreach ($whitelist as $key => $param) {
       if (!empty($_GET[$key])) {
@@ -95,27 +99,26 @@ class CRM_Contact_Page_AJAX {
     }
 
     $result = civicrm_api('Contact', 'getquick', $params);
-    if (empty($result['is_error']) && !empty($result['values'])) {
-      foreach ($result['values'] as $key => $val) {
-        echo "{$val['data']}|{$val['id']}\n";
-      }
-    }
-    CRM_Utils_System::civiExit();
+    CRM_Core_Page_AJAX::autocompleteResults(CRM_Utils_Array::value('values', $result), 'data');
   }
 
+  /**
+   * Ajax callback for custom fields of type ContactReference
+   *
+   * Todo: Migrate contact reference fields to use EntityRef
+   */
   static function contactReference() {
-    $name = CRM_Utils_Array::value('s', $_GET);
+    $name = CRM_Utils_Array::value('term', $_GET);
     $name = CRM_Utils_Type::escape($name, 'String');
     $cfID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
 
     // check that this is a valid, active custom field of Contact Reference type
-    $params           = array('id' => $cfID);
+    $params = array('id' => $cfID);
     $returnProperties = array('filter', 'data_type', 'is_active');
-    $fldValues = $cf = array();
+    $cf = array();
     CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
-    if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] = !'ContactReference') {
-      echo "$name|error\n";
-      CRM_Utils_System::civiExit();
+    if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] != 'ContactReference') {
+      CRM_Utils_System::civiExit('error');
     }
 
     if (!empty($cf['filter'])) {
@@ -127,8 +130,7 @@ class CRM_Contact_Page_AJAX {
       if (!empty($action) &&
         !in_array($action, array('get', 'lookup'))
       ) {
-        echo "$name|error\n";
-        CRM_Utils_System::civiExit();
+        CRM_Utils_System::civiExit('error');
       }
     }
 
@@ -138,12 +140,7 @@ class CRM_Contact_Page_AJAX {
 
     $return = array_unique(array_merge(array('sort_name'), $list));
 
-    $config = CRM_Core_Config::singleton();
-
-    $limit = 10;
-    if (CRM_Utils_Array::value('limit', $_GET)) {
-      $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
-    }
+    $limit = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
 
     $params = array('offset' => 0, 'rowCount' => $limit, 'version' => 3);
     foreach ($return as $fld) {
@@ -180,27 +177,22 @@ class CRM_Contact_Page_AJAX {
 
     $contact = civicrm_api('Contact', 'Get', $params);
 
-    if (CRM_Utils_Array::value('is_error', $contact)) {
-      echo "$name|error\n";
-      CRM_Utils_System::civiExit();
+    if (!empty($contact['is_error'])) {
+      CRM_Utils_System::civiExit('error');
     }
 
-    $contactList = '';
+    $contactList = array();
     foreach ($contact['values'] as $value) {
       $view = array();
       foreach ($return as $fld) {
-        if (CRM_Utils_Array::value($fld, $value)) {
+        if (!empty($value[$fld])) {
           $view[] = $value[$fld];
         }
       }
-      echo $contactList = implode(' :: ', $view) . "|" . $value['id'] . "\n";
-    }
-
-    if (!$contactList) {
-      echo "$name|$name\n";
+      $contactList[] = array('id' => $value['id'], 'text' => implode(' :: ', $view));
     }
 
-    CRM_Utils_System::civiExit();
+    CRM_Utils_System::civiExit(json_encode($contactList));
   }
 
   /**
@@ -232,7 +224,7 @@ class CRM_Contact_Page_AJAX {
       $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
     }
 
-    if (CRM_Utils_Array::value('limit', $_GET)) {
+    if (!empty($_GET['limit'])) {
       $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
     }
 
@@ -243,53 +235,30 @@ class CRM_Contact_Page_AJAX {
             SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
             FROM civicrm_pcp pcp, civicrm_contribution_page cp, civicrm_contact cc
             {$includeEmailFrom}
-            {$whereClause}
+            {$whereClause} AND pcp.page_type = 'contribute'
+            UNION ALL
+            SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
+            FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
+            {$includeEmailFrom}
+            {$whereClause} AND pcp.page_type = 'event'
             LIMIT 0, {$limit}
             ) t
         ORDER BY sort_name
         ";
 
     $dao = CRM_Core_DAO::executeQuery($query);
-
+    $results = array();
     while ($dao->fetch()) {
-      echo $pcpList = "$dao->data|$dao->id\n";
+      $results[] = array('id' => $dao->id, 'text' => $dao->data);
     }
-
-    CRM_Utils_System::civiExit();
-  }
-
-  /**
-   * Function to fetch the values
-   */
-  static function autocomplete() {
-    $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('cfid', 'ogid', 'sigts'));
-    if (CRM_Utils_Time::getTimeRaw() > $_REQUEST['sigts'] + self::AUTOCOMPLETE_TTL
-      || !$signer->validate($_REQUEST['sig'], $_REQUEST)
-    ) {
-      CRM_Utils_System::civiExit();
-    }
-
-    $fieldID       = CRM_Utils_Type::escape($_GET['cfid'], 'Integer');
-    $optionGroupID = CRM_Utils_Type::escape($_GET['ogid'], 'Integer');
-    $label         = CRM_Utils_Type::escape($_GET['s'], 'String');
-
-    $selectOption = CRM_Core_BAO_CustomOption::valuesByID($fieldID, $optionGroupID);
-
-    $completeList = NULL;
-    foreach ($selectOption as $id => $value) {
-      if (strtolower($label) == strtolower(substr($value, 0, strlen($label)))) {
-        echo $completeList = "$value|$id\n";
-      }
-    }
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($results);
   }
 
   static function relationship() {
-    $relType         = CRM_Utils_Array::value('rel_type', $_REQUEST);
-    $relContactID    = CRM_Utils_Array::value('rel_contact', $_REQUEST);
-    $sourceContactID = CRM_Utils_Array::value('contact_id', $_REQUEST); // we no longer need this.
-    $relationshipID  = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode
-    $caseID          = CRM_Utils_Array::value('case_id', $_REQUEST);
+    $relType = CRM_Utils_Request::retrieve('rel_type', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
+    $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
+    $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode
+    $caseID = CRM_Utils_Request::retrieve('case_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
 
     // check if there are multiple clients for this case, if so then we need create
     // relationship and also activities for each contacts
@@ -297,6 +266,8 @@ class CRM_Contact_Page_AJAX {
     // get case client list
     $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
 
+    $ret = array('is_error' => 0);
+
     foreach($clientList as $sourceContactID) {
       $relationParams = array(
         'relationship_type_id' => $relType . '_a_b',
@@ -327,19 +298,22 @@ class CRM_Contact_Page_AJAX {
       // create new or update existing relationship
       $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
 
-      $status = 'process-relationship-fail';
-      if (CRM_Utils_Array::value(0, $return[4])) {
+      if (!empty($return[4][0])) {
         $relationshipID = $return[4][0];
-        $status = 'process-relationship-success';
 
         //create an activity for case role assignment.CRM-4480
         CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID);
       }
+      else {
+        $ret = array(
+          'is_error' => 1,
+          'error_message' => ts('The relationship type definition for the case role is not valid for the client and / or staff contact types. You can review and edit relationship types at <a href="%1">Administer >> Option Lists >> Relationship Types</a>.',
+            array(1 => CRM_Utils_System::url('civicrm/admin/reltype', 'reset=1')))
+        );
+      }
     }
 
-    $relation['status'] = $status;
-    echo json_encode($relation);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($ret);
   }
 
   /**
@@ -352,8 +326,7 @@ class CRM_Contact_Page_AJAX {
     $values           = array();
 
     CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
-    echo json_encode($values);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($values);
   }
 
   static function groupTree() {
@@ -363,7 +336,9 @@ class CRM_Contact_Page_AJAX {
   }
 
   /**
-   * Function for building contact combo box
+   * @deprecated
+   * Old quicksearch function. No longer used in core.
+   * @todo: Remove this function and associated menu entry in CiviCRM 5
    */
   static function search() {
     $json = TRUE;
@@ -374,7 +349,7 @@ class CRM_Contact_Page_AJAX {
     }
     $name = CRM_Utils_Type::escape($name, 'String');
     $whereIdClause = '';
-    if (CRM_Utils_Array::value('id', $_GET)) {
+    if (!empty($_GET['id'])) {
       $json = TRUE;
       if (is_numeric($_GET['id'])) {
         $id = CRM_Utils_Type::escape($_GET['id'], 'Integer');
@@ -425,7 +400,8 @@ class CRM_Contact_Page_AJAX {
 
       if (isset($_GET['org']) || isset($_GET['hh'])) {
         $json = FALSE;
-        if ($splitName = explode(' :: ', $name)) {
+        $splitName = explode(' :: ', $name);
+        if ($splitName) {
           $contactName = trim(CRM_Utils_Array::value('0', $splitName));
           $street      = trim(CRM_Utils_Array::value('1', $splitName));
           $city        = trim(CRM_Utils_Array::value('2', $splitName));
@@ -468,7 +444,7 @@ WHERE civicrm_contact.contact_type ='Household'
 AND household_name LIKE '%$contactName%' {$addStreet} {$addCity} {$whereIdClause} ORDER BY household_name ";
       }
       elseif ($relType) {
-        if (CRM_Utils_Array::value('case', $_GET)) {
+        if (!empty($_GET['case'])) {
           $query = "
 SELECT distinct(c.id), c.sort_name
 FROM civicrm_contact c
@@ -541,28 +517,6 @@ ORDER BY sort_name ";
     CRM_Utils_System::civiExit();
   }
 
-  /**
-   *
-   * Function to check how many contact exits in db for given criteria,
-   * if one then return contact id else null
-   */
-  static function contact() {
-    $name = CRM_Utils_Type::escape($_GET['name'], 'String');
-
-    $query = "
-SELECT id
-FROM civicrm_contact
-WHERE sort_name LIKE '%$name%'";
-
-    $dao = CRM_Core_DAO::executeQuery($query);
-    $dao->fetch();
-
-    if ($dao->N == 1) {
-      echo $dao->id;
-    }
-    CRM_Utils_System::civiExit();
-  }
-
   /**
    * Function to delete custom value
    *
@@ -572,7 +526,8 @@ WHERE sort_name LIKE '%$name%'";
     $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
 
     CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
-    if ($contactId = CRM_Utils_Array::value('contactId', $_REQUEST)) {
+    $contactId = CRM_Utils_Array::value('contactId', $_REQUEST);
+    if ($contactId) {
       echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_REQUEST['groupID'], $contactId);
     }
 
@@ -621,8 +576,7 @@ WHERE sort_name LIKE '%$name%'";
           CRM_Utils_Hook::enableDisable($recordBAO, $recordID, $isActive);
         }
       }
-      echo json_encode($status);
-      CRM_Utils_System::civiExit();
+      CRM_Utils_JSON::output($status);
     }
   }
 
@@ -667,7 +621,7 @@ WHERE sort_name LIKE '%$name%'";
    *  Function to get email address of a contact
    */
   static function getContactEmail() {
-    if (CRM_Utils_Array::value('contact_id', $_REQUEST)) {
+    if (!empty($_REQUEST['contact_id'])) {
       $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
       if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
         return;
@@ -682,7 +636,8 @@ WHERE sort_name LIKE '%$name%'";
     else {
       $noemail = CRM_Utils_Array::value('noemail', $_GET);
       $queryString = NULL;
-      if ($name = CRM_Utils_Array::value('name', $_GET)) {
+      $name = CRM_Utils_Array::value('name', $_GET);
+      if ($name) {
         $name = CRM_Utils_Type::escape($name, 'String');
         if ($noemail) {
           $queryString = " cc.sort_name LIKE '%$name%'";
@@ -691,21 +646,23 @@ WHERE sort_name LIKE '%$name%'";
           $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
         }
       }
-      elseif ($cid = CRM_Utils_Array::value('cid', $_GET)) {
-        //check cid for interger
-        $contIDS = explode(',', $cid);
-        foreach ($contIDS as $contID) {
-          CRM_Utils_Type::escape($contID, 'Integer');
-        }
-        $queryString = " cc.id IN ( $cid )";
+      else {
+       $cid = CRM_Utils_Array::value('cid', $_GET);
+       if ($cid) {
+          //check cid for interger
+          $contIDS = explode(',', $cid);
+          foreach ($contIDS as $contID) {
+            CRM_Utils_Type::escape($contID, 'Integer');
+          }
+          $queryString = " cc.id IN ( $cid )";
+       }
       }
 
       if ($queryString) {
         $offset = CRM_Utils_Array::value('offset', $_GET, 0);
-        $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
+        $rowCount = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
 
         $offset = CRM_Utils_Type::escape($offset, 'Int');
-        $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
 
         // add acl clause here
         list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
@@ -732,8 +689,8 @@ LIMIT {$offset}, {$rowCount}
           $dao = CRM_Core_DAO::executeQuery($query);
           while ($dao->fetch()) {
             $result[] = array(
-              'name' => $dao->name,
               'id' => $dao->id,
+              'text' => $dao->name,
             );
           }
         }
@@ -758,13 +715,13 @@ LIMIT {$offset}, {$rowCount}
           $dao = CRM_Core_DAO::executeQuery($query);
 
           while ($dao->fetch()) {
+              //working here
             $result[] = array(
-              'name' => '"' . $dao->name . '" &lt;' . $dao->email . '&gt;',
+              'text' => '"' . $dao->name . '" <' . $dao->email . '>',
               'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
             );
           }
         }
-
         if ($result) {
           echo json_encode($result);
         }
@@ -780,17 +737,21 @@ LIMIT {$offset}, {$rowCount}
     $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
     $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
 
-    if ($name = CRM_Utils_Array::value('name', $_GET)) {
+    $name = CRM_Utils_Array::value('name', $_GET);
+    if ($name) {
       $name = CRM_Utils_Type::escape($name, 'String');
       $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
     }
-    elseif ($cid = CRM_Utils_Array::value('cid', $_GET)) {
-      //check cid for interger
-      $contIDS = explode(',', $cid);
-      foreach ($contIDS as $contID) {
-        CRM_Utils_Type::escape($contID, 'Integer');
+    else {
+       $cid = CRM_Utils_Array::value('cid', $_GET);
+       if ($cid) {
+        //check cid for interger
+        $contIDS = explode(',', $cid);
+        foreach ($contIDS as $contID) {
+          CRM_Utils_Type::escape($contID, 'Integer');
+        }
+        $queryString = " cc.id IN ( $cid )";
       }
-      $queryString = " cc.id IN ( $cid )";
     }
 
     if ($queryString) {
@@ -826,7 +787,7 @@ LIMIT {$offset}, {$rowCount}
 
       while ($dao->fetch()) {
         $result[] = array(
-          'name' => '"' . $dao->name . '" &lt;' . $dao->phone . '&gt;',
+          'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
           'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
         );
       }
@@ -858,8 +819,7 @@ LIMIT {$offset}, {$rowCount}
 
     $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
     asort($subTypes);
-    echo json_encode($subTypes);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($subTypes);
   }
 
   static function buildDedupeRules() {
@@ -881,8 +841,7 @@ LIMIT {$offset}, {$rowCount}
 
     $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
 
-    echo json_encode($dedupeRules);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($dedupeRules);
   }
 
   /**
@@ -914,8 +873,7 @@ LIMIT {$offset}, {$rowCount}
         CRM_Utils_System::civiExit();
     }
 
-    echo json_encode($dashlets);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($dashlets);
   }
 
   /**
@@ -934,116 +892,7 @@ LIMIT {$offset}, {$rowCount}
       );
     }
 
-    echo json_encode($signatures);
-    CRM_Utils_System::civiExit();
-  }
-
-  static function relationshipContacts() {
-    $searchValues = $searchRows = array();
-    $addCount = 0;
-
-    $relType          = CRM_Utils_Type::escape($_REQUEST['relType'], 'String');
-    $typeName         = isset($_REQUEST['typeName']) ? CRM_Utils_Type::escape($_REQUEST['typeName'], 'String') : '';
-    $relContact       = CRM_Utils_Type::escape($_REQUEST['relContact'], 'String');
-    $currentContactId = CRM_Utils_Type::escape($_REQUEST['cid'], 'Integer');
-
-    if (in_array($typeName, array(
-      'Employee of', 'Employer of'))) {
-      $addCount = 1;
-    }
-
-    $sortMapper = array(
-      1 => 'sort_name', (2 + $addCount) => 'city', (3 + $addCount) => 'state_province',
-      (4 + $addCount) => 'email', (5 + $addCount) => 'phone',
-    );
-
-    $sEcho     = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
-    $offset    = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
-    $rowCount  = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
-    $sort      = isset($_REQUEST['iSortCol_0']) ? $sortMapper[CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer')] : 'sort_name';
-    $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
-
-    $searchValues[] = array('sort_name', 'LIKE', $relContact, 0, 1);
-
-    list($rid, $direction) = explode('_', $relType, 2);
-
-    $relationshipType = new CRM_Contact_DAO_RelationshipType();
-
-    $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;
-      }
-
-      if ($type == 'Individual' || $type == 'Organization' || $type == 'Household') {
-        $searchValues[] = array('contact_type', '=', $type, 0, 0);
-      }
-
-      if ($subType) {
-        $searchValues[] = array('contact_sub_type', '=', $subType, 0, 0);
-      }
-    }
-
-    // exclude current contact
-    $searchValues[] = array('contact_id', '!=', $currentContactId, 0, 0);
-
-    $query       = new CRM_Contact_BAO_Query($searchValues);
-    $searchCount = $query->searchQuery(0, 0, NULL, TRUE);
-    $iTotal      = $searchCount;
-
-    if ($searchCount > 0) {
-      // get the result of the search
-      $result = $query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE,
-        FALSE, FALSE, FALSE, NULL, $sortOrder
-      );
-
-      $config = CRM_Core_Config::singleton();
-
-      while ($result->fetch()) {
-        $query->convertToPseudoNames($result);
-        $contactID = $result->contact_id;
-        $typeImage = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ?
-          $result->contact_sub_type : $result->contact_type,
-          FALSE, $contactID
-        );
-
-        $searchRows[$contactID]['id'] = $contactID;
-        $searchRows[$contactID]['name'] = $typeImage . ' ' . $result->sort_name;
-        $searchRows[$contactID]['city'] = $result->city;
-        $searchRows[$contactID]['state'] = $result->state_province;
-        $searchRows[$contactID]['email'] = $result->email;
-        $searchRows[$contactID]['phone'] = $result->phone;
-      }
-    }
-
-    foreach ($searchRows as $cid => $row) {
-      $searchRows[$cid]['check'] = '<input type="checkbox" id="contact_check[' . $cid . ']" name="contact_check[' . $cid . ']" value=' . $cid . ' />';
-
-      if ($typeName == 'Employee of') {
-        $searchRows[$cid]['employee_of'] = '<input type="radio" name="employee_of" value=' . $cid . ' >';
-      }
-      elseif ($typeName == 'Employer of') {
-        $searchRows[$cid]['employer_of'] = '<input type="checkbox"  name="employer_of[' . $cid . ']" value=' . $cid . ' />';
-      }
-    }
-
-    $selectorElements = array('check', 'name');
-    if ($typeName == 'Employee of') {
-      $selectorElements[] = 'employee_of';
-    }
-    elseif ($typeName == 'Employer of') {
-      $selectorElements[] = 'employer_of';
-    }
-    $selectorElements = array_merge($selectorElements, array('city', 'state', 'email', 'phone'));
-
-    $iFilteredTotal = $iTotal;
-    echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($signatures);
   }
 
   /**
@@ -1076,8 +925,7 @@ LIMIT {$offset}, {$rowCount}
       $status = $exception->delete();
     }
 
-    echo json_encode(array('status' => ($status) ? $oper : $status));
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
   }
 
   static function getDedupes() {
@@ -1112,7 +960,7 @@ LIMIT {$offset}, {$rowCount}
       $searchRows[$mainId]['dst'] = CRM_Utils_System::href($main['dstName'], 'civicrm/contact/view', "reset=1&cid={$main['dstID']}");
       $searchRows[$mainId]['weight'] = CRM_Utils_Array::value('weight', $main);
 
-      if (CRM_Utils_Array::value('canMerge', $main)) {
+      if (!empty($main['canMerge'])) {
         $mergeParams = "reset=1&cid={$main['srcID']}&oid={$main['dstID']}&action=update&rgid={$rgid}";
         if ($gid) {
           $mergeParams .= "&gid={$gid}";
@@ -1139,8 +987,7 @@ LIMIT {$offset}, {$rowCount}
 
     $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
 
-    echo json_encode($pdfFormat);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($pdfFormat);
   }
 
   /**
@@ -1151,25 +998,7 @@ LIMIT {$offset}, {$rowCount}
 
     $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
 
-    echo json_encode($paperSize);
-    CRM_Utils_System::civiExit();
-  }
-
-  static function relationshipContactTypeList() {
-    $relType = CRM_Utils_Array::value('relType', $_REQUEST);
-
-    $types = CRM_Contact_BAO_Relationship::getValidContactTypeList($relType);
-
-    $elements = array();
-    foreach ($types as $key => $label) {
-      $elements[] = array(
-        'name' => $label,
-        'value' => $key,
-      );
-    }
-
-    echo json_encode($elements);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($paperSize);
   }
 
   static function selectUnselectContacts() {
@@ -1203,10 +1032,14 @@ LIMIT {$offset}, {$rowCount}
     $countSelectionCids = count($contactIds[$cacheKey]);
 
     $arrRet = array('getCount' => $countSelectionCids);
-    echo json_encode($arrRet);
-    CRM_Utils_System::civiExit();
+    CRM_Utils_JSON::output($arrRet);
   }
 
+  /**
+   * @param $name
+   *
+   * @return string
+   */
   static function _convertToId($name) {
     if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
       $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
@@ -1228,7 +1061,66 @@ LIMIT {$offset}, {$rowCount}
       $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
     }
 
-    echo json_encode($addressVal);
+    CRM_Utils_JSON::output($addressVal);
+  }
+
+  /**
+   * Function to retrieve contact relationships
+   */
+  public static function getContactRelationships() {
+    $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
+    $context = CRM_Utils_Type::escape($_GET['context'], 'String');
+
+    $sortMapper = array(
+      0 => 'relation',
+      1 => 'sort_name',
+      2 => 'start_date',
+      3 => 'end_date',
+      4 => 'city',
+      5 => 'state',
+      6 => 'email',
+      7 => 'phone',
+      8 => 'links',
+      9 => '',
+      10 => '',
+    );
+
+    $sEcho     = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
+    $offset    = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
+    $rowCount  = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
+    $sort      = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
+    $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
+
+    $params = $_POST;
+    if ($sort && $sortOrder) {
+      $params['sortBy'] = $sort . ' ' . $sortOrder;
+    }
+
+    $params['page'] = ($offset / $rowCount) + 1;
+    $params['rp'] = $rowCount;
+
+    $params['contact_id'] = $contactID;
+    $params['context'] = $context;
+
+    // get the contact relationships
+    $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
+
+    $iFilteredTotal = $iTotal = $params['total'];
+    $selectorElements = array(
+      'relation',
+      'name',
+      'start_date',
+      'end_date',
+      'city',
+      'state',
+      'email',
+      'phone',
+      'links',
+      'id',
+      'is_active',
+    );
+
+    echo CRM_Utils_JSON::encodeDataTableSelector($relationships, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
     CRM_Utils_System::civiExit();
   }
 }