fixed Whitespace issue in code
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
index 81aef571076d655c6493e74f3244b99ebced784c..b2d2ed0c07d3fa9484a777209dcd973b66fc89d5 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2014                                |
+ | Copyright CiviCRM LLC (c) 2004-2015                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2014
+ * @copyright CiviCRM LLC (c) 2004-2015
  *
  */
 
@@ -46,64 +46,7 @@ class CRM_Contact_Page_AJAX {
   const AUTOCOMPLETE_TTL = 21600; // 6hr; 6*60*60
 
   /**
-   * @deprecated
-   */
-  public static function getContactList() {
-    // if context is 'customfield'
-    if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
-      return self::contactReference();
-    }
-
-    $params = array('version' => 3, 'check_permissions' => TRUE);
-
-    // String params
-    // FIXME: param keys don't match input keys, using this array to translate
-    $whitelist = array(
-      's' => 'name',
-      'fieldName' => 'field_name',
-      'tableName' => 'table_name',
-      'context' => 'context',
-      'rel' => 'rel',
-      'contact_sub_type' => 'contact_sub_type',
-      'contact_type' => 'contact_type',
-    );
-    foreach ($whitelist as $key => $param) {
-      if (!empty($_GET[$key])) {
-        $params[$param] = $_GET[$key];
-      }
-    }
-
-    //CRM-10687: Allow quicksearch by multiple fields
-    if (!empty($params['field_name'])) {
-      if ($params['field_name'] == 'phone_numeric') {
-        $params['name'] = preg_replace('/[^\d]/', '', $params['name']);
-      }
-      if (!$params['name']) {
-        CRM_Utils_System::civiExit();
-      }
-    }
-
-    // Numeric params
-    $whitelist = array(
-      'limit',
-      'org',
-      'employee_id',
-      'cid',
-      'id',
-      'cmsuser',
-    );
-    foreach ($whitelist as $key) {
-      if (!empty($_GET[$key]) && is_numeric($_GET[$key])) {
-        $params[$key] = $_GET[$key];
-      }
-    }
-
-    $result = civicrm_api('Contact', 'getquick', $params);
-    CRM_Core_Page_AJAX::autocompleteResults(CRM_Utils_Array::value('values', $result), 'data');
-  }
-
-  /**
-   * Ajax callback for custom fields of type ContactReference.
+   * Ajax callback for custom fields of type ContactReference
    *
    * Todo: Migrate contact reference fields to use EntityRef
    */
@@ -206,7 +149,7 @@ class CRM_Contact_Page_AJAX {
       $contactList[] = array('id' => $value['id'], 'text' => implode(' :: ', $view));
     }
 
-    CRM_Utils_System::civiExit(json_encode($contactList));
+    CRM_Utils_JSON::output($contactList);
   }
 
   /**
@@ -215,7 +158,7 @@ class CRM_Contact_Page_AJAX {
   public static function getPCPList() {
     $name = CRM_Utils_Array::value('term', $_GET);
     $name = CRM_Utils_Type::escape($name, 'String');
-    $limit = '10';
+    $limit = $max = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
 
     $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
 
@@ -238,8 +181,11 @@ class CRM_Contact_Page_AJAX {
       $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
     }
 
-    if (!empty($_GET['limit'])) {
-      $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
+    $offset = $count = 0;
+    if (!empty($_GET['page'])) {
+      $page = (int) $_GET['page'];
+      $offset = $limit * ($page - 1);
+      $limit++;
     }
 
     $select = 'cc.sort_name, pcp.title, cp.title';
@@ -255,23 +201,28 @@ class CRM_Contact_Page_AJAX {
             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
+        LIMIT $offset, $limit
         ";
 
     $dao = CRM_Core_DAO::executeQuery($query);
-    $results = array();
+    $output = array('results' => array(), 'more' => FALSE);
     while ($dao->fetch()) {
-      $results[] = array('id' => $dao->id, 'text' => $dao->data);
+      if (++$count > $max) {
+        $output['more'] = TRUE;
+      }
+      else {
+        $output['results'][] = array('id' => $dao->id, 'text' => $dao->data);
+      }
     }
-    CRM_Utils_JSON::output($results);
+    CRM_Utils_JSON::output($output);
   }
 
   public static function relationship() {
     $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
+    $relationshipID = CRM_Utils_Request::retrieve('rel_id', 'Positive', CRM_Core_DAO::$_nullObject); // 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
@@ -310,7 +261,7 @@ class CRM_Contact_Page_AJAX {
       }
 
       // create new or update existing relationship
-      $return = CRM_Contact_BAO_Relationship::createMultiple($relationParams, $relationIds);
+      $return = CRM_Contact_BAO_Relationship::legacyCreateMultiple($relationParams, $relationIds);
 
       if (!empty($return[4][0])) {
         $relationshipID = $return[4][0];
@@ -344,205 +295,23 @@ class CRM_Contact_Page_AJAX {
   }
 
   public static function groupTree() {
+    header('Content-Type: application/json');
     $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
     echo CRM_Contact_BAO_GroupNestingCache::json($gids);
     CRM_Utils_System::civiExit();
   }
 
-  /**
-   * @deprecated
-   * Old quicksearch function. No longer used in core.
-   * @todo: Remove this function and associated menu entry in CiviCRM 5
-   */
-  public static function search() {
-    $json = TRUE;
-    $name = CRM_Utils_Array::value('name', $_GET, '');
-    if (!array_key_exists('name', $_GET)) {
-      $name = CRM_Utils_Array::value('s', $_GET) . '%';
-      $json = FALSE;
-    }
-    $name = CRM_Utils_Type::escape($name, 'String');
-    $whereIdClause = '';
-    if (!empty($_GET['id'])) {
-      $json = TRUE;
-      if (is_numeric($_GET['id'])) {
-        $id = CRM_Utils_Type::escape($_GET['id'], 'Integer');
-        $whereIdClause = " AND civicrm_contact.id = {$id}";
-      }
-      else {
-        $name = $_GET['id'];
-      }
-    }
-
-    $elements = array();
-    if ($name || isset($id)) {
-      $name = $name . '%';
-
-      //contact's based of relationhip type
-      $relType = NULL;
-      if (isset($_GET['rel'])) {
-        $relation = explode('_', $_GET['rel']);
-        $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
-        $rel = CRM_Utils_Type::escape($relation[2], 'String');
-      }
-
-      //shared household info
-      $shared = NULL;
-      if (isset($_GET['sh'])) {
-        $shared = CRM_Utils_Type::escape($_GET['sh'], 'Integer');
-        if ($shared == 1) {
-          $contactType = 'Household';
-          $cName = 'household_name';
-        }
-        else {
-          $contactType = 'Organization';
-          $cName = 'organization_name';
-        }
-      }
-
-      // contacts of type household
-      $hh = $addStreet = $addCity = NULL;
-      if (isset($_GET['hh'])) {
-        $hh = CRM_Utils_Type::escape($_GET['hh'], 'Integer');
-      }
-
-      //organization info
-      $organization = $street = $city = NULL;
-      if (isset($_GET['org'])) {
-        $organization = CRM_Utils_Type::escape($_GET['org'], 'Integer');
-      }
-
-      if (isset($_GET['org']) || isset($_GET['hh'])) {
-        $json = FALSE;
-        $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));
-        }
-        else {
-          $contactName = $name;
-        }
-
-        if ($street) {
-          $addStreet = "AND civicrm_address.street_address LIKE '$street%'";
-        }
-        if ($city) {
-          $addCity = "AND civicrm_address.city LIKE '$city%'";
-        }
-      }
-
-      if ($organization) {
-
-        $query = "
-SELECT CONCAT_WS(' :: ',sort_name,LEFT(street_address,25),city) 'sort_name',
-civicrm_contact.id 'id'
-FROM civicrm_contact
-LEFT JOIN civicrm_address ON ( civicrm_contact.id = civicrm_address.contact_id
-                                AND civicrm_address.is_primary=1
-                             )
-WHERE civicrm_contact.contact_type='Organization' AND organization_name LIKE '%$contactName%'
-{$addStreet} {$addCity} {$whereIdClause}
-ORDER BY organization_name ";
-      }
-      elseif ($shared) {
-        $query = "
-SELECT CONCAT_WS(':::' , sort_name, supplemental_address_1, sp.abbreviation, postal_code, cc.name )'sort_name' , civicrm_contact.id 'id' , civicrm_contact.display_name 'disp' FROM civicrm_contact LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )LEFT JOIN civicrm_state_province sp ON (civicrm_address.state_province_id =sp.id )LEFT JOIN civicrm_country cc ON (civicrm_address.country_id =cc.id )WHERE civicrm_contact.contact_type ='{$contactType}' AND {$cName} LIKE '%$name%' {$whereIdClause} ORDER BY {$cName} ";
-      }
-      elseif ($hh) {
-        $query = "
-SELECT CONCAT_WS(' :: ' , sort_name, LEFT(street_address,25),city) 'sort_name' , location_type_id 'location_type_id', is_primary 'is_primary', is_billing 'is_billing', civicrm_contact.id 'id'
-FROM civicrm_contact
-LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )
-WHERE civicrm_contact.contact_type ='Household'
-AND household_name LIKE '%$contactName%' {$addStreet} {$addCity} {$whereIdClause} ORDER BY household_name ";
-      }
-      elseif ($relType) {
-        if (!empty($_GET['case'])) {
-          $query = "
-SELECT distinct(c.id), c.sort_name
-FROM civicrm_contact c
-LEFT JOIN civicrm_relationship ON civicrm_relationship.contact_id_{$rel} = c.id
-WHERE c.sort_name LIKE '%$name%'
-AND civicrm_relationship.relationship_type_id = $relType
-GROUP BY sort_name
-";
-        }
-      }
-      else {
-
-        $query = "
-SELECT sort_name, id
-FROM civicrm_contact
-WHERE sort_name LIKE '%$name'
-{$whereIdClause}
-ORDER BY sort_name ";
-      }
-
-      $limit = 10;
-      if (isset($_GET['limit'])) {
-        $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
-      }
-
-      $query .= " LIMIT 0,{$limit}";
-
-      $dao = CRM_Core_DAO::executeQuery($query);
-
-      if ($shared) {
-        while ($dao->fetch()) {
-          echo $dao->sort_name;
-          CRM_Utils_System::civiExit();
-        }
-      }
-      else {
-        while ($dao->fetch()) {
-          if ($json) {
-            $elements[] = array(
-              'name' => addslashes($dao->sort_name),
-              'id' => $dao->id,
-            );
-          }
-          else {
-            echo $elements = "$dao->sort_name|$dao->id|$dao->location_type_id|$dao->is_primary|$dao->is_billing\n";
-          }
-        }
-        //for adding new household address / organization
-        if (empty($elements) && !$json && ($hh || $organization)) {
-          echo CRM_Utils_Array::value('s', $_GET);
-        }
-      }
-    }
-
-    if (isset($_GET['sh'])) {
-      echo "";
-      CRM_Utils_System::civiExit();
-    }
-
-    if (empty($elements)) {
-      $name = str_replace('%', '', $name);
-      $elements[] = array(
-        'name' => $name,
-        'id' => $name,
-      );
-    }
-
-    if ($json) {
-      echo json_encode($elements);
-    }
-    CRM_Utils_System::civiExit();
-  }
-
   /**
    * Delete custom value.
    */
   public static function deleteCustomValue() {
+    header('Content-Type: text/plain');
     $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
     $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
-
+    $contactId = CRM_Utils_Request::retrieve('contactId', 'Positive', CRM_Core_DAO::$_nullObject);
     CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
-    $contactId = CRM_Utils_Array::value('contactId', $_REQUEST);
     if ($contactId) {
-      echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_REQUEST['groupID'], $contactId);
+      echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $customGroupID, $contactId);
     }
 
     // reset the group contact cache for this group
@@ -550,66 +319,24 @@ ORDER BY sort_name ";
     CRM_Utils_System::civiExit();
   }
 
-  /**
-   * Perform enable / disable actions on record.
-   */
-  public static function enableDisable() {
-    $op = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
-    $recordID = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
-    $recordBAO = CRM_Utils_Type::escape($_REQUEST['recordBAO'], 'String');
-
-    $isActive = NULL;
-    if ($op == 'disable-enable') {
-      $isActive = TRUE;
-    }
-    elseif ($op == 'enable-disable') {
-      $isActive = FALSE;
-    }
-    $status = array('status' => 'record-updated-fail');
-    if (isset($isActive)) {
-      // first munge and clean the recordBAO and get rid of any non alpha numeric characters
-      $recordBAO = CRM_Utils_String::munge($recordBAO);
-      $recordClass = explode('_', $recordBAO);
-
-      // make sure recordClass is namespaced (we cant check CRM since extensions can also use this)
-      // but it should be at least 3 levels deep
-      if (count($recordClass) >= 3) {
-        require_once str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php";
-        $method = 'setIsActive';
-
-        if (method_exists($recordBAO, $method)) {
-          $updated = call_user_func_array(array($recordBAO, $method),
-            array($recordID, $isActive)
-          );
-          if ($updated) {
-            $status = array('status' => 'record-updated-success');
-          }
-
-          // call hook enableDisable
-          CRM_Utils_Hook::enableDisable($recordBAO, $recordID, $isActive);
-        }
-      }
-      CRM_Utils_JSON::output($status);
-    }
-  }
-
   /**
    *  check the CMS username.
    */
   static public function checkUserName() {
     $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
+    $sig = CRM_Utils_Request::retrieve('sig', 'String', CRM_Core_DAO::$_nullObject);
+    $for = CRM_Utils_Request::retrieve('for', 'String', CRM_Core_DAO::$_nullObject);
     if (
       CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
-      || $_REQUEST['for'] != 'civicrm/ajax/cmsuser'
-      || !$signer->validate($_REQUEST['sig'], $_REQUEST)
+      || $for != 'civicrm/ajax/cmsuser'
+      || !$signer->validate($sig, $_REQUEST)
     ) {
       $user = array('name' => 'error');
-      echo json_encode($user);
-      CRM_Utils_System::civiExit();
+      CRM_Utils_JSON::output($user);
     }
 
     $config = CRM_Core_Config::singleton();
-    $username = trim($_REQUEST['cms_name']);
+    $username = trim(CRM_Utils_Type::escape($_REQUEST['cms_name'], 'String'));
 
     $params = array('name' => $username);
 
@@ -619,13 +346,15 @@ ORDER BY sort_name ";
     if (isset($errors['cms_name']) || isset($errors['name'])) {
       //user name is not availble
       $user = array('name' => 'no');
-      echo json_encode($user);
+      CRM_Utils_JSON::output($user);
     }
     else {
       //user name is available
       $user = array('name' => 'yes');
-      echo json_encode($user);
+      CRM_Utils_JSON::output($user);
     }
+
+    // Not reachable: JSON::output() above exits.
     CRM_Utils_System::civiExit();
   }
 
@@ -641,6 +370,8 @@ ORDER BY sort_name ";
       list($displayName,
         $userEmail
         ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
+
+      header('Content-Type: text/plain');
       if ($userEmail) {
         echo $userEmail;
       }
@@ -661,7 +392,7 @@ ORDER BY sort_name ";
       else {
         $cid = CRM_Utils_Array::value('cid', $_GET);
         if ($cid) {
-          //check cid for interger
+          //check cid for integer
           $contIDS = explode(',', $cid);
           foreach ($contIDS as $contID) {
             CRM_Utils_Type::escape($contID, 'Integer');
@@ -694,8 +425,8 @@ LIMIT {$offset}, {$rowCount}
           // send query to hook to be modified if needed
           CRM_Utils_Hook::contactListQuery($query,
             $name,
-            CRM_Utils_Array::value('context', $_GET),
-            CRM_Utils_Array::value('cid', $_GET)
+            CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject),
+            CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject)
           );
 
           $dao = CRM_Core_DAO::executeQuery($query);
@@ -719,8 +450,8 @@ LIMIT {$offset}, {$rowCount}
           // send query to hook to be modified if needed
           CRM_Utils_Hook::contactListQuery($query,
             $name,
-            CRM_Utils_Array::value('context', $_GET),
-            CRM_Utils_Array::value('cid', $_GET)
+            CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject),
+            CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject)
           );
 
           $dao = CRM_Core_DAO::executeQuery($query);
@@ -734,7 +465,7 @@ LIMIT {$offset}, {$rowCount}
           }
         }
         if ($result) {
-          echo json_encode($result);
+          CRM_Utils_JSON::output($result);
         }
       }
     }
@@ -790,8 +521,8 @@ LIMIT {$offset}, {$rowCount}
       // send query to hook to be modified if needed
       CRM_Utils_Hook::contactListQuery($query,
         $name,
-        CRM_Utils_Array::value('context', $_GET),
-        CRM_Utils_Array::value('cid', $_GET)
+        CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject),
+        CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject)
       );
 
       $dao = CRM_Core_DAO::executeQuery($query);
@@ -805,14 +536,14 @@ LIMIT {$offset}, {$rowCount}
     }
 
     if ($result) {
-      echo json_encode($result);
+      CRM_Utils_JSON::output($result);
     }
     CRM_Utils_System::civiExit();
   }
 
 
   public static function buildSubTypes() {
-    $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
+    $parent = CRM_Utils_Request::retrieve('parentId', 'Positive', CRM_Core_DAO::$_nullObject);
 
     switch ($parent) {
       case 1:
@@ -834,7 +565,7 @@ LIMIT {$offset}, {$rowCount}
   }
 
   public static function buildDedupeRules() {
-    $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
+    $parent = CRM_Utils_Request::retrieve('parentId', 'Positive', CRM_Core_DAO::$_nullObject);
 
     switch ($parent) {
       case 1:
@@ -983,6 +714,7 @@ LIMIT {$offset}, {$rowCount}
       }
     }
 
+    header('Content-Type: application/json');
     echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
 
     CRM_Utils_System::civiExit();
@@ -1060,7 +792,7 @@ LIMIT {$offset}, {$rowCount}
   }
 
   public static function getAddressDisplay() {
-    $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
+    $contactId = CRM_Utils_Request::retrieve('contact_id', 'Positive', CRM_Core_DAO::$_nullObject);
     if (!$contactId) {
       $addressVal["error_message"] = "no contact id found";
     }
@@ -1081,6 +813,8 @@ LIMIT {$offset}, {$rowCount}
   public static function getContactRelationships() {
     $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
     $context = CRM_Utils_Type::escape($_GET['context'], 'String');
+    $relationship_type_id = CRM_Utils_Type::escape(CRM_Utils_Array::value('relationship_type_id', $_GET), 'Integer',
+      FALSE);
 
     if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
       return CRM_Utils_System::permissionDenied();
@@ -1116,6 +850,9 @@ LIMIT {$offset}, {$rowCount}
 
     $params['contact_id'] = $contactID;
     $params['context'] = $context;
+    if ($relationship_type_id) {
+      $params['relationship_type_id'] = $relationship_type_id;
+    }
 
     // get the contact relationships
     $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
@@ -1135,6 +872,7 @@ LIMIT {$offset}, {$rowCount}
       'is_active',
     );
 
+    header('Content-Type: application/json');
     echo CRM_Utils_JSON::encodeDataTableSelector($relationships, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
     CRM_Utils_System::civiExit();
   }