3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Class CRM_Utils_Weight
31 class CRM_Utils_Weight
{
33 * @var array, list of GET fields which must be validated
35 * To reduce the size of this patch, we only sign the exploitable fields
36 * which make up "$baseURL" in addOrder() (eg 'filter' or 'dao').
37 * Less-exploitable fields (eg 'dir') are left unsigned.
39 static $SIGNABLE_FIELDS = array('reset', 'dao', 'idName', 'url', 'filter'); // 'id','src','dst','dir'
42 * Function to correct duplicate weight entries by putting them (duplicate weights) in sequence.
44 * @param string $daoName full name of the DAO
45 * @param array $fieldValues field => value to be used in the WHERE
46 * @param string $weightField field which contains the weight value,
47 * defaults to 'weight'
51 static function correctDuplicateWeights($daoName, $fieldValues = NULL, $weightField = 'weight') {
52 $selectField = "MIN(id) AS dupeId, count(id) as dupeCount, $weightField as dupeWeight";
53 $groupBy = "$weightField having dupeCount>1";
55 $minDupeID = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField, NULL, NULL, $groupBy);
57 // return early if query returned empty
59 if (!$minDupeID->fetch()) {
63 if ($minDupeID->dupeId
) {
64 $additionalWhere = "id !=" . $minDupeID->dupeId
. " AND $weightField >= " . $minDupeID->dupeWeight
;
65 $update = "$weightField = $weightField + 1";
66 $status = CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
69 if ($minDupeID->dupeId
&& $status) {
70 //recursive call to correct all duplicate weight entries.
71 return CRM_Utils_Weight
::correctDuplicateWeights($daoName, $fieldValues, $weightField);
73 elseif (!$minDupeID->dupeId
) {
74 // case when no duplicate records are found.
78 // case when duplicate records are found but update status is false.
84 * Remove a row from the specified weight, and shift all rows below it up
86 * @param string $daoName full name of the DAO
87 * $param integer $weight the weight to be removed
89 * @param array $fieldValues field => value to be used in the WHERE
90 * @param string $weightField field which contains the weight value,
91 * defaults to 'weight'
95 static function delWeight($daoName, $fieldID, $fieldValues = NULL, $weightField = 'weight') {
96 $object = new $daoName();
97 $object->id
= $fieldID;
98 if (!$object->find(TRUE)) {
102 $weight = (int)$object->weight
;
108 $additionalWhere = "$weightField > $weight";
109 $update = "$weightField = $weightField - 1";
110 $status = CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
116 * Updates the weight fields of other rows according to the new and old weight passed in.
117 * And returns the new weight be used. If old-weight not present, Creates a gap for a new row to be inserted
118 * at the specified new weight
120 * @param string $daoName full name of the DAO
121 * @param integer $oldWeight
122 * @param integer $newWeight
123 * @param array $fieldValues field => value to be used in the WHERE
124 * @param string $weightField field which contains the weight value,
125 * defaults to 'weight'
129 static function updateOtherWeights($daoName, $oldWeight, $newWeight, $fieldValues = NULL, $weightField = 'weight') {
130 $oldWeight = (int ) $oldWeight;
131 $newWeight = (int ) $newWeight;
133 // max weight is the highest current weight
134 $maxWeight = CRM_Utils_Weight
::getMax($daoName, $fieldValues, $weightField);
139 if ($newWeight > $maxWeight) {
140 //calculate new weight, CRM-4133
141 $calNewWeight = CRM_Utils_Weight
::getNewWeight($daoName, $fieldValues, $weightField);
143 //no need to update weight for other fields.
144 if ($calNewWeight > $maxWeight) {
145 return $calNewWeight;
147 $newWeight = $maxWeight;
150 return $newWeight +
1;
153 elseif ($newWeight < 1) {
157 // if they're the same, nothing to do
158 if ($oldWeight == $newWeight) {
162 // if oldWeight not present, indicates new weight is to be added. So create a gap for a new row to be inserted.
164 $additionalWhere = "$weightField >= $newWeight";
165 $update = "$weightField = ($weightField + 1)";
166 CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
170 if ($newWeight > $oldWeight) {
171 $additionalWhere = "$weightField > $oldWeight AND $weightField <= $newWeight";
172 $update = "$weightField = ($weightField - 1)";
174 elseif ($newWeight < $oldWeight) {
175 $additionalWhere = "$weightField >= $newWeight AND $weightField < $oldWeight";
176 $update = "$weightField = ($weightField + 1)";
178 CRM_Utils_Weight
::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere);
184 * returns the new calculated weight.
186 * @param string $daoName full name of the DAO
187 * @param array $fieldValues field => value to be used in the WHERE
188 * @param string $weightField field which used to get the wt, default to 'weight'.
192 static function getNewWeight($daoName, $fieldValues = NULL, $weightField = 'weight') {
193 $selectField = "id AS fieldID, $weightField AS weight";
194 $field = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField);
195 $sameWeightCount = 0;
197 while ($field->fetch()) {
198 if (in_array($field->weight
, $weights)) {
201 $weights[$field->fieldID
] = $field->weight
;
205 if ($sameWeightCount) {
206 $newWeight = max($weights) +
1;
208 //check for max wt should not greater than cal max wt.
209 $calMaxWt = min($weights) +
count($weights) - 1;
210 if ($newWeight > $calMaxWt) {
211 $newWeight = $calMaxWt;
214 elseif (!empty($weights)) {
215 $newWeight = max($weights);
222 * returns the highest weight.
224 * @param string $daoName full name of the DAO
225 * @param array $fieldValues field => value to be used in the WHERE
226 * @param string $weightField field which contains the weight value,
227 * defaults to 'weight'
231 static function getMax($daoName, $fieldValues = NULL, $weightField = 'weight') {
232 $selectField = "MAX(ROUND($weightField)) AS max_weight";
233 $weightDAO = CRM_Utils_Weight
::query('SELECT', $daoName, $fieldValues, $selectField);
235 if ($weightDAO->max_weight
) {
236 return $weightDAO->max_weight
;
242 * returns the default weight ( highest weight + 1 ) to be used.
244 * @param string $daoName full name of the DAO
245 * @param array $fieldValues field => value to be used in the WHERE
246 * @param string $weightField field which contains the weight value,
247 * defaults to 'weight'
251 static function getDefaultWeight($daoName, $fieldValues = NULL, $weightField = 'weight') {
252 $maxWeight = CRM_Utils_Weight
::getMax($daoName, $fieldValues, $weightField);
253 return $maxWeight +
1;
257 * Execute a weight-related query
259 * @param string $queryType SELECT, UPDATE, DELETE
260 * @param string $daoName full name of the DAO
261 * @param array $fieldValues field => value to be used in the WHERE
262 * @param string $queryData data to be used, dependent on the query type
263 * @param null $additionalWhere
264 * @param string $orderBy optional ORDER BY field
266 * @param null $groupBy
268 * @return Object CRM_Core_DAO objet that holds the results of the query
270 static function &query($queryType,
274 $additionalWhere = NULL,
279 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
282 $table = $dao->getTablename();
283 $fields = &$dao->fields();
284 $fieldlist = array_keys($fields);
286 $whereConditions = array();
287 if ($additionalWhere) {
288 $whereConditions[] = $additionalWhere;
292 if (is_array($fieldValues)) {
293 foreach ($fieldValues as $fieldName => $value) {
294 if (!in_array($fieldName, $fieldlist)) {
295 // invalid field specified. abort.
299 $whereConditions[] = "$fieldName = %$fieldNum";
300 $fieldType = $fields[$fieldName]['type'];
301 $params[$fieldNum] = array($value, CRM_Utils_Type
::typeToString($fieldType));
304 $where = implode(' AND ', $whereConditions);
306 switch ($queryType) {
308 $query = "SELECT $queryData FROM $table";
310 $query .= " WHERE $where";
313 $query .= " GROUP BY $groupBy";
316 $query .= " ORDER BY $orderBy";
321 $query = "UPDATE $table SET $queryData";
323 $query .= " WHERE $where";
328 $query = "DELETE FROM $table WHERE $where AND $queryData";
335 $resultDAO = CRM_Core_DAO
::executeQuery($query, $params);
344 * @param null $filter
346 static function addOrder(&$rows, $daoName, $idName, $returnURL, $filter = NULL) {
351 $ids = array_keys($rows);
352 $numIDs = count($ids);
353 array_unshift($ids, 0);
356 $lastID = $ids[$numIDs];
357 if ($firstID == $lastID) {
358 $rows[$firstID]['order'] = NULL;
361 $config = CRM_Core_Config
::singleton();
362 $imageURL = $config->userFrameworkResourceURL
. 'i/arrow';
364 $queryParams = array(
372 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$SIGNABLE_FIELDS);
373 $queryParams['_sgn'] = $signer->sign($queryParams);
374 $baseURL = CRM_Utils_System
::url('civicrm/admin/weight', $queryParams);
376 for ($i = 1; $i <= $numIDs; $i++
) {
378 $prevID = $ids[$i - 1];
379 $nextID = $ids[$i +
1];
382 $url = "{$baseURL}&src=$id";
385 $alt = ts('Move to top');
386 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$firstID}&dir=first\"><img src=\"{$imageURL}/first.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
388 $alt = ts('Move up one row');
389 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$prevID}&dir=swap\"><img src=\"{$imageURL}/up.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
392 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
393 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
397 $alt = ts('Move down one row');
398 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$nextID}&dir=swap\"><img src=\"{$imageURL}/down.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
400 $alt = ts('Move to bottom');
401 $links[] = "<a class=\"crm-weight-arrow\" href=\"{$url}&dst={$lastID}&dir=last\"><img src=\"{$imageURL}/last.gif\" title=\"$alt\" alt=\"$alt\" class=\"order-icon\"></a>";
404 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
405 $links[] = "<img src=\"{$imageURL}/spacer.gif\" class=\"order-icon\">";
407 $rows[$id]['weight'] = implode(' ', $links);
411 static function fixOrder() {
412 $signature = CRM_Utils_Request
::retrieve( '_sgn', 'String', CRM_Core_DAO
::$_nullObject);
413 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), self
::$SIGNABLE_FIELDS);
415 // Validate $_GET values b/c subsequent code reads $_GET (via CRM_Utils_Request::retrieve)
416 if (! $signer->validate($signature, $_GET)) {
417 CRM_Core_Error
::fatal('Request signature is invalid');
420 // Note: Ensure this list matches self::$SIGNABLE_FIELDS
421 $daoName = CRM_Utils_Request
::retrieve('dao', 'String', CRM_Core_DAO
::$_nullObject);
422 $id = CRM_Utils_Request
::retrieve('id', 'Integer', CRM_Core_DAO
::$_nullObject);
423 $idName = CRM_Utils_Request
::retrieve('idName', 'String', CRM_Core_DAO
::$_nullObject);
424 $url = CRM_Utils_Request
::retrieve('url', 'String', CRM_Core_DAO
::$_nullObject);
425 $filter = CRM_Utils_Request
::retrieve('filter', 'String', CRM_Core_DAO
::$_nullObject);
426 $src = CRM_Utils_Request
::retrieve('src', 'Integer', CRM_Core_DAO
::$_nullObject);
427 $dst = CRM_Utils_Request
::retrieve('dst', 'Integer', CRM_Core_DAO
::$_nullObject);
428 $dir = CRM_Utils_Request
::retrieve('dir', 'String', CRM_Core_DAO
::$_nullObject);
429 $object = new $daoName();
430 $srcWeight = CRM_Core_DAO
::getFieldValue($daoName, $src, 'weight', $idName);
431 $dstWeight = CRM_Core_DAO
::getFieldValue($daoName, $dst, 'weight', $idName);
432 if ($srcWeight == $dstWeight) {
433 self
::fixOrderOutput($url);
436 $tableName = $object->tableName();
438 $query = "UPDATE $tableName SET weight = %1 WHERE $idName = %2";
439 $params = array(1 => array($dstWeight, 'Integer'),
440 2 => array($src, 'Integer'),
442 CRM_Core_DAO
::executeQuery($query, $params);
444 if ($dir == 'swap') {
445 $params = array(1 => array($srcWeight, 'Integer'),
446 2 => array($dst, 'Integer'),
448 CRM_Core_DAO
::executeQuery($query, $params);
450 elseif ($dir == 'first') {
451 // increment the rest by one
452 $query = "UPDATE $tableName SET weight = weight + 1 WHERE $idName != %1 AND weight < %2";
454 $query .= " AND $filter";
456 $params = array(1 => array($src, 'Integer'),
457 2 => array($srcWeight, 'Integer'),
459 CRM_Core_DAO
::executeQuery($query, $params);
461 elseif ($dir == 'last') {
462 // increment the rest by one
463 $query = "UPDATE $tableName SET weight = weight - 1 WHERE $idName != %1 AND weight > %2";
465 $query .= " AND $filter";
467 $params = array(1 => array($src, 'Integer'),
468 2 => array($srcWeight, 'Integer'),
470 CRM_Core_DAO
::executeQuery($query, $params);
473 self
::fixOrderOutput($url);
479 static function fixOrderOutput($url) {
480 if (empty($_GET['snippet']) ||
$_GET['snippet'] !== 'json') {
481 CRM_Utils_System
::redirect($url);
484 CRM_Core_Page_AJAX
::returnJsonResponse(array(
485 'userContext' => $url,