Merge pull request #8157 from eileenmcnaughton/CRM-18424
[civicrm-core.git] / CRM / Core / Page / AJAX.php
index 95fc8566deb2085b7197d02b2a846871c807fbb6..84185152f1767ade3fe74edfb0a573b2c6636067 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 4.7                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015                                |
+ | Copyright CiviCRM LLC (c) 2004-2016                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
+ * @copyright CiviCRM LLC (c) 2004-2016
  * $Id$
  *
  */
@@ -214,4 +214,53 @@ class CRM_Core_Page_AJAX {
     CRM_Utils_System::setHttpHeader('Cache-Control', "max-age=$ttl, public");
   }
 
+  public static function defaultSortAndPagerParams($defaultOffset = 0, $defaultRowCount = 25, $defaultSort = NULL, $defaultsortOrder = 'asc') {
+    $params = array(
+      '_raw_values' => array(),
+    );
+
+    $sortMapper = array();
+    if (isset($_GET['columns'])) {
+      foreach ($_GET['columns'] as $key => $value) {
+        $sortMapper[$key] = CRM_Utils_Type::validate($value['data'], 'MysqlColumnName');
+      };
+    }
+
+    $offset = isset($_GET['start']) ? CRM_Utils_Type::validate($_GET['start'], 'Integer') : $defaultOffset;
+    $rowCount = isset($_GET['length']) ? CRM_Utils_Type::validate($_GET['length'], 'Integer') : $defaultRowCount;
+    // Why is the number of order by columns limited to 1?
+    $sort = isset($_GET['order'][0]['column']) ? CRM_Utils_Array::value(CRM_Utils_Type::validate($_GET['order'][0]['column'], 'Integer'), $sortMapper) : $defaultSort;
+    $sortOrder = isset($_GET['order'][0]['dir']) ? CRM_Utils_Type::validate($_GET['order'][0]['dir'], 'MysqlOrderByDirection') : $defaultsortOrder;
+
+    if ($sort) {
+      $params['sortBy'] = "{$sort} {$sortOrder}";
+
+      $params['_raw_values']['sort'][0] = $sort;
+      $params['_raw_values']['order'][0] = $sortOrder;
+    }
+
+    $params['offset'] = $offset;
+    $params['rp'] = $rowCount;
+    $params['page'] = ($offset / $rowCount) + 1;
+
+    return $params;
+  }
+
+  public static function validateParams($requiredParams = array(), $optionalParams = array()) {
+    $params = array();
+
+    foreach ($requiredParams as $param => $type) {
+      $params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type);
+    }
+
+    foreach ($optionalParams as $param => $type) {
+      if (CRM_Utils_Array::value($param, $_GET)) {
+        $params[$param] = CRM_Utils_Type::validate(CRM_Utils_Array::value($param, $_GET), $type);
+      }
+    }
+
+    return $params;
+
+  }
+
 }